From harold.fellermann at upf.edu Thu Apr 14 13:38:26 2005 From: harold.fellermann at upf.edu (harold fellermann) Date: Thu, 14 Apr 2005 19:38:26 +0200 Subject: curses for different terminals In-Reply-To: <219t51pr0he28bke65jl2c1t0k5528qa7m@4ax.com> References: <219t51pr0he28bke65jl2c1t0k5528qa7m@4ax.com> Message-ID: <74e2b8a76d1e4606961d159f14b9b37a@upf.edu> On 14.04.2005, at 19:17, Christos TZOTZIOY Georgiou wrote: > On Thu, 14 Apr 2005 18:39:14 +0200, rumours say that harold fellermann > might have written: > >> Hi all, > >> I want to use curses in a server application that provides a GUI for >> telnet clients. Therefore, I need the functionality to open and handle >> several >> screens. > > Just to make sure we understand what you want to do: > > 1. Are you doing an single process application that produces output on > many terminals? ie the program is kind of like a service? gotcha. I want to write a TCP server that handles incoming requests in threads (one thread per request using SocketServer.ThreadingTCPServer). Now, I want the server to use curses for client-server communication (client will be telnet). Thus, my programm runs in a single process (although several threads) and provides several curses screens (one for each client.) >> Concerning >> http://dickey.his.com/ncurses/ncurses-intro.html#init >> this can be done using the function newterm(type,ofp,ifp). However, >> this >> function seems not to be defined in the python library. Does anyone >> know >> how this can be done in python? > > Select one of the above, or describe more the desired situation if I > didn't cover your case, and we will try to help you more. great, thanks, - harold - -- Dieses Schreiben wurde maschinell erstellt und bedarf daher keiner Unterschrift. -- From fuzzyman at gmail.com Tue Apr 5 09:47:08 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 5 Apr 2005 06:47:08 -0700 Subject: Python Google Server In-Reply-To: <1112706994.922193.5610@z14g2000cwz.googlegroups.com> References: <1112696434.623557.97000@g14g2000cwa.googlegroups.com> <1112706994.922193.5610@z14g2000cwz.googlegroups.com> Message-ID: <1112708828.425612.75110@z14g2000cwz.googlegroups.com> Another change - change the line `dotloc = url.find('.') + 1` to `dotloc = url.rfind('.') + 1` This makes it find the last '.' in the url Best Regards, Fuzzy http://www.voidspace.org.uk/python From mehmetmutigozel at gmail.com Fri Apr 22 17:41:45 2005 From: mehmetmutigozel at gmail.com (mehmetmutigozel at gmail.com) Date: 22 Apr 2005 14:41:45 -0700 Subject: a=[ lambda t: t**n for n in range(4) ] Message-ID: <1114206105.666055.33720@g14g2000cwa.googlegroups.com> I was thinking about something like the following; >>> a=[ t**n for n in range(4) ] Traceback (most recent call last): File "", line 1, in ? NameError: name 't' is not defined >>> or >>> a=[ lambda t: t**n for n in range(4) ] >>> t=2 >>> a [ at 0x403dcc6c>, at 0x403dcca4>, at 0x403dccdc>, at 0x403dcd14>] >>> t=3 >>> a [ at 0x403dcc6c>, at 0x403dcca4>, at 0x403dccdc>, at 0x403dcd14>] >>> is something like that possible? Will you give me advice about that? From ritterhaus at yahoo.com Wed Apr 6 15:49:51 2005 From: ritterhaus at yahoo.com (ritterhaus at yahoo.com) Date: 6 Apr 2005 12:49:51 -0700 Subject: Python sleep doesn't work right in a loop? In-Reply-To: References: <1112814877.560518.229530@z14g2000cwz.googlegroups.com> Message-ID: <1112816991.860177.68420@l41g2000cwc.googlegroups.com> Nope. Does't work. Running Python 2.3.4 on Debian, Linux kernel 2.6. This is actually test code for a larger project... # flash the selected wx.TextControl for flasher in range(4): self.textField.SetBackgroundColour(255, 0, 0) time.sleep(0.8) self.textField.SetBackgroundColour(255, 255, 223) time.sleep(0.8) Even when I add an explicit call to repaint the TextCtrl between each sleep, things appear to be 'queued' until after the loop is fnished. Very bizarre. From bronger at physik.rwth-aachen.de Wed Apr 20 09:16:55 2005 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Wed, 20 Apr 2005 15:16:55 +0200 Subject: Why Python does *SLICING* the way it does?? References: <1113976729.450677.261130@o13g2000cwo.googlegroups.com> <87r7h5lk5a.fsf@wilson.rwth-aachen.de> Message-ID: <878y3doaew.fsf@wilson.rwth-aachen.de> Hall?chen! Antoon Pardon writes: > Op 2005-04-20, Torsten Bronger schreef : > >> [...] >> >> It's interesting to muse about a language that starts at "1" for >> all arrays and strings, as some more or less obsolete languages >> do. I think this is more intuitive, since most people (including >> mathematicians) start counting at "1". The reason for starting >> at "0" is easier memory address calculation, so nothing for >> really high level languages. > > Personnaly I would like to have the choice. Sometimes I prefer to > start at 0, sometimes at 1 and other times at -13 or +7. In HTBasic you have the choice between 0 and 1; there is a global source code directive for it. However, hardly anybody really wants to use HTBasic. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus From beliavsky at aol.com Thu Apr 28 13:46:47 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 28 Apr 2005 10:46:47 -0700 Subject: OOP References: <1114709684.096071.109960@l41g2000cwc.googlegroups.com> Message-ID: <1114710407.077569.43810@l41g2000cwc.googlegroups.com> demon_slayer2... at yahoo.com wrote: > Hey yall, > I'm new to Python and I love it. Now I can get most of the topics > covered with the Python tutorials I've read but the one thats just > stumping me is Object Orientation. I can't get the grasp of it. Does > anyone know of a good resource that could possibly put things in focus > for me? Maybe Part VI, "Classes and OOP", of the book "Learning Python", 2nd edition, by Lutz and Ascher. Both the motivation for OOP and its implementation in Python are discussed, in about 100 pages. From jerf at jerf.org Tue Apr 26 21:36:42 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Tue, 26 Apr 2005 21:36:42 -0400 Subject: schedule a monthly ftp event References: <1114553735.360210.290000@f14g2000cwb.googlegroups.com> Message-ID: On Tue, 26 Apr 2005 15:15:35 -0700, willitfw wrote: > Greetings, > I am looking for some guidance on a script. > > My goals are: > 1) have this script run automatically through a time set schedule. > 2) verify if a file is updated on an ftp site (usually on the 15th of > the month). > 3) If the updated file exists, ftp it to local drive. > 4) e-mail other users when the file has been updated on the local > drive. Operating system? comp.lang.python can help you with the other stuff, but the scheduling is OS-dependent. (Which isn't to say you won't get help, but it is, technically, off topic.) On UNIX, use some "cron" varient, Windows has some sort of Scheduler built in but I've never done anything with it but turn it off, and I have no clue about Mac, though perhaps it has cron too in OSX. From mirnazim at gmail.com Thu Apr 28 06:42:22 2005 From: mirnazim at gmail.com (Mir Nazim) Date: 28 Apr 2005 03:42:22 -0700 Subject: (PHP or Python) Developing something like www.tribe.net In-Reply-To: <1114665613.879362.75100@l41g2000cwc.googlegroups.com> References: <1113835147.364885.304290@l41g2000cwc.googlegroups.com> <1114503432.227799.52670@o13g2000cwo.googlegroups.com> <1114587592.260950.181990@l41g2000cwc.googlegroups.com> <1114587846.011299.125420@g14g2000cwa.googlegroups.com> <1114663336.926935.97910@f14g2000cwb.googlegroups.com> <1114665613.879362.75100@l41g2000cwc.googlegroups.com> Message-ID: <1114684942.036081.8880@o13g2000cwo.googlegroups.com> Ok I get your point. Well actually my application is small in the begining, but then may be will a large one when we want to add more features. From nde at no.spam.org Wed Apr 20 07:52:40 2005 From: nde at no.spam.org (Nick Efford) Date: Wed, 20 Apr 2005 11:52:40 +0000 (UTC) Subject: Why Python does *SLICING* the way it does?? References: <1113976729.450677.261130@o13g2000cwo.googlegroups.com> Message-ID: seberino at spawar.navy.mil wrote: > Many people I know ask why Python does slicing the way it does..... > Can anyone /please/ give me a good defense/justification??? > I'm referring to why mystring[:4] gives me > elements 0, 1, 2 and 3 but *NOT* mystring[4] (5th element). mystring[:4] can be read as "the first four characters of mystring". If it included mystring[4], you'd have to read it as "the first five characters of mystring", which wouldn't match the appearance of '4' in the slice. Given another slice like mystring[2:4], you know instantly by looking at the slice indices that this contains 4-2 = 2 characters from the original string. If the last index were included in the slice, you'd have to remember to add 1 to get the number of characters in the sliced string. It all makes perfect sense when you look at it this way! Nick From Michael.Coll-Barth at VerizonWireless.com Sat Apr 16 10:43:37 2005 From: Michael.Coll-Barth at VerizonWireless.com (Michael.Coll-Barth at VerizonWireless.com) Date: Sat, 16 Apr 2005 10:43:37 -0400 Subject: trouble to print array contents using slice operator Message-ID: <20050416144341.7FE591E4003@bag.python.org> print a[10:15] or print a[10:] -----Original Message----- From: python-list-bounces+michael.coll-barth=verizonwireless.com at python.org [mailto:python-list-bounces+michael.coll-barth=verizonwireless.com at pytho n.org]On Behalf Of praba kar Sent: Saturday, April 16, 2005 10:28 AM To: python-list at python.org Subject: trouble to print array contents using slice operator Dear all, In Php array_slice function base we can print array contents as per our desire eg) $a = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15); $arr = array_slice($a,10,10); this function will print 11,12,13,14,15 But I try to print the same thing in python using slice operator eg) print a[10:10] This statement print [] empty array. How I need to get my desired output like php array_slice function? with regards Prabahar ________________________________________________________________________ Yahoo! India Matrimony: Find your life partner online Go to: http://yahoo.shaadi.com/india-matrimony -- http://mail.python.org/mailman/listinfo/python-list ___________________________________________________________________ The information contained in this message and any attachment may be proprietary, confidential, and privileged or subject to the work product doctrine and thus protected from disclosure. If the reader of this message is not the intended recipient, or an employee or agent responsible for delivering this message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify me immediately by replying to this message and deleting it and all copies and backups thereof. Thank you. From lee at example.com Thu Apr 7 16:13:42 2005 From: lee at example.com (Lee Harr) Date: Thu, 07 Apr 2005 20:13:42 GMT Subject: Problems extracting attachment from email References: Message-ID: On 2005-04-07, foten wrote: > The problem I'm having is when I'm trying to extract the > attachement using > f=open(Filename, "wb") > f.write(msg.get_payload(decode=1)) > f.close() > Not the whole message is decoded and stored! > When only trying > f.write(msg.get_payload()) > I see that the last 255 bytes are missing. > What happens if you do... m = msg.get_payload(decode=1) f.write(m) f.write(m) f.close() ? Just wondering if maybe some buffer not being flushed properly. Maybe could replace the 2nd f.write() with an f.flush() From gsakkis at rutgers.edu Sat Apr 30 04:32:02 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 30 Apr 2005 01:32:02 -0700 Subject: Numeric/Numarray equivalent to zip ? Message-ID: <1114849922.518669.105590@l41g2000cwc.googlegroups.com> What's the fastest and most elegant equivalent of zip() in Numeric/Numarray between two equally sized 1D arrays ? That is, how to combine two (N,)-shaped arrays to one (N,2) (or (2,N)) shaped ? I expect the fastest and the most elegant idiom to be identical, as it is usually the case in this excellent library, but if not, both would be useful to know. Thanks, George From steven.bethard at gmail.com Wed Apr 13 03:23:47 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 13 Apr 2005 01:23:47 -0600 Subject: Doubt regarding sorting of a list specific field In-Reply-To: References: Message-ID: vincent wehren wrote: > "praba kar" schrieb im Newsbeitrag > news:mailman.1817.1113371391.1799.python-list at python.org... > | Dear All, > | > | I have doubt regarding sorting. I have a list > | that list have another list (eg) > | > | list = [[1234,'name1'],[2234,'name2'],[0432,'name3']] > > -> Be careful, 0432 is octal notation for 282. > | > | I want to sort only numeric value having array field. > | How I need to do for that. > > You may want use the decorate-sort-undecorate idiom. > I othere words, you isolate the index you want to sort by, > sort on the indices, than get rid of the indices again. > > Something like: > > def sortSeqOfSeqs(seq, idx): > tmp = sorted([(elem[idx], elem) for elem in seq]) > return [elem[1] for elem in tmp] Note that this is not stable: py> seq = [(1,'c'),(1,'b')] py> [tup[1] for tup in sorted((x[0], x) for x in seq)] [(1, 'b'), (1, 'c')] Which should not have reordered the list since 1 == 1. If you want a stable version, you could use: py> [tup[2] for tup in sorted((x[0], i, x) for i, x in enumerate(seq))] [(1, 'c'), (1, 'b')] But that seems pretty silly. You're already using Python 2.4 features (e.g. sorted), so you might as well use the key argument to sorted: py> sorted(seq, key=operator.itemgetter(0)) [(1, 'c'), (1, 'b')] Note if you're not using 2.4, you may want to use the decorate-sort-undecorate pattern like: py> decorated_seq = [(x[0], i, x) for i, x in enumerate(seq)] py> decorated_seq.sort() py> [tup[2] for tup in decorated_seq] [(1, 'c'), (1, 'b')] But personally, I'd just upgrade. ;) STeVe From jjl at pobox.com Fri Apr 22 16:07:41 2005 From: jjl at pobox.com (John J. Lee) Date: 22 Apr 2005 20:07:41 +0000 Subject: trying to read from dying disk References: <1114195387.535143.76860@o13g2000cwo.googlegroups.com> Message-ID: <871x92mv76.fsf@pobox.com> jdh2358 at gmail.com writes: > I have a python file that is trying to read raw data from a raw > partition on a dying dist, eg [...] > On some blocks, the read succeeds, on others it fails and an IOError is > thrown, and on others it appears to hang indefinitely and will not > respond to any attempt to kill it with 'kill -9 PID', etc. > > Is there anyway to do a timeout read on this kind of file, or even to > kill the process once it hangs? > > linux kernel 2.6.10 > python 2.4.1 This sounds like a linux kernel question much more than a Python one. Try a linux programmers' list? John From donn at drizzle.com Sat Apr 2 10:42:40 2005 From: donn at drizzle.com (Donn Cave) Date: Sat, 02 Apr 2005 15:42:40 -0000 Subject: boring the reader to death (wasRe: Lambda: the Ultimate DesignFlaw References: <424e8d1d$1@nntp0.pdx.net> Message-ID: <1112456559.835048@yasure> Quoth Scott David Daniels : | Sunnan wrote: | > ...Because what is "boring"? The opposite of dense, tense, intense. Utterly | > predictable; it's like the combination of all my prejudices. Even before | > I knew, I thought "Bet Python separates statements from expressions". | | Python is for terse, pithy prose; Python is not for poetry. That's an odd thing to say. Poetry is verbose, florid? Python is Dutch. Donn From mikin at yourmail.com Tue Apr 12 09:44:17 2005 From: mikin at yourmail.com (Mikin von Flap) Date: Tue, 12 Apr 2005 15:44:17 +0200 Subject: Extending an embeded Python Message-ID: I'm trying to embed Python in a Windows exe, and extend it with some functions in the same program. So far I only add one function: static PyObject* py_print( PyObject* self, PyObject* args ) { const char* msg; if( !PyArg_ParseTuple( args, "s", &msg ) ) return 0; EventLog::log( msg ); Py_INCREF( Py_None ); return Py_None; } static PyMethodDef StoneAgeMethods[] = { { "log", py_print, METH_VARARGS, "Print a message to the log" }, { 0, 0, 0, 0 } /* sentinel */ }; int APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE, LPSTR, int ) { EventLog::init( "con_dump.txt" ); Py_Initialize(); EventLog::log( "Python version '%s'", Py_GetVersion() ); PyObject* res0 = Py_InitModule( "stoneage", StoneAgeMethods ); res1 = PyRun_SimpleString( "stoneage.log( \"test\" )\n" ); // FAIL res2 = PyRun_SimpleString( "log( \"test\" )\n" ); // FAIL res3 = PyRun_SimpleString( "print \"test\"\n" ); // OK Py_Finalize(); } This compiles without problems, but when I run it I can't use the "log" function. Result res0 is a non-null object. As far as I can understand the "Extending and Embedding the Python Interpreter" doc, res1 should work but it doesn't! I'm a total newbie to Python, so any help appreciated :) From philippe at philippecmartin.com Wed Apr 20 13:09:59 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Wed, 20 Apr 2005 17:09:59 GMT Subject: Faster os.walk() References: <1114011606.600970.43300@l41g2000cwc.googlegroups.com> <1114016094.531694.117130@z14g2000cwz.googlegroups.com> Message-ID: How about rerouting stdout/err and 'popening" something like /bin/find -name '*' -exec a_script_or_cmd_that_does_what_i_want_with_the_file {} \; ? Regards, Philippe fuzzylollipop wrote: > du is faster than my code that does the same thing in python, it is > highly optomized at the os level. > > that said, I profiled spawning an external process to call du and over > the large number of times I need to do this it is actually slower to > execute du externally than my os.walk() implementation. > > du does not return the value I need anyway, I need files only not raw > blocks consumed which is what du returns. also I need to filter out > some files and dirs. > > after extensive profiling I found out that the way that os.walk() is > implemented it calls os.stat() on the dirs and files multiple times and > that is where all the time is going. > > I guess I need something like os.statcache() but that is deprecated, > and probably wouldn't fix my problem. I only walk the dir once and then > cache all bytes, it is the multiple calls to os.stat() that is kicked > off by the os.walk() command internally on all the isdir() and > getsize() and what not. > > just wanted to check and see if anyone had already solved this problem. From http Fri Apr 22 15:21:02 2005 From: http (Paul Rubin) Date: 22 Apr 2005 12:21:02 -0700 Subject: gui developing References: Message-ID: <7x8y3afwip.fsf@ruckus.brouhaha.com> Mage writes: > I am flirting with the idea of developing a gui app in python as a > newbie. Which module should I use? Tkinter is the most widespread and it's pretty easy to use. > I have noticed that wxpython is already installed on my gentoo and the > examples on their wiki looks easy. Is it okay or should I use wax or > something else? If wxpython already installed, then that's great. It's not preinstalled on the RH9 or FC3 systems I use, and I found it an enormous pain to install. I eventually gave up. From joal at bigpond.net.au Sat Apr 2 22:46:36 2005 From: joal at bigpond.net.au (Joal Heagney) Date: Sun, 03 Apr 2005 03:46:36 GMT Subject: Name of IDLE on Linux In-Reply-To: <8KI3e.2623$44.1361@newsread1.news.atl.earthlink.net> References: <8764z4nbv5.fsf@thomas.local> <8KI3e.2623$44.1361@newsread1.news.atl.earthlink.net> Message-ID: Edward Diener wrote: > Thomas Rast wrote: > >>Edward Diener writes: >> >> >>>It is a pity the Python Linux binary installations do not >>>create folders on the desktop or in the Gnome menu system with links >>>to the Python to the documentation and a readme telling me what >>>executables were installed. >> >>Imagine they did, and the other 1392 packages (on my system) too :-) > > > I can understand that . But I would rather have links somewhere than not > know what it was a particular package does and how to use it. As a relative > Linux newbie, I have found it disconcerting to have things installed on my > system when I first booted the system or when I install new packages or > upgrade existing ones, and not know what these packages are used for. One > can always delete links, and they are cheap, so I would rather have too much > to begin with than too little. > > >>Documentation usually resides in /usr/share/doc/, >>/usr/share/doc/packages/ or similiar. You're on an RPM-based >>system, so >> >>$ rpm -ql >> >>lists all files belonging to that package. You should have little >>trouble spotting the documentation files there. > > > Thanks. That does help. > > As a "relative linux newbie" (Aren't we all? I've been using linux for 7 years now, and the only thing that has happened is that my definition of "newbie" has stretched.), you might find the following useful. If you're using KDE, you can set a bookmark in konqueror to the documentation and it'll bring it up in the bookmark toolbar. Only hassle is when you update python and the docs, you have to edit the bookmark. Another approach is to type in /usr/share/doc/py into the konqueror URL and it'll pop up a list of folders containing python documentation. Joal PS: DON'T add a general bookmark to /usr/share/doc I did that when I was beginning, and every time I went document hunting, I'd have to wait a good minute and a half for konqueror to display all the folders in this directory. From steven.bethard at gmail.com Sat Apr 2 12:21:11 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 02 Apr 2005 10:21:11 -0700 Subject: Ternary Operator in Python In-Reply-To: <424e8e5a$1@nntp0.pdx.net> References: <20050401072442.73412.qmail@web8408.mail.in.yahoo.com> <1112391650.018826.274970@l41g2000cwc.googlegroups.com> <424e8e5a$1@nntp0.pdx.net> Message-ID: Scott David Daniels wrote: > Roy Smith wrote: > >> ... How our tools warp our thinking. > > That is what it means to be human. I can think of no better reason > for a programmer to regularly learn languages: "our tools warp our > thinking." A programmer is a professionally warped thinker. > > --Scott David Daniels > Scott.Daniels at Acm.Org +1 QOTW STeVe From mahs at telcopartners.com Tue Apr 19 19:28:07 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Tue, 19 Apr 2005 16:28:07 -0700 Subject: Array of Chars to String In-Reply-To: <42658990.7739398@news.oz.net> References: <42658990.7739398@news.oz.net> Message-ID: Bengt Richter wrote: > I think this will be worth it if your string to modify is _very_ long: > > >>> def some_func(s, letters, table=''.join([chr(i) for i in xrange(256)])): > ... return s.translate(table, > ... ''.join([chr(i) for i in xrange(256) if chr(i) not in letters])) > ... > >>> some_func("Bob Carol Ted Alice", 'adB') > 'Bad' > According to my measurements the string doesn't have to be long at all before your method is faster - cool use of str.translate: >>> def some_func(s, letters, table=''.join([chr(i) for i in xrange(256)])): ... return s.translate(table, ... ''.join([chr(i) for i in xrange(256) if chr(i) not in letters])) ... >>> some_func("Bob Carol Ted Alice", 'adB') 'Bad' >>> def func_join(s, letters): ... return "".join(letter for letter in s if letter in set(letters)) ... >>> def func_join1(s, letters): ... return "".join(letter for letter in s if letter in letters) >>> for multiplier in (1, 10, 100, 1000, 10000): ... print "List multiplier: %s" % multiplier ... print shell.timefunc(func_join, "Bob Carol Ted Alice" * multiplier, 'adB') ... print shell.timefunc(func_join1, "Bob Carol Ted Alice" * multiplier, 'adB') ... print shell.timefunc(some_func, "Bob Carol Ted Alice" * multiplier, 'adB') ... List multiplier: 1 func_join(...) 11267 iterations, 44.38usec per call func_join1(...) 38371 iterations, 13.03usec per call some_func(...) 1230 iterations, 406.69usec per call List multiplier: 10 func_join(...) 1381 iterations, 362.40usec per call func_join1(...) 7984 iterations, 62.63usec per call some_func(...) 1226 iterations, 407.94usec per call List multiplier: 100 func_join(...) 140 iterations, 3.59msec per call func_join1(...) 873 iterations, 0.57msec per call some_func(...) 1184 iterations, 422.42usec per call List multiplier: 1000 func_join(...) 15 iterations, 35.50msec per call func_join1(...) 90 iterations, 5.57msec per call some_func(...) 949 iterations, 0.53msec per call List multiplier: 10000 func_join(...) 2 iterations, 356.53msec per call func_join1(...) 9 iterations, 55.59msec per call some_func(...) 313 iterations, 1.60msec per call >>> Michael From ruses at users.snip.snip.ch Wed Apr 20 06:29:49 2005 From: ruses at users.snip.snip.ch (Maurice Caret) Date: Wed, 20 Apr 2005 12:29:49 +0200 Subject: goto statement In-Reply-To: References: <20050420092359.81900.qmail@web8409.mail.in.yahoo.com> Message-ID: <42662f0a$1_2@news.bluewin.ch> Simon Brunning a ?crit : > On 4/20/05, praba kar wrote: > >> In Python what is equivalent to goto statement > > > http://docs.python.org/tut/node6.html > > See, it's those dratted node numbers again. ;-) > other equivalents are in http://docs.python.org/tut/node10.html From fredrik at pythonware.com Tue Apr 12 02:03:36 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 12 Apr 2005 08:03:36 +0200 Subject: Best editor? References: <1112725379.514651.66540@l41g2000cwc.googlegroups.com><86k6nbww6z.fsf@guru.mired.org> <861x9gwvys.fsf@guru.mired.org> Message-ID: Mike Meyer wrote: >> Yup, that's why emacs stands for Eighty Megabytes And Constantly >> Swapping. ;-) > > Gee, it's changed from eight to eighty. Probably because eight is a > small app by todays standards. Then again, it's not like 80 is large > these days. my emacs starts in no time at all, and consumes just under 6 megs with python- mode and a couple of moderately-sized python modules in memory. that's just over 1% of the available memory on this stock hardware. guess my emacs is broken. From martin at v.loewis.de Wed Apr 20 02:30:50 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 20 Apr 2005 08:30:50 +0200 Subject: Encoding Questions In-Reply-To: <1113939785.827851.144980@l41g2000cwc.googlegroups.com> References: <1113934291.419258.314390@o13g2000cwo.googlegroups.com> <1113939785.827851.144980@l41g2000cwc.googlegroups.com> Message-ID: <4265f71a$0$17562$9b622d9e@news.freenet.de> jalil at feghhi.com wrote: > thanks for the replies. As for why I set my default encoding to utf-8 > in python, I did it a while ago and I think I did it because when I was > reading some strings from database in utf-8 it raised errors b/c there > were some chars it could recongnize in standard encoding. When I made > the change, the error didn't happen anymore. > > Does it make sense? No. If reading the strings from the database already gives an exception (i.e. without any processing of these strings), that is a bug in the database. It is also unlikely that this is what actually happened. More likely, you are reading the strings from the database, and then combining them explicitly with Unicode strings. Instead of changing the default encoding, you should tell your database adapter to return the strings as Unicode objects; if this is not supported, you should convert them to Unicode objects in the process of reading them. Regards, Martin From aahz at pythoncraft.com Mon Apr 18 12:24:54 2005 From: aahz at pythoncraft.com (Aahz) Date: 18 Apr 2005 09:24:54 -0700 Subject: Removing dictionary-keys not in a set? References: <1113824946.525441.285760@l41g2000cwc.googlegroups.com> Message-ID: In article <1113824946.525441.285760 at l41g2000cwc.googlegroups.com>, Tim N. van der Leeuw wrote: > >I'd like to remove keys from a dictionary, which are not found in a >specific set. So it's kind of an intersection-operation. Why not just use the builtin set operations? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "The joy of coding Python should be in seeing short, concise, readable classes that express a lot of action in a small amount of clear code -- not in reams of trivial code that bores the reader to death." --GvR From removethis.kartic.krishnamurthy at gmail.com Thu Apr 28 17:59:35 2005 From: removethis.kartic.krishnamurthy at gmail.com (Kartic) Date: Thu, 28 Apr 2005 21:59:35 GMT Subject: why "import wx" doesn't work? In-Reply-To: <4271560d$1_2@rain.i-cable.com> References: <427126ca$1_3@rain.i-cable.com> <4271560d$1_2@rain.i-cable.com> Message-ID: The Great 'monkey' uttered these words on 4/28/2005 5:30 PM: > It is the current version of wxPython(2.6). But follow you instruction it > still can't work... > But if using the default "from wxPython.wx import *", it work, don't know > what is the problem. May be this is an old example that cannot work with > "import wx". Because I get another example and it is ok. > I suspect you are mixing program code for the namespace version (import wx) with the old method of importing (from wxPython.wx import *). Here are two version of a very simple app... try both and see if you get any errors. And if so, _please_ post the exact error you get. --- BEGIN The "new" namespace version ---- import wx class MainFrame(wx.Frame): def __init__(self, parent, id=-1, title="Test Wx", size=(-1, -1), pos=(-1,-1), style=wx.DEFAULT_FRAME_STYLE|wx.NO_FULL_REPAINT_ON_RESIZE): wx.Frame.__init__(self, parent, id, title, size, pos, style) self.Show(True) app = wx.PySimpleApp() frame = MainFrame(None, -1, "Test Wx NameSpace Style") app.MainLoop() --- END The "new" namespace version ---- --- BEGIN The old style import ---- from wxPython.wx import * class MainFrame(wxFrame): def __init__(self, parent, id=-1, title="Test Wx", size=(-1, -1), pos=(-1,-1), style=wxDEFAULT_FRAME_STYLE|wxNO_FULL_REPAINT_ON_RESIZE): wxFrame.__init__(self, parent, id, title, size, pos, style) self.Show(True) app = wxPySimpleApp() frame = MainFrame(None, -1, "Test Wx Old Style") app.MainLoop() --- END The old style import ---- Hope that helped! Thanks, -Kartic From bill.mill at gmail.com Wed Apr 20 10:18:39 2005 From: bill.mill at gmail.com (Bill Mill) Date: Wed, 20 Apr 2005 10:18:39 -0400 Subject: Why Python does *SLICING* the way it does?? In-Reply-To: References: <1113976729.450677.261130@o13g2000cwo.googlegroups.com> <87r7h5lk5a.fsf@wilson.rwth-aachen.de> Message-ID: <797fe3d4050420071852568e03@mail.gmail.com> On 20 Apr 2005 13:39:42 GMT, Antoon Pardon wrote: > Op 2005-04-20, Bill Mill schreef : > > On 20 Apr 2005 12:52:19 GMT, Antoon Pardon wrote: > >> Op 2005-04-20, Torsten Bronger schreef : > >> > Hall?chen! > >> > > >> > nde at no.spam.org (Nick Efford) writes: > >> > > >> >> seberino at spawar.navy.mil wrote: > >> >>> Many people I know ask why Python does slicing the way it does..... > >> >> > >> >>> Can anyone /please/ give me a good defense/justification??? > >> >> > >> >>> I'm referring to why mystring[:4] gives me elements 0, 1, 2 and 3 > >> >>> but *NOT* mystring[4] (5th element). > >> >> > >> >> mystring[:4] can be read as "the first four characters of > >> >> mystring". If it included mystring[4], you'd have to read it as > >> >> "the first five characters of mystring", which wouldn't match the > >> >> appearance of '4' in the slice. > >> >> > >> >> [...] > >> >> > >> >> It all makes perfect sense when you look at it this way! > >> > > >> > Well, also in my experience every variant has its warts. You'll > >> > never avoid the "i+1" or "i-1" expressions in your indices or loops > >> > (or your mind ;). > >> > > >> > It's interesting to muse about a language that starts at "1" for all > >> > arrays and strings, as some more or less obsolete languages do. I > >> > think this is more intuitive, since most people (including > >> > mathematicians) start counting at "1". The reason for starting at > >> > "0" is easier memory address calculation, so nothing for really high > >> > level languages. > >> > >> Personnaly I would like to have the choice. Sometimes I prefer to > >> start at 0, sometimes at 1 and other times at -13 or +7. > >> > > > > -1. You can start arrays at 0 or 1 (and arbitrary bases? I don't > > recall) in VB, and it's an unmitigated disaster. It adds needless > > complexity. > > Complexity that is now put on the programmers shoulders. > > If I have a table with indexes going from -13 to +7, I have to > add the offset myself if I want to use a list for that. > > > What our slicing system loses in elegance in a few cases, > > it more than makes up for in consistency throughout all programs. > > You write this af if other solutions can't be consistent. Propose one, and I won't write it off without thinking, but my bias is way against it from experience. Knowledge gets scattered across the program, unless you're defining the start index every time you use the list, which seems no better than adding an offset to me. Peace Bill Mill bill.mill at gmail.com From WLigtenberg at gmail.com Fri Apr 22 09:56:29 2005 From: WLigtenberg at gmail.com (Willem Ligtenberg) Date: Fri, 22 Apr 2005 15:56:29 +0200 Subject: XML parsing per record References: Message-ID: As you can read in the other post of mine, my problem was with the iterating through the list. didn't know that you should do. e.text. I did only print e, not print e.text Did read documentation, but must admit not everything. Anyway, thank you very much! On Fri, 22 Apr 2005 15:47:08 +0200, Fredrik Lundh wrote: > Willem Ligtenberg wrote: > >> As I'm trying to write the code using cElementTree. >> I stumble across one problem. Sometimes there are multiple values to >> retrieve from one record for the same element. Like this: >> ATP-binding cassette, subfamily G, member 1 >> ATP-binding cassette 8 >> >> How do you get not only the first, but the rest as well, so that I can >> store it in a list. > > findall returns a list of matching elements. if "elem" is the paretnt element, > this gives you a list of the text inside all Prot-ref_name_E child elements: > > [e.text for e in elem.findall("Prot-ref_name_E")] > > (you have read the elementtree documentation, I hope?) > > From eurleif at ecritters.biz Mon Apr 25 06:23:43 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Mon, 25 Apr 2005 10:23:43 GMT Subject: HTML cleaner? In-Reply-To: References: Message-ID: Ivan Voras wrote: > Is there a HTML clean/tidy library or module written in pure python? I > found mxTidy, but it's a interface to command-line tool. > > What I'm searching is something that will accept a list of allowed tags > and/or attributes and strip the rest from HTML string. Here's a module I wrote to do something along the lines of what you want: . Unfortunately, it requires the HTML to be relatively well-formed (e.g. it doesn't like things like "foo"), so I feed the HTML into uTidyLib (another interface to HTML Tidy) first. I'm not sure why you don't want to use Tidy, but if you do change your mind, you should be able to use my module alongside Tidy to limit the HTML elements and attributes which will be accepted. From ivanlan at pauahtun.org Fri Apr 22 20:31:12 2005 From: ivanlan at pauahtun.org (Ivan Van Laningham) Date: Fri, 22 Apr 2005 18:31:12 -0600 Subject: trying to read from dying disk References: <1114195387.535143.76860@o13g2000cwo.googlegroups.com> <871x92mv76.fsf@pobox.com> <1114203696.267519.189200@o13g2000cwo.googlegroups.com> Message-ID: <42699750.567A888A@pauahtun.org> Hi All-- jdh2358 at gmail.com wrote: > > I'm currently attempting something with > > http://www.python.org/doc/current/lib/node368.html > > but it seems the read operation is ignoring these signals just as it is > ignoring my signals from the kill command -- perhaps unsurprisingly. > > Perhaps there is no hope. > Basically, if you are waiting for a hardware interrupt that never comes, you are doomed. You can escape by rebooting; in dire cases the only way out is to power down. One of the prime sources of zombie processes on unix systems is users trying to interrupt (with ^C) a process that is waiting for a hardware interrupt. Metta, Ivan ---------------------------------------------- Ivan Van Laningham God N Locomotive Works http://www.andi-holmes.com/ http://www.foretec.com/python/workshops/1998-11/proceedings.html Army Signal Corps: Cu Chi, Class of '70 Author: Teach Yourself Python in 24 Hours From reinhold-birkenfeld-nospam at wolke7.net Wed Apr 20 14:53:31 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Wed, 20 Apr 2005 20:53:31 +0200 Subject: What's the difference between these 2 statements? In-Reply-To: <70c4ec00.0504201052.30227e93@posting.google.com> References: <70c4ec00.0504201052.30227e93@posting.google.com> Message-ID: <3cnmpbF6gnlkhU1@individual.net> ATSkyWalker wrote: > What's the difference between these 2 statements? > > If you have a String s="12345" > > s[len(s)::-1] = "54321" > > But > > s[len(s):0:-1] = "5432" > > Why? What's the difference? What number then can I use as the end of > the slice if I were to supply all 3 parameters? -1. Reinhold From bokr at oz.net Thu Apr 14 02:02:05 2005 From: bokr at oz.net (Bengt Richter) Date: Thu, 14 Apr 2005 06:02:05 GMT Subject: Compute pi to base 12 using Python? References: <7x3btui27t.fsf@ruckus.brouhaha.com> Message-ID: <425e0615.339549977@news.oz.net> On 13 Apr 2005 18:20:06 -0700, Paul Rubin wrote: >Dick Moores writes: >> I need to figure out how to compute pi to base 12, to as many digits >> as possible. I found this reference, >> , but I really don't >> understand it well enough. Could someone show me how to do what I need? > >Using the GNU "bc" utility: > > $ bc -l > bc 1.06 > Copyright 1991-1994, 1997, 1998, 2000 Free Software Foundation, Inc. > This is free software with ABSOLUTELY NO WARRANTY. > For details type `warranty'. > scale = 3000 # number of output places wanted > obase = 12 # output base > print 4 * a(1) # pi = 4*arctan(1) > 3.184809493B918664573A6211BB151551A05729290A7809A492742140A60A55256A\ > 0661A03753A3AA54805646880181A3683083272BBBA0A370B12265529A828903B4B2\ > 56B8403759A71626B8A54687621849B849A8225616B442796A31737B229B23914898\ > 53943B8763725616447236B027A421AA17A38B52A18A838B01514A51144A23315A30\ > 09A8906B61B8B48A62253A88A50A43BA0944572315933664476B3AABB77583975120\ > 683526B75B462060BB03B432551913772729A2147553531793848A0402B999B50585\ > 35374465A68806716644039539A8431935198527B9399B112990ABB0383B10764542\ > 4577A51601B3624A88B7A676A3992912121A213887B92873946A61332242217AA735\ > 4115357744939112602BA4B888818A3269222B528487747839994AB223B65B876269\ > 5422822669BA00A586097842A51750362073B5A768363B21BB1A97A4A19444774939\ > 9804922175A068A46739461990A2065BB0A30BBAB7024A585B1A84428195489784A0\ > 7A331A7B0A1574565B373B05B03A5A80A13AB87857734679985558A5373178A7B282\ > 71992A3894A5776085083B9B238B2220542462888641A2BAB8B3083AB49659172A31\ > 2B78518654494A068662586A181835A64440B2970A12281397589881536720890580\ > 1032881449223841428763329617531239B9A657405584014534390B587625606BB8\ > 0923795944B43757A431B039556282978A6A49590553490BA1844947175637A90824\ > 7B50127722464441380A852B0847B5813019BB70A67663B426565434069884476132\ > 193344BA55A2128A03838974606B851B2979321A408067225A5AA4B3464A1A174735\ > 95333909AB9127079655B3164B68B9B28A9B818A220A025AB0934203995B7A62A7AA\ > 739355340539BA3182905B193905603A43B660B9426A92294697144A896A5B233935\ > 8BB2B7294BB89635B071A6351211360B820B1882AB8433B54757B87A373284B1BA18\ > 2A10326476B369A4A6365B58B8018994BB152556765475A704BB94B6B2A39458971A\ > 8B90512786B5029404818644323552916170B3ABB7363496427B088B68725A685700\ > 40617949289077B278069A09B559324B8A66828B40549B0296065B2300330592569A\ > 7B76B92BA1293585B6A9B604567A0901362856373B4B56897946256B4172B1B50474\ > 351364749A33996A81BA8847347A8411B850B79A03018291672AA0945656A159AA6A\ > A0A845531A592005B8A34366B882257107B190969A846474836A9800750778920BA7\ > 97297A2791101B0685A86BB704B9BAA17B055293679843B35215B0A8B1182B611953\ > B080AA5431B219907A8448A81B1A9493245676B88013B47033524085959415862101\ > 4216619553246570601967448B470174B9244892444817453865A4003B5AA7176451\ > AAB90681A949786154AA040477382BA69371041710B8728458A23979252B25423675\ > 3A44A1900AA283536A227648812525743868B410A567794663359A6726A528678332\ > 8135114789B7645505B047848020A730A9557B206776AA56A19682744107901306B2\ > 9008808619866B4911A05264B872A46B5376383932699531B449195640B62A636228\ > 30886247A47B3957169861239358041AA281333622AA15912B0A636047A489BB0726\ > 282A78B96671B27305A9652496B9B999011A7BA36898891665B1A6009058978850A2\ > 1B01A158A1473B84A192B8672542A2A7056581995207A436A5B3BA2824637A3112AB\ > B57176468206A071200A327B3216425148100786502AA21236ABB35499277670A126\ > 9730583403B1922A483856007301983989159BB688A58B602339806B63002A339A50\ > B0BA533B84827793913081070A32595A101803A9A20234691B1A0B623274B69B0B44\ > 688195169461059543A252BB05208720BA13118266A872B26B9B584959B44B > quit > $ > >The arctan calculation takes about 20 sec on an Athlon of around 2 ghz. That's cool. I will have to find out about bc. Thanks ;-) Interesting to note, it also took about 20 sec on my _old_ machine: >>> from time import clock >>> def foo(): ... t0 = clock() ... open('pi12by60.txt','w').write( ... ''.join(c+'\n'[:(i+1)%60==0] for i,c in enumerate(pidigits(12, 3003)))+'\n') ... print clock()-t0 ... >>> foo() 22.3866400935 That's on a 300Mhz Pentium II using the Lambert Meertens algorithm for pi ;-) Regards, Bengt Richter From peter at engcorp.com Thu Apr 14 13:38:40 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 14 Apr 2005 13:38:40 -0400 Subject: smtplib does not send to all recipients In-Reply-To: <9Y-dndpOXf1sNMPfRVn-sA@powergate.ca> References: <1113244721.415164.81290@f14g2000cwb.googlegroups.com> <1113246181.843652.158520@o13g2000cwo.googlegroups.com> <1113421803.445281.3660@l41g2000cwc.googlegroups.com> <1113487680.752215.194840@l41g2000cwc.googlegroups.com> <9Y-dndpOXf1sNMPfRVn-sA@powergate.ca> Message-ID: <9Y-dndVOXf04N8PfRVn-sA@powergate.ca> Peter Hansen wrote: > dccarson at gmail.com wrote: >> OK, I've discovered the lost messages, but I'm still slightly confused >> as to why they ended up there. The messages were being delivered to >> the local machine, box1.domain.com, even though I was addressing them >> to @domain.com. > > The address is irrelevant with SMTP. What matters is Well, that statement by itself is pretty silly... :-( I hope you got my point from the rest of the post. -Peter From mefjr75 at hotmail.com Sat Apr 23 14:01:30 2005 From: mefjr75 at hotmail.com (M.E.Farmer) Date: 23 Apr 2005 11:01:30 -0700 Subject: PDF Printing support from Python In-Reply-To: <116km8isuo9736c@corp.supernews.com> References: <1114191192.978923.268390@f14g2000cwb.googlegroups.com> <116iihncpcr5057@corp.supernews.com> <1114198703.935948.286720@o13g2000cwo.googlegroups.com> <116inf1aivjgd28@corp.supernews.com> <1114205820.773917.70820@f14g2000cwb.googlegroups.com> <116is1or7an6735@corp.supernews.com> <116km8isuo9736c@corp.supernews.com> Message-ID: <1114279290.689629.97770@z14g2000cwz.googlegroups.com> > You're use of the word "driver" is one with which I'm not > familiar. But I don't really "do windows" so it's probably a > Widnowism. It is a windowism but not exclusively ;). http://www.collaborium.org/onsite/romania/UTILS/Printing-HOWTO/winprinters.html This is the first link I found that mentioned drivers, but the last time I installed Linux-Mandrake I saw a document that went into detail about CUPS and windows printing. It seems that cups is available for windows( they also use the word driver ) http://www.cups.org/windows/index.php Ghostscript for windows available here http://www.ghostscript.com/ http://www.cs.wisc.edu/~ghost/ From kasimov at i.com.ua Sat Apr 30 11:25:31 2005 From: kasimov at i.com.ua (Maksim Kasimov) Date: Sat, 30 Apr 2005 18:25:31 +0300 Subject: large dictionary creation takes a LOT of time. In-Reply-To: <427255b4$1_3@newspeer2.tds.net> References: <1114757468.367583.210840@z14g2000cwz.googlegroups.com> <42720ccb$1_2@newspeer2.tds.net> <427255b4$1_3@newspeer2.tds.net> Message-ID: <4273A36B.5010501@i.com.ua> sorry for my question, but i've read the documentation, and can't find where is the explanation of how it is exactly works (but of course i do believe you). If it is buit in function, can i see the source code of the method to find it out? Kent Johnson wrote: > Maksim Kasimov wrote: > >> Kent Johnson wrote: >> > for line in open(path): >> the line of your example raise another question: opened file will be >> read at once time, as method readlines() do, or it will be read line >> by line as method readline() do. > > > It will be read line by line as readline() does. > >> as far i know, it is depends on implementation of method "__iter__" of >> the object that "open()" returns, so another question: where i can >> find such an information (about how does such a functions works)? > > > http://docs.python.org/lib/built-in-funcs.html > http://docs.python.org/lib/bltin-file-objects.html > > Kent -- Best regards, Maxim Kasimov mailto: kasimov at i.com.ua From dcrespo at gmail.com Mon Apr 25 11:40:27 2005 From: dcrespo at gmail.com (dcrespo) Date: 25 Apr 2005 08:40:27 -0700 Subject: cross platform printing In-Reply-To: References: <0hx4e.3479$3O2.2184@trnddc01> <1GYae.2601$Nc.903@trnddc05> <86pswjpgtt.fsf@guru.mired.org> Message-ID: <1114443627.828336.291630@f14g2000cwb.googlegroups.com> Hi Dennis... Then, what would be your solution? Print a PDF? If so, how you do that without assuming that an application is available to print it? Daniel From fredrik at pythonware.com Tue Apr 19 08:54:57 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 19 Apr 2005 14:54:57 +0200 Subject: Memory leak in python References: <20050419115818.67408.qmail@web31708.mail.mud.yahoo.com> Message-ID: "Abhishek S" wrote: > I am seeing that the python application is very slowly > eating up the memory. i need help to indentify it. what Python application? > It start with 11MB and keeps growing by 1 MB around > every 30mins. have you checked for growing lists (etc)? From prabapython at yahoo.co.in Fri Apr 8 04:24:57 2005 From: prabapython at yahoo.co.in (praba kar) Date: Fri, 8 Apr 2005 09:24:57 +0100 (BST) Subject: doubt regarding Conversion of date into timestamp In-Reply-To: 6667 Message-ID: <20050408082457.58848.qmail@web8410.mail.in.yahoo.com> Dear All, I am new to Python I want to know how to change a time into timestamp eg "Fri, 8 Apr 2005 09:22:14 +0900" like format date I want to change as a timestamp. I have used below code to get timestamp import time time.strptime(v,'%a, %d %b %Y %X +0900') function. This function will return time stamp. But If the format of date string is changed. This function raise error eg My web application always return different format of date Fri, 8 Apr 2005 10:31:37 +0530 Fri, 8 Apr 2005 10:11:03 +0900 Fri, 8 Apr 2005 09:40:47 +0800 Kindly help to resolve this problem. with regards, Prabahar ________________________________________________________________________ Yahoo! India Matrimony: Find your life partner online Go to: http://yahoo.shaadi.com/india-matrimony From steve at holdenweb.com Fri Apr 1 19:08:41 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 01 Apr 2005 19:08:41 -0500 Subject: New to programming question In-Reply-To: References: <1112325275.120122.100800@o13g2000cwo.googlegroups.com> <0_63e.19914$C7.11056@news-server.bigpond.net.au> <424d1573.11134991@news.oz.net> Message-ID: <424DE289.7070006@holdenweb.com> Joal Heagney wrote: > Bengt Richter wrote: > >> On Fri, 01 Apr 2005 07:46:41 GMT, Joal Heagney >> wrote: >> >> >>> Oh goddammmnitttt. I seem to be doing this a lot today. Look below >>> for the extra addition to the code I posted. >>> >>> Joal Heagney wrote: >>> >>>> Here's my contribution anycase: >>>> >>>> count = 0 >>>> # Get first input >>>> name = raw_input("Guess my name: ") >>>> # Give the sucker two extra goes >>>> while count < 2: >>>> # Check the value of name >>>> if name == 'Ben': >>>> print "You're right!" >>>> break >>>> else: >>>> name = raw_input("Try again: ") >>> >>> >>> # Here's the bit I missed out. >>> count += 1 >>> >>>> # Of course, we haven't checked the sucker's last guess >>>> # so we have to do that now. >>>> if count == 2: >>>> if name == 'Ben': >>>> print "You're right!" >>>> else: >>>> print "No more tries for you!!!" >>>> >>>> >>>> Hope this helps. >>>> Joal >>> >>> >>> GRRRRRRRR. >>> >> >> >> Need something more straightforward, e.g., a wrapped one-liner: >> >> >>> def guess(n=3): print ("You're right!", 'No more tries for >> you!!!')[n-1 in >> ... (x for x in xrange(n) for t in [raw_input('Guess my name: >> ')=='Ben'] >> ... if not t or iter([]).next())] > > > Okay, now in my opinion, that's just too complex to give to a newbie as > a suggested implementation. :) > > Joal I suppose this would be far too easy to understand, then: pr =['Guess my name', 'Wrong, try again', 'Last chance'] for p in pr: name = raw_input(p+": ") if name == "Ben": print "You're right!" break else: print "Loser: no more tries for you" regards Steve -- Steve Holden +1 703 861 4237 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ From fred.dixon at gmail.com Sat Apr 2 10:37:24 2005 From: fred.dixon at gmail.com (fred.dixon) Date: 2 Apr 2005 07:37:24 -0800 Subject: terminating an inactive process References: Message-ID: <1112456244.140844.161920@f14g2000cwb.googlegroups.com> i use this to open/close netscape as it also doesnt like to close all the time. its a WMI script but easiely edited. check out script-o-matic from ms-downloads , it outputs python code as well as others. ###################################################################### strComputer = "." Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2") Set colItems = objWMIService.ExecQuery("Select * from Win32_Process",,48) For Each objItem in colItems strProcess = Ucase(objItem.Name) If strProcess = "NETSCP.EXE" Then objItem.Terminate() End If Next '--------------------- MyVar = MsgBox ("Do you want to start Netscape Mail and News " & chr(13) & chr(13) & "Any Zombie processes have been exorcised from the machine already." & chr(13) & chr(13) , 308, "Warning!") Set objWMIService = Nothing Set colItems = Nothing If MyVar = 7 Then Wscript.Quit Else sExecStr = "C:\Program Files\Netscape\Netscape\Netscp.exe -mail" Dim oShell, obj Set oShell = WScript.CreateObject ("WSCript.shell") Set obj = oShell.exec(sExecStr) Set oShell = Nothing Set obj = Nothing End If '-------------------------------- MyVar = MsgBox ("Click to close Netscape") strComputer = "." Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2") Set colItems = objWMIService.ExecQuery("Select * from Win32_Process",,48) For Each objItem in colItems strProcess = Ucase(objItem.Name) If strProcess = "NETSCP.EXE" Then objItem.Terminate() End If Next Set objWMIService = Nothing Set colItems = Nothing From fabian.steels at free.fr Mon Apr 11 09:52:45 2005 From: fabian.steels at free.fr (fabian) Date: 11 Apr 2005 06:52:45 -0700 Subject: variables exist Message-ID: <9622d535.0504110552.1e070e8d@posting.google.com> how testing if a variable exists in python as isset in php?? thanks From ville at spammers.com Fri Apr 1 05:38:12 2005 From: ville at spammers.com (Ville Vainio) Date: 01 Apr 2005 13:38:12 +0300 Subject: Case-insensitive dict, non-destructive, fast, anyone? Message-ID: I need a dict (well, it would be optimal anyway) class that stores the keys as strings without coercing the case to upper or lower, but still provides fast lookup (i.e. uses hash table). >> d = CiDict([('Hi', 12),('hoho',13)]) >> d['hi'] 12 >> d.keys() ['Hi','hoho'] Note that 'Hi' preserved the case. I imagine that 'Hi' and 'hi' would need to share the same hash value in order for the lookup to be fast. Anyone have a an implementation that I could use? Quick googling only produced implementations that coerce all keys to lowercase. -- Ville Vainio http://tinyurl.com/2prnb From ksenia.marasanova at gmail.com Mon Apr 11 03:21:12 2005 From: ksenia.marasanova at gmail.com (Ksenia Marasanova) Date: Mon, 11 Apr 2005 09:21:12 +0200 Subject: templating system In-Reply-To: References: Message-ID: <130df19305041100216862c8d9@mail.gmail.com> > In EmPy, your template would look something like this:: > > > > Batch expanding the template would look like something as simple as > (substituting in your example):: > > ... > return em.expand(open(templateFilename).read(), **locals()) Thanks! I've read "Known issues and caveats" on the website: """ EmPy was primarily intended for static processing of documents, rather than dynamic use, and hence speed of processing was not the primary consideration in its design. """ Have you noticed any speed problems with EmPy? -- Ksenia From dresserd at gouldacademy.org Fri Apr 29 11:34:22 2005 From: dresserd at gouldacademy.org (dresserd at gouldacademy.org) Date: 29 Apr 2005 08:34:22 -0700 Subject: WSDL.Proxy newbie question Message-ID: <1114788862.001735.269700@g14g2000cwa.googlegroups.com> Hello, I am new to implementing and consuming web services with Python. I have had some success setting up a simple SOAPServer and connecting to it and also using some of the simpler (one parameter) web services available from xmethods.org. I am currently stuck trying to use a simple hashing service that requires more than one parameter to be passed. I have done a lot of searching and tried passing the parameters in many ways. I think I am stuck on what type of data structure to pass the service. here's the xmethod service profile http://www.xmethods.net/ve2/ViewListing.po;jsessionid=zbLKBgtAiSjIS-KAclxRipnP(QHyMHiRM)?key=uuid:FD460436-81BF-86BD-F252-2AB6C00B624C Below is an example attempt. Thanks in advance for any suggestions. Python 2.3.3 (#1, May 7 2004, 10:31:40) [GCC 3.3.3 20040412 (Red Hat Linux 3.3.3-7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import SOAPpy >>> wsdlFile = 'http://www.bs-byg.dk/hashclass.wsdl' >>> server.soapproxy.config.dumpSOAPOut =1 >>> server.soapproxy.config.dumpSOAPIn =1 >>> server.debug = 1 >>> server.HashString({'Str':'test','HashType':'MD5'}) *** Outgoing SOAP ****************************************************** MD5 test ************************************************************************ *** Incoming SOAP ****************************************************** ************************************************************************ : {} From __peter__ at web.de Tue Apr 5 09:03:55 2005 From: __peter__ at web.de (Peter Otten) Date: Tue, 05 Apr 2005 15:03:55 +0200 Subject: check interpreter version before running script References: Message-ID: rbt wrote: > Is there a recommended or 'Best Practices' way of checking the version > of python before running scripts? I have scripts that use the os.walk() > feature (introduced in 2.3) and users running 2.2 who get errors. > Instead of telling them, 'Upgrade you Python Install, I'd like to use > sys.version or some other way of checking before running. I like import os try: os.walk except AttributeError: # implement fallback No need to remember in which version the desired feature came to be. Peter From pballard at ozemail.com.au Tue Apr 5 04:34:10 2005 From: pballard at ozemail.com.au (Peter Ballard) Date: 5 Apr 2005 01:34:10 -0700 Subject: DIY Spam Filter in Python References: <9d5509fa.0504040039.526c93b6@posting.google.com> <42517cff$0$15069$636a15ce@news.free.fr> Message-ID: <9d5509fa.0504050034.458e7b71@posting.google.com> Damien Wyart wrote in message news:<42517cff$0$15069$636a15ce at news.free.fr>... > * pballard at ozemail.com.au (Peter Ballard) in comp.lang.python: > > Source code, and a bit of documentation, is at: > > http://members.ozemail.com.au/~pballard/diyspamfilter.html > > BTW, 2 of the 3 files are links, so missing from the tar archive... Sigh. Murphy's Law strikes again. The tar file is fixed now. -- Peter From mahs at telcopartners.com Mon Apr 18 23:21:37 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Mon, 18 Apr 2005 20:21:37 -0700 Subject: Proposal: an unchanging URL for Python documentation In-Reply-To: <16996.30734.778261.632448@montanaro.dyndns.org> References: <1113878396.500420.256230@g14g2000cwa.googlegroups.com> <16996.30734.778261.632448@montanaro.dyndns.org> Message-ID: Skip Montanaro wrote: > steve> I propose that an additional a URL be set up for the Python HTML > steve> documentation. This URL will always contain the current version > steve> of the documentation. Suppose we call it "current". Then (while > steve> 2.4 is still the current version) the documentation for the os > steve> module would also be available at > steve> http://python.org/doc/current/lib/module-os.html. > > Time machine at work? The above URL works for me now. > ... > > But appears to be firefox-specific. > > Skip Works for me with both Firefox and IE6 under WinXP Michael From hancock at anansispaceworks.com Sun Apr 3 19:06:18 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Sun, 3 Apr 2005 18:06:18 -0500 Subject: Help me dig my way out of nested scoping In-Reply-To: <1112562768.181026.180140@l41g2000cwc.googlegroups.com> References: <1112562768.181026.180140@l41g2000cwc.googlegroups.com> Message-ID: <200504031806.18732.hancock@anansispaceworks.com> On Sunday 03 April 2005 04:12 pm, Brendan wrote: > from ThirdPartyLibrary import F > from MyOtherModule import AB > > def FW(x): > lastX = None > aLastX = None > bLastX = None I'm pretty sure your method will work if you just specify that these are global: def FW(x): global lastX = None global aLastX = None global bLastX = None OTOH, I'm biased against using module-level variables for this kind of purpose and I think things that retain state really ought to be class instances, so I'd probably replace AB(x) with a callable object, and define two wrappers to access it (untested): class AB: def __init__(self): self._last_x = None self._last_a = None self._last_b = None def __call__(self, x): if x == self._last_x: return self._last_a, self._last_b else: self._last_a, self._last_b = self.AB(x) return self._last_a, self._last_b def A(self, x): return self(x)[0] def B(self, x): return self(x)[1] def AB(self, x): """ This is where you compute your new values when needed. """ # something that computes a and b return a,b ab = AB() Then you actually pass the methods ab.A and ab.B to your library routine. This will usually work, though if it somehow insists on an actual function instead of a callable, you can always use wrapper functions. This also has the advantage that you *can* process more than one case at a time (i.e. if you have two different places where you need this function to be called and you aren't sure what order they'll be processed (or don't want to think about it), you can give them different instances of AB to work with, and they'll remember their previous calls separately. Cheers, Terry -- -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From simon.brunning at gmail.com Mon Apr 4 08:51:23 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Mon, 4 Apr 2005 13:51:23 +0100 Subject: (win32) speedfan api control In-Reply-To: References: Message-ID: <8c7f10c6050404055148907888@mail.gmail.com> On Apr 2, 2005 3:22 AM, tlviewer wrote: (Snip Windows GUI automation stuff.) WATSUP includes a module for Windows GUI automation. It's probably worth a look - it might save you from doing all the research that I had to do! http://www.tizmoi.net/watsup/intro.html -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From kbk at shore.net Thu Apr 14 14:43:28 2005 From: kbk at shore.net (Kurt B. Kaiser) Date: Thu, 14 Apr 2005 14:43:28 -0400 (EDT) Subject: Weekly Python Patch/Bug Summary Message-ID: <200504141843.j3EIhSNw007456@bayview.thirdcreek.com> Patch / Bug Summary ___________________ Patches : 314 open ( +6) / 2824 closed ( +5) / 3138 total (+11) Bugs : 898 open (+16) / 4921 closed ( +8) / 5819 total (+24) RFE : 177 open ( +1) / 151 closed ( +0) / 328 total ( +1) New / Reopened Patches ______________________ typos in rpc.py (2005-04-09) CLOSED http://python.org/sf/1179503 opened by engelbert gruber [AST] Fix for core in test_grammar.py (2005-04-08) http://python.org/sf/1179513 opened by logistix no html file for modulefinder (2005-04-10) http://python.org/sf/1180012 opened by George Yoshida fix typos in Library Reference (2005-04-10) http://python.org/sf/1180062 opened by George Yoshida great improvement for locale.py formatting functions (2005-04-10) http://python.org/sf/1180296 opened by Georg Brandl clarify behavior of StringIO objects when preinitialized (2005-04-10) CLOSED http://python.org/sf/1180305 opened by Georg Brandl st_gen and st_birthtime support for FreeBSD (2005-04-11) http://python.org/sf/1180695 opened by Antti Louko binary formats for marshalling floats (2005-04-11) http://python.org/sf/1180995 opened by Michael Hudson make float packing copy bytes when they can (2005-04-12) http://python.org/sf/1181301 opened by Michael Hudson range() in for loops, again (2005-04-12) http://python.org/sf/1181334 opened by Armin Rigo HMAC hexdigest and general review (2005-04-13) http://python.org/sf/1182394 opened by Shane Holloway Patches Closed ______________ Complex commented (2005-04-06) http://python.org/sf/1177597 closed by loewis typos in rpc.py (2005-04-08) http://python.org/sf/1179503 closed by rhettinger clarify behavior of StringIO objects when preinitialized (2005-04-10) http://python.org/sf/1180305 closed by rhettinger Improved output for unittest failUnlessEqual (2003-04-22) http://python.org/sf/725569 closed by purcell [AST] Generator expressions (2005-03-21) http://python.org/sf/1167628 closed by bcannon New / Reopened Bugs ___________________ 256 should read 255 in operator module docs (2005-04-06) CLOSED http://python.org/sf/1178255 opened by Dan Everhart operator.isMappingType and isSequenceType on instances (2005-04-06) CLOSED http://python.org/sf/1178269 opened by Dan Everhart Erroneous line number error in Py2.4.1 (2005-04-07) http://python.org/sf/1178484 opened by Timo Linna configure: refuses setgroups (2005-04-07) http://python.org/sf/1178510 opened by zosh 2.4.1 breaks pyTTS (2005-04-07) http://python.org/sf/1178624 opened by Dieter Deyke Variable.__init__ uses self.set(), blocking specialization (2005-04-07) http://python.org/sf/1178863 opened by Emil Variable.__init__ uses self.set(), blocking specialization (2005-04-07) http://python.org/sf/1178872 opened by Emil IDLE bug - changing shortcuts (2005-04-08) http://python.org/sf/1179168 opened by Przemysław Gocyła can't import thru cygwin symlink (2005-04-08) http://python.org/sf/1179412 opened by steveward Missing def'n of equality for set elements (2005-04-09) CLOSED http://python.org/sf/1179957 opened by Skip Montanaro codecs.readline sometimes removes newline chars (2005-04-02) http://python.org/sf/1175396 reopened by doerwalter locale.format question (2005-04-10) CLOSED http://python.org/sf/1180002 opened by Andrew Ma test_posix fails on cygwin (2005-04-10) http://python.org/sf/1180147 opened by Henrik Wist subprocess.Popen fails with closed stdout (2005-04-10) http://python.org/sf/1180160 opened by neuhauser broken pyc files (2005-04-10) http://python.org/sf/1180193 opened by Armin Rigo Python keeps file references after calling close methode (2005-04-10) http://python.org/sf/1180237 opened by Eelco expanding platform module and making it work as it should (2005-04-10) http://python.org/sf/1180267 opened by Nikos Kouremenos StringIO's docs should mention overwriting of initial value (2005-04-10) CLOSED http://python.org/sf/1180392 opened by Leif K-Brooks BaseHTTPServer uses deprecated mimetools.Message (2005-04-11) http://python.org/sf/1180470 opened by Paul Jimenez lax error-checking in new-in-2.4 marshal stuff (2005-04-11) http://python.org/sf/1180997 opened by Michael Hudson Bad sys.executable value for bdist_wininst install script (2005-04-12) http://python.org/sf/1181619 opened by follower asyncore.loop() documentation (2005-04-13) http://python.org/sf/1181939 opened by Graham re.escape(s) prints wrong for chr(0) (2005-04-13) http://python.org/sf/1182603 opened by Nick Jacobson dir() does not include _ (2005-04-13) http://python.org/sf/1182614 opened by Nick Jacobson ZipFile __del__/close problem with longint/long files (2005-04-14) http://python.org/sf/1182788 opened by Robert Kiendl Bugs Closed ___________ 256 should read 255 in operator module docs (2005-04-06) http://python.org/sf/1178255 closed by rhettinger operator.isMappingType and isSequenceType on instances (2005-04-06) http://python.org/sf/1178269 closed by rhettinger GNU readline 4.2 prompt issue (2002-12-30) http://python.org/sf/660083 closed by mwh non-ascii readline input crashes python (2004-08-14) http://python.org/sf/1009263 closed by mwh readline+no threads (2003-09-24) http://python.org/sf/811844 closed by mwh compiler module didn't get updated for "class foo():pass" (2005-04-03) http://python.org/sf/1176012 closed by bcannon Missing def'n of equality for set elements (2005-04-09) http://python.org/sf/1179957 closed by rhettinger locale.format question (2005-04-10) http://python.org/sf/1180002 closed by andrewma StringIO's docs should mention overwriting of initial value/ (2005-04-10) http://python.org/sf/1180392 closed by rhettinger New / Reopened RFE __________________ making builtin exceptions more informative (2005-04-13) http://python.org/sf/1182143 opened by Sebastien de Menten From trasno-owner at ceu.fi.udc.es Mon Apr 4 16:35:31 2005 From: trasno-owner at ceu.fi.udc.es (trasno-owner at ceu.fi.udc.es) Date: Mon, 04 Apr 2005 22:35:31 +0200 Subject: Mail Delivery System Message-ID: You are not allowed to post to this mailing list, and your message has been automatically rejected. If you think that your messages are being rejected in error, contact the mailing list owner at trasno-owner at ceu.fi.udc.es. -------------- next part -------------- An embedded message was scrubbed... From: python-list at python.org Subject: Mail Delivery System Date: Mon, 4 Apr 2005 13:39:58 -0700 Size: 2848 URL: From kristian.zoerhoff at gmail.com Tue Apr 26 20:52:20 2005 From: kristian.zoerhoff at gmail.com (Kristian Zoerhoff) Date: Tue, 26 Apr 2005 19:52:20 -0500 Subject: Fwd: how to find the drive in python/cygwin? In-Reply-To: <426E9E0E.1020905@little-lisper.org> References: <1114540166.625601.50420@g14g2000cwa.googlegroups.com> <3511dc75050426113375a904e@mail.gmail.com> <426E9E0E.1020905@little-lisper.org> Message-ID: <3511dc7505042617524edd244a@mail.gmail.com> Forwarding to list, as you forgot to Reply-all (Don't worry, we all do it at least once!). ---------- Forwarded message ---------- From: Mayer Goldberg Date: Apr 26, 2005 3:01 PM Subject: Re: how to find the drive in python/cygwin? To: Kristian Zoerhoff Dear Kristian: Thanks for the very fast reply! I wasn't thinking of the mount command -- this is really the correct way to think about my problem. >>My program needs to run on an external media that comes with Cygwin on >>it. I have no control over what drive is assigned to that media, but >>for some reason, I do need to know the letter. > > Why? Basically this has to do with moving around: I use different computers throughout the day, and need to carry with me a sane and productive computing environment. Rebooting to linux is not an option for me, so I need a Windows solution. I found it in the form of a 40G pocket hard drive with a USB connection. I plug in the connection, go to my software subdirectory and run what I need. I have a mixture of Unix and Windows programs, and often I have to run a Windows program instead of a unix program (for example, I run miktex instead of the tetex that comes with cygwin). The Windows utilities need to be passed arguments in DOS format, i.e., something like G:\FOO\foo.dll. Cygwin is only one specific application I use, so I didn't install everything under the / (which would have solved many problems for me!). As a result, I need to know the drive letter. Thanks again, Mayer -- Kristian kristian.zoerhoff(AT)gmail.com zoerhoff(AT)freeshell.org From theaney at cablespeed.com Mon Apr 25 22:00:29 2005 From: theaney at cablespeed.com (Tim Heaney) Date: Mon, 25 Apr 2005 22:00:29 -0400 Subject: Quote-aware string splitting References: <9Kgbe.24031$h6.523@tornado.texas.rr.com> Message-ID: <87oec2e1qa.fsf@mrbun.watterson> "J. W. McCall" writes: > > I need to split a string as per string.strip(), but with a > modification: I want it to recognize quoted strings and return them as > one list item, regardless of any whitespace within the quoted string. > > For example, given the string: > > 'spam "the life of brian" 42' > > I'd want it to return: > > ['spam', 'the life of brian', '42'] > > I see no standard library function to do this, so what would be the > most simple way to achieve this? This should be simple, but I must be > tired as I'm not currently able to think of an elegant way to do this. > > Any ideas? How about the csv module? It seems like it might be overkill, but it does already handle that sort of quoting >>> import csv >>> csv.reader(['spam "the life of brian" 42'], delimiter=' ').next() ['spam', 'the life of brian', '42'] From gh at ghaering.de Mon Apr 4 19:39:03 2005 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Tue, 05 Apr 2005 01:39:03 +0200 Subject: change extensions In-Reply-To: <4251cef9@dnews.tpgi.com.au> References: <4251cef9@dnews.tpgi.com.au> Message-ID: <4251D017.2040808@ghaering.de> Bob Then wrote: > how can i change all files from one extension to another within a direcory? Using os.listdir, os.path.split and os.rename. -- Gerhard From prabapython at yahoo.co.in Fri Apr 22 03:35:33 2005 From: prabapython at yahoo.co.in (praba kar) Date: Fri, 22 Apr 2005 08:35:33 +0100 (BST) Subject: regarding system function In-Reply-To: 6667 Message-ID: <20050422073533.28224.qmail@web8408.mail.in.yahoo.com> --- Robert Kern wrote: > praba kar wrote: > > Dear All, > > > > In Php If I send a command to system function > > then It will return 1 on success and 0 on failure. > So > > based upon that value I can to further work. > > > > But In Python If I send a command to system > > function then It will return 0 only for both > > conditions(success and failure). > > Are you sure about that? > > In [3]:os.system('cat foo') > cat: foo: No such file or directory > Out[3]:256 > I agree above statement but When I delete a directory os.system('rm -rf test') 0 if directory is not present then I again try to delete os.system('rm -rf test') now this time also It will print 0 ________________________________________________________________________ Yahoo! India Matrimony: Find your life partner online Go to: http://yahoo.shaadi.com/india-matrimony From viznut at charter.net Mon Apr 25 23:27:10 2005 From: viznut at charter.net (Randall Hopper) Date: Mon, 25 Apr 2005 22:27:10 -0500 Subject: Python callbacks & PyGILState_Release() In-Reply-To: References: Message-ID: <20050426032710.GB13345@charter.net> David E. Konerding DSD staff: |Randall Hopper wrote: |> Is there a clean way to save the full exception state in the callback |> before the PyGILState_Release(), and restore it when we return across the |> C++ wrapper? ... |I saved the exception state by retrieveing it from sys.exc_info(), which |contains all the traceback object data as Python variable. I think you can |get the same info from your C++ callback wrapper, and use PyErr_Fetch and |PyErr_Restore to save and restore the exception sate. Ok, thanks. I'll give this a shot! Randy From robin at reportlab.com Mon Apr 25 11:55:57 2005 From: robin at reportlab.com (Robin Becker) Date: Mon, 25 Apr 2005 16:55:57 +0100 Subject: regex over files In-Reply-To: <426D08BC.1040703@klix.ch> References: <426D0659.7080307@chamonix.reportlab.co.uk> <426D08BC.1040703@klix.ch> Message-ID: <426D130D.6040400@chamonix.reportlab.co.uk> Gerald Klix wrote: > Map the file into RAM by using the mmap module. > The file's contents than is availabel as a seachable string. > that's a good idea, but I wonder if it actually saves on memory? I just tried regexing through a 25Mb file and end up with 40Mb as working set (it rose linearly as the loop progessed through the file). Am I actually saving anything by not letting normal vm do its thing? > HTH, > Gerald > > Robin Becker schrieb: > >> Is there any way to get regexes to work on non-string/unicode objects. >> I would like to split large files by regex and it seems relatively >> hard to do so without having the whole file in memory. Even with >> buffers it seems hard to get regexes to indicate that they failed >> because of buffer termination and getting a partial match to be >> resumable seems out of the question. >> >> What interface does re actually need for its src objects? > > -- Robin Becker From claird at lairds.us Mon Apr 4 13:08:03 2005 From: claird at lairds.us (Cameron Laird) Date: Mon, 04 Apr 2005 17:08:03 GMT Subject: Sending keytrokes to Windows app References: <42511F4B.40702@btk.utu.fi> Message-ID: In article , Simon Brunning wrote: >On Apr 4, 2005 12:04 PM, Marten Hedman wrote: >> I am trying to control a Windows application from a python script with >> SendKeys and Python 2.3. > >WATSUP might be worth a look, instead... > >http://www.tizmoi.net/watsup/intro.html . . . More references: . From casevh at comcast.net Fri Apr 1 12:14:01 2005 From: casevh at comcast.net (casevh at comcast.net) Date: 1 Apr 2005 09:14:01 -0800 Subject: ANN: BigDecimal - decimal arithmetic on very large intergers References: <032720052340.23979.42474457000403FA00005DAB220699973508900A9C0E0C@comcast.net> Message-ID: <1112375640.957543.282190@z14g2000cwz.googlegroups.com> M.-A. Lemburg wrote: > casevh at comcast.net wrote: > > BigDecimal is a Python class that supports decimal arithmetic on very large integers. BigDecimal was inspired by the posting of BigDec to c.l.py by Tim Peters. BigDecimal implements all the commonly used integer methods. (It doesn't implement any of the binary/shifting operations.) > > > > It has been optimized for performance. It uses a 4x4 Toom-Cook algorithm for multiplication and a new, very fast, division algorithm. If GMPY is available, it will be automatically used. > > > > Performance examples, computing the decimal represendation of the 42nd Mersenne prime: > > 2**25964951 - 1 > > > > Tim Peter's posting to c.l.py: 13 minutes 41 seconds > > BigDecimal: 59 seconds > > BigDecimal w/gmpy: 10 seconds > > You might want to look into mxNumber (part of the egenix-mx-experimental > package): > > http://www.egenix.com/files/python/mxNumber.html > > There's a C type called Integer in that package that basically > wraps the GMP integer type. > > -- > Marc-Andre Lemburg > eGenix.com > > Professional Python Services directly from the Source (#1, Apr 01 2005) > >>> Python/Zope Consulting and Support ... http://www.egenix.com/ > >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ > >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ > ________________________________________________________________________ > > ::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,FreeBSD for free ! :::: I have used mxNumber in the past. This library uses "super" digits with hundreds / thousands of decimal digits and then builds builds multiplication and division on those. The original motivation was that the conversion time to / from decimal string format is O(n) instead of O(n^2). Using just native Python long support, the 4-way Toom-Cook multiplication algorithm is faster than the built-in multiplication when the numbers are several hundred thousand digits long. On my machine, it is roughly twice as fast when multiplying one million digit numbers. (The 4-way Toom-Cook is O(n^~1.4) versus O(n^~1.585) for the Karatsuba multiplication in Python.) The division algortihm in BigDecimal is effectively O(n^~1.4) also. Using just native Python long support, the division algorithm is faster than the built-in division algorithm when the numbers are several tens of thousands digits long. Interestingly, BigDecimal can do division faster than GMP 3.1.x with numbers approximately 10 million digits in length. BigDecimal is faster than GMP 4.1.4 with numbers of approximately 1 million digits in length. (GMP 4 is faster for small, ~10,000 digits, than GMP 3, but grows more quickly.) casevh From wnebfynj at mnovryyb.pbz Tue Apr 12 09:17:07 2005 From: wnebfynj at mnovryyb.pbz (JZ) Date: Tue, 12 Apr 2005 15:17:07 +0200 Subject: os.open() i flaga lock References: <12ff5c7es4cwa$.1fpe48svo59a1$.dlg@40tude.net> Message-ID: <9se17ni2zulz.1tvoh66h4ipkp$.dlg@40tude.net> Dnia Tue, 12 Apr 2005 15:14:25 +0200, JZ napisa?(a): > Szukam jakiego? odpowiednika fcntl na win32. W manualu napisali ?e > os.open() z odpowiedni? flag? jest bardziej uniwersalne od fcntl. Niestety > zero informacji na temat tej flagi oraz brak jakiegokolwiek przyk?adu... :( Sorry, I wanted to send to another group. because I cannot remove the post, I provide simple translation: I am looking for function similar ro fcnt but for win32. I've found brief info in manual about os.open() which should work with specific flag value. But I cannot find any info abotu that flag and no examples at all. :( -- JZ From jeffrey at fro.man Sun Apr 17 02:28:13 2005 From: jeffrey at fro.man (Jeffrey Froman) Date: Sat, 16 Apr 2005 23:28:13 -0700 Subject: Decorator Syntax For Recursive Properties Message-ID: <11640g942e65da1@corp.supernews.com> Consider the following class: class Node(object): def __init__(self, name, parent=None): self.name = name self.parent = parent def _ancestors(self, ants=None): if ants is None: ants = [] else: ants.insert(0, self.name) if self.parent is None: return ants return self.parent._ancestors(ants) ancestors = property(_ancestors) The ancestor property generates a list ancestor nodes by having each parent examine its own name recursively. The recursion is managed by calling the method underlying the parent property, rather than calling the property directly. Is it possible to rewrite this property using decorator syntax? Does the @property decorator create some underlying method that I can call directly? Alternately, perhaps there is a way to rewrite the recursion so that such a call is unnecessary? Note that the property should not add its own name if it is the originating node (the node trying to find _its_ ancestors). So something like this didn't work for me: @property def ancestors(self): if self.parent is None: return [self.name] return [self.name] + self.parent.ancestors In other words, since there is no longer a list passing from child to parent during the recursion, is there a graceful way to examine the state of the ancestor list so far? Thanks, Jeffrey From tores at stud.cs.uit.no Wed Apr 20 11:20:26 2005 From: tores at stud.cs.uit.no (Tor Erik Sønvisen) Date: Wed, 20 Apr 2005 17:20:26 +0200 Subject: logging to two files Message-ID: Hi Have the following code: import logging logging.basicConfig(level = logging.DEBUG, format = '[%(levelname)-8s %(asctime)s] %(message)s', filename = 'rfs.log', filemode = 'w') When using logging.(debug, info etc) stuff is logged to rfs.log. How may I specify another log with different charateristics, such as a different file regards From perle at cs.tu-berlin.de Thu Apr 7 13:50:07 2005 From: perle at cs.tu-berlin.de (Frank Wilde) Date: 7 Apr 2005 17:50:07 GMT Subject: Lambda: the Ultimate Design Flaw References: <1498066.d23UzBfE8y@yahoo.com> <3b5ui7F6h0vgtU1@individual.net> Message-ID: Ulrich Hobelmann wrote: > alex goldman wrote: >> I personally think GOTO was unduly criticized by Dijkstra. With the >> benefit of hindsight, we can see that giving up GOTO in favor of >> other primitives failed to solve the decades-old software crisis. > The fault of goto in imperative languages is that it has no > arguments, thus creating spaghetti of gotos and assignments. > > Continuations rule! While continuations are a very interesting abstraction, the improvement of structured programming was to be able to prove properties of your programs in time linear to the size of the program instead of quadratic. I don't see how giving arguments to the GOTO would help there. Ciao, Perle From newsgroups at jhrothjr.com Thu Apr 21 22:31:47 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 21 Apr 2005 21:31:47 -0500 Subject: deprecation of has_key? References: <1114069715.945176.73750@l41g2000cwc.googlegroups.com> <426775C8.3000303@holdenweb.com> Message-ID: <116gojl7je5jq10@news.supernews.com> "Terry Reedy" wrote in message news:mailman.2254.1114121746.1799.python-list at python.org... > > "Steven Bethard" wrote in message > news:dfWdnZdcUZbqX_rfRVn-vw at comcast.com... >> Ahh, ok. Now I understand. I think you could probably search the >> python-dev archives and see why the decision was made as it was. For >> pretty much all my purposes, "key in dict" is much more useful than "item >> in dict". Practicality beats Purity and all. ;) > > In '[for] x in mydict:', x could potentially be key, value, or item-pair. > All three were considered and discussed -- I believe on clp-- and key > chosen as the most useful. A specific analogy brought forth was the phone > book, a mapping of names to phone number and maybe address. The decision > was definite closer to a coin-toss to a no-brainer. I actually use the item-pair more frequently, but it's not something that concerns me overmuch. I don't really worry about a few extra keystrokes; just a whole lot of extra keystrokes. John Roth > > Terry J. Reedy > > > From kay.schluehr at gmx.net Sat Apr 30 12:24:52 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 30 Apr 2005 09:24:52 -0700 Subject: New Python website In-Reply-To: <1114735502.510591.6360@f14g2000cwb.googlegroups.com> References: <1114735502.510591.6360@f14g2000cwb.googlegroups.com> Message-ID: <1114878292.384982.272050@o13g2000cwo.googlegroups.com> lpe wrote: > http://www.pycode.com > > I was kinda suprised when I could not find any good sites with 3rd > party modules (other than the Vaults of Parnassus, where you must host > files elsewhere), so I decided to write one myself :) Maybe You shot a bit fast? PiPy is good and the Vaults are good. Link them makes them better, though not very innovative. Someone told me that I'm on the Web here, am I? > It is brand new and might still be buggy, but hopefully it will be > usefull to some people. Feel free to join and upload any of your code. > thanks When I was younger I found anarchy cool. Now I find it grey. Ciao, Kay From reinhold-birkenfeld-nospam at wolke7.net Sun Apr 17 09:25:04 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Sun, 17 Apr 2005 15:25:04 +0200 Subject: pre-PEP: Suite-Based Keywords In-Reply-To: <4261c943.136032804@news.oz.net> References: <3cc186F6lodv5U1@individual.net> <4261c943.136032804@news.oz.net> Message-ID: <3cf2qfF6jo33oU1@individual.net> Bengt Richter wrote: > Stretching for it, using my latest and greatest ;-) > > y = f(**:: > x = 1 > y = 'y for f' > )*g(**:: > x = 'x for g' > y = 'y for g' > def foo(): return 'foo for g' > ) > > Note that there is no problem adding other parameters, because :: is just > a unary expression returning dict subtype instance, e.g., > > y = f(11,22,**:: > x = 1 > y = 'y for f' > )*g(*args_from_somewhere, **:: > x = 'x for g' > y = 'y for g' > def foo(): return 'foo for g' > ) You know that this is dead ugly? The real ``problem'' (if you see one) is that the indentation syntax doesn't allow for suites in expressions. Reinhold From enleverlesO.OmcO at OmclaveauO.com Tue Apr 26 01:55:54 2005 From: enleverlesO.OmcO at OmclaveauO.com (Do Re Mi chel La Si Do) Date: Tue, 26 Apr 2005 07:55:54 +0200 Subject: Import DiscID on Windows References: Message-ID: <426dd9d4$0$814$8fcfb975@news.wanadoo.fr> Hi ! Look ctypes, for call the DLLs @-salutations -- Michel Claveau From martin at v.loewis.de Sat Apr 16 12:58:21 2005 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Sat, 16 Apr 2005 18:58:21 +0200 Subject: unicode "em space" in regex In-Reply-To: <1113652436.971442.311570@z14g2000cwz.googlegroups.com> References: <1113652436.971442.311570@z14g2000cwz.googlegroups.com> Message-ID: <4261442D.1010800@v.loewis.de> Xah Lee wrote: > how to represent the unicode "em space" in regex? You will have to pass a Unicode literal as the regular expression, e.g. fracture=re.split(u'\u2003*\\|\u2003*',myline,re.U) Notice that, in raw Unicode literals, you can still use \u to escape characters, e.g. fracture=re.split(ur'\u2003*\|\u2003*',myline,re.U) Regards, Martin From robin at SPAMREMOVEjessikat.fsnet.co.uk Tue Apr 26 16:54:53 2005 From: robin at SPAMREMOVEjessikat.fsnet.co.uk (Robin Becker) Date: Tue, 26 Apr 2005 20:54:53 +0000 Subject: regex over files In-Reply-To: References: <426D0659.7080307@chamonix.reportlab.co.uk> <426D08BC.1040703@klix.ch> <426E021E.8000809@jessikat.fsnet.co.uk> <17006.31984.182979.430076@montanaro.dyndns.org> <426E893D.2070905@chamonix.reportlab.co.uk> Message-ID: <426EAA9D.2050904@jessikat.fsnet.co.uk> Skip Montanaro wrote: ... > If I mmap() a file, it's not slurped into main memory immediately, though as > you pointed out, it's charged to my process's virtual memory. As I access > bits of the file's contents, it will page in only what's necessary. If I > mmap() a huge file, then print out a few bytes from the middle, only the > page containing the interesting bytes is actually copied into physical > memory. .... my simple rather stupid experiment indicates that windows mmap at least will reserve 25Mb of paged file for a linear scan through a 25Mb file. I probably only need 4096b to scan. That's a lot less than even the page table requirement. This isn't rocket science just an old style observation. -- Robin Becker From bill.oldroyd at bl.uk Fri Apr 1 11:58:30 2005 From: bill.oldroyd at bl.uk (bill.oldroyd at bl.uk) Date: 1 Apr 2005 08:58:30 -0800 Subject: Shelve DBRunRecoveryError Message-ID: <1112374710.796497.14280@o13g2000cwo.googlegroups.com> Can anyone help with this error message when using Shelve : Python 2.4. Traceback (most recent call last): File "C:\Python24\CollectB\dataparser.py", line 743, in -toplevel- base.create() File "C:\Python24\CollectB\dataparser.py", line 252, in create self.dataStore[i] = v File "C:\Python24\lib\shelve.py", line 130, in __setitem__ self.dict[key] = f.getvalue() File "C:\Python24\lib\bsddb\__init__.py", line 218, in __setitem__ self.db[key] = value DBRunRecoveryError: (-30978, 'DB_RUNRECOVERY: Fatal error, run database recovery -- PANIC: Invalid argument') Bill From Facundo.Batista at telefonicamoviles.com.ar Mon Apr 11 12:43:01 2005 From: Facundo.Batista at telefonicamoviles.com.ar (Batista, Facundo) Date: Mon, 11 Apr 2005 13:43:01 -0300 Subject: ANNOUNCE: SiGeFi v0.3.1 Message-ID: We're proud to announce the 0.3.1 version of SiGeFi, which you can find at: http://sourceforge.net/projects/sigefi What is SiGeFi? --------------- SiGeFi is a Financial Management System, with focus in the needs of the administration of the money in each personal life and house. Always keeping the easy usage and concepts, SiGeFi has features of a complex Management system: - Complies with Double Entry Accounting - Has a Budget-based Money Distribution system - Allow to make Loans between accounts (with associated financial costs) And of course, it's completely written in Python (didn't decided the GUI yet). What is in this version? ------------------------ GUI: - Main window, with the full menu structure. - Opening of a database and accounts' tree loading. Internal changes: - Specified the start-up procedure. - Implemented consistency controls in the Persistence layer. - Bugfixing (mainly with exchange rates constraints). Created a "demo" application that shows how to work with the core by hand, useful as documentation, and allows to create datasets for GUI testing. See roadmap.txt to find out the milestone for each version, and TODO.txt for more detail. Be aware that most of the documentation is not translated yet, it's only in Spanish. What can I expect for the next version? --------------------------------------- More work in the GUI: - Finish the main windows, the interaction core of the program. - Add shortcuts. - Integrate a toolbar. How can I help? --------------- In a thousand ways, there's a lot of things to do: documentation, fixing code, translations, set up the web page, etc... If you want to participate, send us a mail to the list (sigefi-list at lists.sourceforge.net) or directly to us. Thank you. . Facundo Bit?cora De Vuelo: http://www.taniquetil.com.ar/plog PyAr - Python Argentina: http://pyar.decode.com.ar/ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA. La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From jelleferinga at gmail.com Tue Apr 26 17:21:22 2005 From: jelleferinga at gmail.com (jelle) Date: 26 Apr 2005 14:21:22 -0700 Subject: how to pass an array to a VB array via COM In-Reply-To: <8y358mqj.fsf@python.net> References: <1114515084.138728.26180@g14g2000cwa.googlegroups.com> <8y358mqj.fsf@python.net> Message-ID: <1114550482.213271.103030@z14g2000cwz.googlegroups.com> Thomas, No, i went over the syntax extensively. The syntax is RS.AddCurve(points, degree), so 3 represents the degree of a bezier curve. I'm doing fine with all types of functions which use 2 x,y,z coords, but all arrays -tuple of tuples- fail. The odd thing is that when i use RS.GetPoints() which is a method to get back user-defines x,y,z points, i get a tuple of tuples containing these points. Though when i write these back to the program, all fails: I admit posting this problem also to the more specific python-win32 group, though no response there yet... >>>s = RS.GetPoints() >>>s ((-7.0, -30.0, 0.0), (15.0, -24.0, 0.0), (-7.0, 12.0, 0.0), (14.0, 29.0, 0.0), (28.0, 10.0, 0.0), (20.0, 1.0, 0.0)) Cool, I get to choose points in the GUI, right back into python, wicked! Though when I send these points back to the app: RS.AddPolyline(s) The same error all over again: --- Traceback (most recent call last): File " ", line 1, in ? File "c:\Python23\lib\site-packages\jf\interface\RhinoScript.py", line 129, in AddPolyline return self._ApplyTypes_(85, 1, (12, 0), ((12, 0),), 'AddPolyline', None,vaPoints) File "c:\Python23\lib\site-packages\win32com\client\__init__.py", line 446, in _ApplyTypes_ return self._get_good_object_( com_error: (-2147352567, 'Exception occurred.', (6, 'RhinoScript_m', 'Type mismatch in parameter. One-dimensional array required.', 'C:\\Program Files\\Rhinoceros 3.0\\RhinoScript_m.HLP', 393222, 0), None) --- From simon.brunning at gmail.com Tue Apr 19 11:58:31 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Tue, 19 Apr 2005 16:58:31 +0100 Subject: [Python-Dev] How do you get yesterday from a time object In-Reply-To: <20050419153446.30407.qmail@web60116.mail.yahoo.com> References: <20050419153446.30407.qmail@web60116.mail.yahoo.com> Message-ID: <8c7f10c6050419085830e4e7cc@mail.gmail.com> On 4/19/05, Ralph Hilton wrote: > i'm a beginning python programmer. > > I want to get the date for yesterday > > nowTime = time.localtime(time.time()) > print nowTime. > oneDay = 60*60*24 # number seconds in a day > yday = nowTime - oneDay # <-- generates an error > print yday.strftime("%Y-%m-%d") today = datetime.date.today() previous_working = today - datetime.timedelta(days=1) -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From ajikoe at gmail.com Wed Apr 6 05:29:40 2005 From: ajikoe at gmail.com (ajikoe at gmail.com) Date: 6 Apr 2005 02:29:40 -0700 Subject: Establishing connection SSH Message-ID: <1112779780.058547.270960@o13g2000cwo.googlegroups.com> Hello all, I have one computer and 1 server. I have login and password. The only way I can connect to server is using SSH protocol. I usually use Winscp3 to connect to the server (by providing login and password). Now I would like to connect to the server directly using python code. How can I establish connection ? Can I run something in the server and take the result back? Sincerely Yours, Pujo From __peter__ at web.de Tue Apr 5 08:59:08 2005 From: __peter__ at web.de (Peter Otten) Date: Tue, 05 Apr 2005 14:59:08 +0200 Subject: copying a file in the python script References: <1112678460.464474.82610@z14g2000cwz.googlegroups.com> <2ZadndRAcawiGs_fRVn-ig@comcast.com> Message-ID: Larry Bates wrote: > If you are moving the file to another directory on the same hard > drive (e.g. same filesystem) you can use os.rename(old, new) and > the file doesn't have to be copied at all. This is more efficient. > If you are copying to another filesystem, you must use shutil.copy > and os.remove (or os.unlink). Or use shutil.move() which implements the strategy you describe. Peter From fdreger at amiga.pl Sat Apr 23 17:30:24 2005 From: fdreger at amiga.pl (Filip Dreger) Date: Sat, 23 Apr 2005 23:30:24 +0200 Subject: func_code vs. string problem References: Message-ID: Uzytkownik "Steven Bethard" napisal w wiadomosci news:QvKdnZAEj5TEKfffRVn-oQ at comcast.com... > Filip Dreger wrote: >> I am trying to find a way of executing functions without creating a >> nested scope, so they can share local and global namespace (even if >> they are declared in some other module). > > Why? Can you explain what the use case is? I have a large set of objects of a single class - 'actor'. They are created all at once, and they all live in a sort of container written in C. The methods of the functions are few and general. One of them is simply 'act()', that is called by the C program every X seconds (tics, whatever). Each object can play 0..N roles, and the roles played by an object often change during its lifetime. The roles should be played in the act() method. Also, the roles should be defined in some simple way, and in an external python file (so adding/removing roles does not require recompiling of the parts embedded in C). If I had a magic function 'exec in current scope' I would implement it like this: class actor: def __init__(): self.roles=[] def act(): for i in self.roles: exec i in current scope then the roles would simply be functions defined in any importable file. For example creating an actor that logs each time it is called would be as simple as: import actor def log(): self.counter+=1 print "called %d times"%self.counter a=actor.actor() a.counter=0 a.roles.append(log) Let me recapitulate (is that the right English word?): 1. I need to keep the definitions of roles in a separate file (they can not simply be additional methods) 2. I need the roles to have full access to global and local namespace of the actor object (sometimes they have to change it, and sometimes they have to use some external modules) - the roles should work like plugins. 3. I guess I also need a fresh look at the problem. Maybe I am simply going the wrong way? I am more than willing to change my design, if someone shows me the light :-) regards, Filip Dreger From gabriel.barros at gmail.com Mon Apr 11 09:05:49 2005 From: gabriel.barros at gmail.com (Gabriel B.) Date: Mon, 11 Apr 2005 10:05:49 -0300 Subject: workaround for generating gui tools In-Reply-To: <4259c2ed.60213392@news.oz.net> References: <1113061810.530359.172720@g14g2000cwa.googlegroups.com> <3bqgh6F6larilU1@individual.net> <4259c2ed.60213392@news.oz.net> Message-ID: <5175a81c050411060515786e54@mail.gmail.com> On Apr 10, 2005 11:08 PM, Bengt Richter wrote: > On Sat, 9 Apr 2005 19:22:16 +0200, "Fredrik Lundh" wrote: > open('mywidget_v2.txt','w').write(repr(mywidget.textview) How about a pickle hook? You'd just unpack the pickle data, and end up with a pointer to a frame(?) containing all the goods, then just .pack() it into whatever you want. From donmcdaniel2005 at yahoo.com Fri Apr 29 10:49:39 2005 From: donmcdaniel2005 at yahoo.com (Donald L McDaniel) Date: Fri, 29 Apr 2005 07:49:39 -0700 Subject: Ron Grossi: God is not a man References: <1114098221.580669.86300@g14g2000cwa.googlegroups.com> <1114127633.859113.292290@l41g2000cwc.googlegroups.com> <#2tJ0r3RFHA.3664@TK2MSFTNGP15.phx.gbl> <1114328806.147822.64660@z14g2000cwz.googlegroups.com> <1114329202.229148.82550@o13g2000cwo.googlegroups.com> <1114654290.690332.155200@f14g2000cwb.googlegroups.com> <3dc8hjF6s5i2uU1@individual.net> <3desu2F6qoj7aU1@individual.net> Message-ID: <#ATbpqMTFHA.3980@TK2MSFTNGP12.phx.gbl> MC05 wrote: > "sheltech" wrote in message > news:FEpce.1407$7F4.136 at newsread2.news.atl.earthlink.net... >> >> "MC05" wrote in message >> news:3dc8hjF6s5i2uU1 at individual.net... >>> >>> "Donald L McDaniel" wrote in message >>> news:ueXTQC8SFHA.3184 at TK2MSFTNGP15.phx.gbl... >>>> >>>> 4) I doubt seriously whether God plays a guitar, since guitars are >>>> made by men, for men. His Son could theoretically play a guitar. >>>> Perhaps He does. Perhaps He doesn't. Only the Father and His Holy >>>> Angels know. >>> >>> So then Lucifer was a wicked bass player whose sex and drugs and >>> rock n roll alientated the rest of the band and was fired? >>> >>> >>> >> >> "Fired" .... good one > > Heh. Can't take credit for an accident. Your eye is better than > mine. :) The Devil has been fired...by God Himself. Read the Book of Revelation in the New Testament: Satan's end is clearly outlined by the Angel Jesus sent to St. John. This end is very clear: he will be cast alive into the Lake which burns with fire and brimstone, where he will be tormented day and night forever. Not only Satan and his angels will be cast into the Lake, but all those who follow him and his servants. I assure you, Satan won't be ruling anyone in the Fire. He will be in just as much torment as his followers. Neither will he have any sort of job. I strongly advise you to stop making fun of things you have no understanding of. Your eternal destiny depends on the way you treat others. -- Donald L McDaniel Please reply to the original thread, so that the thread may be kept intact. ============================== From steven.bethard at gmail.com Wed Apr 13 03:13:40 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 13 Apr 2005 01:13:40 -0600 Subject: Doubt regarding sorting of a list specific field In-Reply-To: References: Message-ID: <6omdnTAhJfc-W8HfRVn-oQ@comcast.com> praba kar wrote: > I have doubt regarding sorting. I have a list > that list have another list (eg) > > list = [[1234,'name1'],[2234,'name2'],[0432,'name3']] > > I want to sort only numeric value having array field. > How I need to do for that. In Python 2.4: py> import operator py> seq = [(1234,'name1'),(2234,'name2'),(1432,'name3')] py> seq.sort(key=operator.itemgetter(0)) py> seq [(1234, 'name1'), (1432, 'name3'), (2234, 'name2')] Note that I've changed your name 'list' to 'seq' since 'list' is shadowing the builtin list function in your code, and I've changed your nested lists to tuples because they look like groups of differently typed objects, not sequences of similarly typed objects. See: http://www.python.org/doc/faq/general.html#why-are-there-separate-tuple-and-list-data-types That said, the code I've given will still work if you shadow the builtin list or if you use lists instead of tuples. STeVe From tjreedy at udel.edu Tue Apr 26 12:31:31 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 26 Apr 2005 12:31:31 -0400 Subject: bytecode non-backcompatibility References: <1114418065.581779.52480@l41g2000cwc.googlegroups.com> Message-ID: "Maurice LING" wrote in message news:d4kh4q$tqf$1 at domitilla.aioe.org... > Now I understand that Python bytecodes are only dealing with pure python > source codes. Then stop blaming (machine-independent) CPython 'bytecodes' for any problems you have with compiled-to-machine-language C extensions, which have nothing to do with bytecodes. Bytecodes also have nothing directly to do with source-code compatibility. From dcrespo at gmail.com Fri Apr 22 15:38:23 2005 From: dcrespo at gmail.com (dcrespo) Date: 22 Apr 2005 12:38:23 -0700 Subject: PDF Printing support from Python In-Reply-To: <116iihncpcr5057@corp.supernews.com> References: <1114191192.978923.268390@f14g2000cwb.googlegroups.com> <116iihncpcr5057@corp.supernews.com> Message-ID: <1114198703.935948.286720@o13g2000cwo.googlegroups.com> Hi Grant Edwards... Your solution requires a previous installation of Acrobat. Internally, the OS is sending the pdf file to the Acrobat PDF Driver and then it is sent to the printer. So you have to have Acrobat installed. Don't you? I want to avoid it installing a module that could do it (maybe I'm dreaming:( ). If there's no solution, then I will be very sad :-S This is what exactly I need to do: Generate an invoice of 216cm width and 93cm height (1/3 of the height of a letter paper size), and print it respecting these dimensions. So, when I print this page on a dot matrix printer, it stops at those 93cm of height for continuous printing. What I tried: I created a pdf file manually with these dimensions, and right-click on the pdf file, and selected "print". It just work under Windows XP with Acrobat Reader 7.0, but I want to do it from a Win98 as well. Unfortunately, there's no Acrobat version under Win98 (the maximun is 5.1) that supports this kind of printing (what I had seen until now). It prints, but the all paper at letter size :( Any help? Any other tools? Any one like Cristal Report but for Python? I heard that wxPython supports some kind of reporting, but I don't know it. Anyone knows? Daniel From could.net at gmail.com Tue Apr 5 04:42:11 2005 From: could.net at gmail.com (could ildg) Date: Tue, 5 Apr 2005 16:42:11 +0800 Subject: Is it possible to distinguish between system environment variables and the user ones? Message-ID: <311b5ce1050405014276d17aff@mail.gmail.com> To a environment variable in Windows, can python know if it is a system environment variable or a current-user environment variable? -- ???????????????????? ???????????????? ???????? From robin at SPAMREMOVEjessikat.fsnet.co.uk Fri Apr 29 03:51:25 2005 From: robin at SPAMREMOVEjessikat.fsnet.co.uk (Robin Becker) Date: Fri, 29 Apr 2005 07:51:25 +0000 Subject: regex over files In-Reply-To: References: <426D0659.7080307@chamonix.reportlab.co.uk> <426D08BC.1040703@klix.ch> <426E021E.8000809@jessikat.fsnet.co.uk> <17006.31984.182979.430076@montanaro.dyndns.org> <426E893D.2070905@chamonix.reportlab.co.uk> <426EAA9D.2050904@jessikat.fsnet.co.uk> <426F5B62.3010801@chamonix.reportlab.co.uk> <17008.19697.939514.53469@montanaro.dyndns.org> Message-ID: <4271E77D.400@jessikat.fsnet.co.uk> Peter Otten wrote: > Robin Becker wrote: > > >>#sscan1.py thanks to Skip >>import sys, time, mmap, os, re >>fn = sys.argv[1] >>fh=os.open(fn,os.O_BINARY|os.O_RDONLY) >>s=mmap.mmap(fh,0,access=mmap.ACCESS_READ) >>l=n=0 >>t0 = time.time() >>for mat in re.split("XXXXX", s): > > > re.split() returns a list, not a generator, and this list may consume a lot > of memory. > > ..... that would certainly be the case and may answer why the simple way is so bad for larger memory. I'll have a go at this experiment as well. My original intention was to find the start of each match as a scanner would and this would certainly do that. However, my observation with the trivial byte scan would seem to imply that just scanning the file causes vm problems (at least in xp). I suppose it's hard to explain to the os that I actually only need the relevant few pages. -- Robin Becker From steve at holdenweb.com Fri Apr 8 10:23:30 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 08 Apr 2005 10:23:30 -0400 Subject: Interpreter problem In-Reply-To: <425684F8.5060507@novasyshealth.com> References: <425684F8.5060507@novasyshealth.com> Message-ID: <425693E2.5070903@holdenweb.com> Greg Lindstrom wrote: > I am using python 2.3.5 on a Linux system and have an odd problem > dealing with the 'sha-bang' line. I have a file, driver.py which starts > with > > #!/usr/bin/python > > and works fine (that is, when I type in ./driver.py at the command > prompt the file runs as expected). I have another file, myotherfile.py > which starts with the exact same line (#!/usr/bin/python) but I get > > : bad interpreter: No such file or directory > There's almost certainly a carriage return as well as a newline in the shebang line. [...] regards Steve -- Steve Holden +1 703 861 4237 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ From mefjr75 at hotmail.com Wed Apr 27 12:37:57 2005 From: mefjr75 at hotmail.com (M.E.Farmer) Date: 27 Apr 2005 09:37:57 -0700 Subject: names of methods, exported functions In-Reply-To: References: <1114592521.726967.320810@o13g2000cwo.googlegroups.com> <426f9552.44993106@news.oz.net> Message-ID: <1114619877.485916.232570@l41g2000cwc.googlegroups.com> Michael Hoffman wrote: > Bengt Richter wrote: > > > Using help: (BTW, it would be nice to have some keyword arguments for help to filter down > > information to exclude what may not be interesting) > > No kidding. What do you think the output should look like in that case? > > I think we don't need the mro, or any of the magic methods inherited > from the builtin. > -- > Michael Hoffman The help code is part of pydoc, IIRC, feel free to have a go at it ;) M.E.Farmer From auch-ich-m at g-kein-spam.com Tue Apr 5 12:25:27 2005 From: auch-ich-m at g-kein-spam.com (=?UTF-8?B?QW5kcsOp?= Malo) Date: Tue, 05 Apr 2005 18:25:27 +0200 Subject: re module non-greedy matches broken References: <1153658nrs82j13@corp.supernews.com> <1155e6jgesiik5d@corp.supernews.com> Message-ID: <1480458.f8Wn7Cg56C@news.perlig.de> * lothar wrote: > a non-greedy match - as implicitly defined in the documentation - is a > match in which there is no proper substring in the return which could also > match the regex. Your argumentation is starting at the wrong place. The documentation doesn't define the bahviour, it tries to describe it (wrongly, as said). > you are skirting the issue as to why a matcher should not be able to > return a non-greedy match. > > there is no theoretical reason why it can not be done. I'm sure, you can explain the theory behind regexps in order to substantiate your statement. *shrug* nd From greg at cosc.canterbury.ac.nz Thu Apr 7 01:15:31 2005 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Thu, 07 Apr 2005 17:15:31 +1200 Subject: Lambda: the Ultimate Design Flaw In-Reply-To: <4253fe0c$1@nntp0.pdx.net> References: <4253fe0c$1@nntp0.pdx.net> Message-ID: <3bjtvuF6d00nnU2@individual.net> Scott David Daniels wrote: > Aahz wrote: > >> You just can't have your cake and eat it, too. > > I've always wondered about this turn of phrase. I seldom > eat a cake at one sitting. You need to recursively subdivide the cake until you have a piece small enough to fit in your input buffer. Then the atomicity of the cake-ingestion operation will become apparent. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From mage at mage.hu Sun Apr 24 08:08:55 2005 From: mage at mage.hu (Mage) Date: Sun, 24 Apr 2005 14:08:55 +0200 Subject: postgresql modules and performance Message-ID: <426B8C57.1030802@mage.hu> Hello, I started to write my PostgreSQL layer. I tried pyPgSQL and PyGreSQL. I made a *very minimal* performance test and comparsion with the same thing in php. Table "movie" has 129 record and many fields. I found PyGreSQL / DB-API / fetchall horrible slow (32 sec in my test). PHP did 13 secs and it gave the result in associative array. Maybe I did something bad. pyPgSQL / DB-API raised a futurewarning and didn't worked. pyPgSQL / libpg worked well. I can create php-like dictionary result in 14 secs. Here is the code. It's only a test... Mage ------ test.py -------- import mpypg import datetime print 'This is a python postgesql module' db = mpypg.mpypgdb('dbname=test host=localhost') def test(): res = db.query('select * from movie') #print res['fields'] #print res['rows'] #pass def test2(): res = db.query('select * from movie') #print res['fields'] #print len(res['rows']) #print res['rows'] print len(res) print res[1] start = datetime.datetime.now() for i in range(100): test() #pass end = datetime.datetime.now() print end - start test2() ------ mpypg.py -------- from pyPgSQL import libpq from pyPgSQL import PgSQL import sys import pgdb mpypg_connect_error_message = 'Could not connect to the database' mpypg_query_error_message = 'Could not run the query' class mpypgdb: 'my database class' def __init__(self,str): try: self.database = libpq.PQconnectdb(str) except: mpypg_error_msg(mpypg_connect_error_message) def query(self,query): try: res = self.database.query(query) fields = tuple([res.fname(i) for i in range(res.nfields)]) rows = [] ''' for name in fields: rows[name] = [] for i in range(res.ntuples): for j in range(len(fields)): rows[fields[j]].append(res.getvalue(i,j)) ''' ''' for j in range(len(fields)): rows[fields[j]] = tuple([res.getvalue(i,j) for i in range(res.ntuples)]) ''' for i in range(res.ntuples): rows.append(dict([(fields[j], res.getvalue(i,j)) for j in range(len(fields))])) res.clear() result = {'fields': fields, 'rows': rows} return result; except: mpypg_error_msg(mpypg_query_error_message) class mpgdb: 'my database class' def __init__(self,str): try: self.database = pgdb.connect(database='test') except: mpypg_error_msg(mpypg_connect_error_message) def query(self,query): try: cursor = self.database.cursor() res = cursor.execute(query) #result = {'fields': fields, 'rows': cursor.fetchall()} result = [cursor.fetchone() for i in range(cursor.rowcount)] #result = cursor.fetchall() return result; except: mpypg_error_msg(mpypg_query_error_message) def mpypg_error_msg(message): 'Database error handler' sys.exit(message) From davidf at sjsoft.com Tue Apr 12 05:08:35 2005 From: davidf at sjsoft.com (David Fraser) Date: Tue, 12 Apr 2005 11:08:35 +0200 Subject: Why does StringIO discard its initial value? In-Reply-To: References: Message-ID: Raymond Hettinger wrote: > [Leif K-Brooks] > >>The obvious workaround is to call buffer.write() with the initial value >>instead of passing it to StringIO's constructor, > > > More than just a workaround, it is the preferred approach. > That makes is easier to switch to cStringIO where initialized objects are > read-only. > Others may find this helpful ; it's a pure Python wrapper for cStringIO that makes it behave like StringIO in not having initialized objects readonly. Would it be an idea to extend cStringIO like this in the standard library? It shouldn't lose performance if used like a standard cStringIO, but it prevents frustration :-) David class StringIO: def __init__(self, buf = ''): if not isinstance(buf, (str, unicode)): buf = str(buf) self.len = len(buf) self.buf = cStringIO.StringIO() self.buf.write(buf) self.buf.seek(0) self.pos = 0 self.closed = 0 def __iter__(self): return self def next(self): if self.closed: raise StopIteration r = self.readline() if not r: raise StopIteration return r def close(self): """Free the memory buffer. """ if not self.closed: self.closed = 1 del self.buf, self.pos def isatty(self): if self.closed: raise ValueError, "I/O operation on closed file" return False def seek(self, pos, mode = 0): if self.closed: raise ValueError, "I/O operation on closed file" self.buf.seek(pos, mode) self.pos = self.buf.tell() def tell(self): if self.closed: raise ValueError, "I/O operation on closed file" return self.pos def read(self, n = None): if self.closed: raise ValueError, "I/O operation on closed file" if n == None: r = self.buf.read() else: r = self.buf.read(n) self.pos = self.buf.tell() return r def readline(self, length=None): if self.closed: raise ValueError, "I/O operation on closed file" if length is not None: r = self.buf.readline(length) else: r = self.buf.readline(length) self.pos = self.buf.tell() return r def readlines(self): if self.closed: raise ValueError, "I/O operation on closed file" lines = self.buf.readlines() self.pos = self.buf.tell() return lines def truncate(self, size=None): if self.closed: raise ValueError, "I/O operation on closed file" self.buf.truncate(size) self.pos = self.buf.tell() self.buf.seek(0, 2) self.len = self.buf.tell() self.buf.seek(self.pos) def write(self, s): if self.closed: raise ValueError, "I/O operation on closed file" origpos = self.buf.tell() self.buf.write(s) self.pos = self.buf.tell() if origpos + len(s) > self.len: self.buf.seek(0, 2) self.len = self.buf.tell() self.buf.seek(self.pos) def writelines(self, lines): if self.closed: raise ValueError, "I/O operation on closed file" self.buf.writelines(lines) self.pos = self.buf.tell() self.buf.seek(0, 2) self.len = self.buf.tell() self.buf.seek(self.pos) def flush(self): if self.closed: raise ValueError, "I/O operation on closed file" self.buf.flush() def getvalue(self): if self.closed: raise ValueError, "I/O operation on closed file" return self.buf.getvalue() From hgk at et.uni-magdeburg.de Thu Apr 14 02:33:42 2005 From: hgk at et.uni-magdeburg.de (Hans Georg Krauthaeuser) Date: Thu, 14 Apr 2005 08:33:42 +0200 Subject: Newbie Tkinter Question In-Reply-To: References: <425d9284$0$572$ed2e19e4@ptn-nntp-reader04.plus.net> Message-ID: Peter Otten schrieb: > Pseud O'Nym wrote: > > >>the following fragment doesn't cause any errors and results in buttons the >>correct size for the images, but the buttons don't work, and the images >>aren't displayed. If I add a text property, and remove the images, they >>work fine, so the rest of my code's OK. I've searched this group and >>Python.org to no avail. >> >>class App: >> def __init__(self, master): >> frame = Frame(master) >> frame.pack(side=LEFT, fill=Y) >> image1 = PhotoImage(file='button_a.gif') >> self.button = Button(frame, image=image1) >> self.button.pack(side=TOP) > > > self.image = image1 > > >>Can anyone enlighten me? > > > For reasons that are beyond me widgets do not increase the reference count > of a PhotoImage. Therefore you have to put a reference to the image > elsewhere, e. g. into the App instance, to prevent it from being > garbage-collected when the image1 variable goes out of scope. > > Peter > Because I stumbled across the same 'feature' just recently, I think it's good to give a reference... >From http://tkinter.unpythonic.net/wiki/Images "Something that seems to bite every new Tkinter programmer at least once: you've loaded a PhotoImage, applied it to a Button, Label, or other widget, and nothing shows up - because you referenced the image only via a local variable, so it went out of scope and got deleted before the widget ever appeared. The usual solution is to store a reference to the image as an attribute of the widget that is to display it. You might just call this a bug in Tkinter, but the reality isn't quite that simple... Tk images are not first-class objects: when you apply one to a widget, you do not in any sense "pass a reference to" the image. Instead, you just pass a name, which Tk looks up in an internal table of defined images (from which images can only be deleted manually). From Tkinter, passing a PhotoImage as a parameter actually only sends the str() of the image object to the Tcl side: this is just a string, the randomly-generated name assigned when the object was created. "No reference to the image itself" means "no reference counting" means "no way for the Python side to be notified when the image is truly no longer used". If Tkinter didn't delete images when no Python reference to them existed, they would be unavoidable memory leaks. ..." Hans Georg From aahz at pythoncraft.com Tue Apr 19 14:21:42 2005 From: aahz at pythoncraft.com (Aahz) Date: 19 Apr 2005 11:21:42 -0700 Subject: Proposal: an unchanging URL for Python documentation References: <1113878396.500420.256230@g14g2000cwa.googlegroups.com> <1113914904.034233.192720@z14g2000cwz.googlegroups.com> Message-ID: In article <1113914904.034233.192720 at z14g2000cwz.googlegroups.com>, Steve wrote: > >http://docs.python.org/modindex.html > >and there also is > >http://python.org/doc/current/modindex.html > >Anybody know why there are two different URLs? > >Which one should be considered the "official" current documentation >URL? (REASON: A person wanting to Wikalong annotate the "official" >current documentation URL would want to know which one to annotate.) I'd consider the official URL to be http://www.python.org/doc/current/modindex.html The primary reason for creating docs.python.org was to make Google searches easier. I believe the eventual intent is to make that the official URL, but there were some glitches in setting it up and I'm not sure whether they've been completely ironed out. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "The joy of coding Python should be in seeing short, concise, readable classes that express a lot of action in a small amount of clear code -- not in reams of trivial code that bores the reader to death." --GvR From steve at holdenweb.com Thu Apr 21 14:13:37 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 21 Apr 2005 14:13:37 -0400 Subject: python classes/file structure In-Reply-To: <1114103206.925440.218520@l41g2000cwc.googlegroups.com> References: <1114091324.679130.294190@g14g2000cwa.googlegroups.com> <1114103206.925440.218520@l41g2000cwc.googlegroups.com> Message-ID: codecraig wrote: > Thanks, but I am not familiar with the "__all__" variable, could u give > me an example? > > Without using, __all__....would i do this in my __init__.py? > > import MyCustomWidget1 > import MyCustomWidget2 > import MyCustomWidget3 > > etc? > Yes, correct. __all__ just limits the names that are imported into the receiving namespace with "from module import *". regards Steve -- Steve Holden +1 703 861 4237 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ From bronger at physik.rwth-aachen.de Wed Apr 20 11:52:18 2005 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Wed, 20 Apr 2005 17:52:18 +0200 Subject: Why Python does *SLICING* the way it does?? References: <1113976729.450677.261130@o13g2000cwo.googlegroups.com> <87r7h5lk5a.fsf@wilson.rwth-aachen.de> Message-ID: <87fyxlqwct.fsf@wilson.rwth-aachen.de> Hall?chen! Bernhard Herzog writes: > Torsten Bronger writes: > >> It's interesting to muse about a language that starts at "1" for >> all arrays and strings, as some more or less obsolete languages >> do. I think this is more intuitive, since most people (including >> mathematicians) start counting at "1". The reason for starting >> at "0" is easier memory address calculation, so nothing for >> really high level languages. > > There are very good reasons for half-open intervals and starting > at 0 apart from memory organization. Dijkstra explained this > quite well in > http://www.cs.utexas.edu/users/EWD/ewd08xx/EWD831.PDF I see only one argument there: "Inclusion of the upper bound would then force the latter to be unnatural by the time the sequence has shrunk to the empty one." While this surely is unaesthetical, I don't think that one should optimise syntax according to this very special case. Besides, no language I know of has probems with negative values. Well, and the argument for "0" derives from that, according to Dijkstra. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus From removethis.kartic.krishnamurthy at gmail.com Wed Apr 13 16:50:25 2005 From: removethis.kartic.krishnamurthy at gmail.com (Kartic) Date: Wed, 13 Apr 2005 20:50:25 GMT Subject: permission In-Reply-To: <425c8b44$1@dnews.tpgi.com.au> References: <425c8b44$1@dnews.tpgi.com.au> Message-ID: James said the following on 4/12/2005 11:00 PM: > Is it possible to check if you have permission to access and or change a > directory or file? James - You can use the access() in the os module. import os print os.access('C:\\', os.R_OK | os.W_OK) # check for read/write access # hopefully print True print os.access('C:\\noexist.file', os.R_OK) # Check no existent file # will print False print os.access('C:\\Docume~1\\anotheruser\\Mydocu~1', os.R_OK) # Read another users documents folder # should print False if no read access Please read http://docs.python.org/lib/os-file-dir.html for more info. Thanks, -Kartic From achrist at easystreet.com Sat Apr 9 14:00:08 2005 From: achrist at easystreet.com (Al Christians) Date: Sat, 09 Apr 2005 11:00:08 -0700 Subject: ntvdm problem on win2k Message-ID: <115g61r25jhbaac@corp.supernews.com> I started having some problems running python programs (python 2.3) from the Win2k command line. I would get crashes with an NTVDM error. Even just executing python would cause it. I upgraded to python 2.3.5, and no difference. When I rearranged my path to move cygwin and a bunch of other stuff (.net, etc) after C:\python23, the problem went away. Is this problem known to anyone but me? Any diagnosis, solution of 12 or fewer steps, or support group? If I'm distributing python programs (python 2.3.5 packaged with py2exe) should I warn or notify the recipients that this is a possible problem with the programs? TIA Al From tom at dtsam.com Thu Apr 21 13:13:48 2005 From: tom at dtsam.com (Thomas Bartkus) Date: Thu, 21 Apr 2005 12:13:48 -0500 Subject: Regular Expressions - Python vs Perl References: <1114092105.964664.211430@l41g2000cwc.googlegroups.com> <1114098472.768814.281750@g14g2000cwa.googlegroups.com> <1114102481.963973.252500@g14g2000cwa.googlegroups.com> Message-ID: "codecraig" wrote in message news:1114102481.963973.252500 at g14g2000cwa.googlegroups.com... > I found some benchmarking (perhaps simple) but search for "The Great > Computer language shootout" ....look at the original shootout and the > win32 one. > > Thomas: > "I doubt the total execution time for all the RegEx queries you ever > ran took > as much time as you just wasted on your little experiment. " .....no > need to be angry. I don't have some "little experiment", but thanks > for being concerned about me wasting my time. > > I do understand that python is certainly easier to read, no doubt. I > was just doing some research to find out about speed/performance > between the two. > > But thanks for pointing out, again, that Pyton is easier to read. > (let's just not forget that python is great for other things other than > just readability.) Your quite welcome. BUT I didn't say a word about readability. I claimed it was easier to *write*. Thomas Bartkus From bokr at oz.net Wed Apr 20 06:19:24 2005 From: bokr at oz.net (Bengt Richter) Date: Wed, 20 Apr 2005 10:19:24 GMT Subject: Behaviour of str.split References: <4263cf31$0$26348$db0fefd9@news.zen.co.uk> <3cm7t9F6nuiooU1@individual.net> Message-ID: <42662833.48350644@news.oz.net> On Wed, 20 Apr 2005 10:55:18 +0200, David Fraser wrote: >Greg Ewing wrote: >> Will McGugan wrote: >> >>> Hi, >>> >>> I'm curious about the behaviour of the str.split() when applied to >>> empty strings. >>> >>> "".split() returns an empty list, however.. >>> >>> "".split("*") returns a list containing one empty string. >> >> >> Both of these make sense as limiting cases. >> >> Consider >> >> >>> "a b c".split() >> ['a', 'b', 'c'] >> >>> "a b".split() >> ['a', 'b'] >> >>> "a".split() >> ['a'] >> >>> "".split() >> [] >> >> and >> >> >>> "**".split("*") >> ['', '', ''] >> >>> "*".split("*") >> ['', ''] >> >>> "".split("*") >> [''] >> >> The split() method is really doing two somewhat different things >> depending on whether it is given an argument, and the end-cases >> come out differently. >> >You don't really explain *why* they make sense as limiting cases, as >your examples are quite different. > >Consider > >>> "a*b*c".split("*") >['a', 'b', 'c'] > >>> "a*b".split("*") >['a', 'b'] > >>> "a".split("*") >['a'] > >>> "".split("*") >[''] > >Now how is this logical when compared with split() above? The trouble is that s.split(arg) and s.split() are two different functions. The first is 1:1 and reversible like arg.join(s.split(arg))==s The second is not 1:1 nor reversible: '<>'.join(s.split()) == s ?? Not usually. I think you can do it with the equivalent whitespace regex, preserving the splitout whitespace substrings and ''.joining those back with the others, but not with split(). I.e., >>> def splitjoin(s, splitter=None): ... return (splitter is None and '<>' or splitter).join(s.split(splitter)) ... >>> splitjoin('a*b*c', '*') 'a*b*c' >>> splitjoin('a*b', '*') 'a*b' >>> splitjoin('a', '*') 'a' >>> splitjoin('', '*') '' >>> splitjoin('a b c') 'a<>b<>c' >>> splitjoin('a b ') 'a<>b' >>> splitjoin(' b ') 'b' >>> splitjoin('') '' >>> splitjoin('*****','*') '*****' Note why that works: >>> '*****'.split('*') ['', '', '', '', '', ''] >>> '*a'.split('*') ['', 'a'] >>> 'a*'.split('*') ['a', ''] >>> splitjoin('*a','*') '*a' >>> splitjoin('a*','*') 'a*' Regards, Bengt Richter From tzot at sil-tec.gr Thu Apr 14 10:22:48 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Thu, 14 Apr 2005 17:22:48 +0300 Subject: Supercomputer and encryption and compression @ rate of 96% References: <1113470846.970773.4780@g14g2000cwa.googlegroups.com> <425e47a9$0$26352$db0fefd9@news.zen.co.uk> Message-ID: On Thu, 14 Apr 2005 13:49:22 +0200, rumours say that "Fredrik Lundh" might have written: >Will McGugan wrote: > >> Please implement this as a Python module. I would like to compress my mp3 collection to single >> bits. > >here's the magic algorithm (somewhat simplified): [snip algo [0]] Well, I take advantage of this "folding" idea for years now. Do you remember DoubleSpace? I was getting to the limits [1] of my 100 MiB hard disk, so I was considering upgrading my hardware. A female friend of mine, knowing a little but not a lot about MS-DOS asked the eye-opening question: "why don't you reapply double space to the compressed drive?" I was enlightened. Of course, a couple of weeks ago I had a bad sector which destroyed 800 KiB right in the middle of _Echoes_, but I had my whole Pink Floyd collection on a 5.25 floppy (zip of zip of zip of...) [0] -- btw, in your code, Fredrik: """file = open(keycode + ".out", "wb")""".replace("keycode", "filename") [1] disk space -- the final frontier -- TZOTZIOY, I speak England very best. "Be strict when sending and tolerant when receiving." (from RFC1958) I really should keep that in mind when talking with people, actually... -- TZOTZIOY, I speak England very best. "Be strict when sending and tolerant when receiving." (from RFC1958) I really should keep that in mind when talking with people, actually... From skip at pobox.com Mon Apr 11 12:44:05 2005 From: skip at pobox.com (Skip Montanaro) Date: Mon, 11 Apr 2005 11:44:05 -0500 Subject: Thoughts on some stdlib modules In-Reply-To: References: <425999BD.7050308@v.loewis.de> <200504102212.19392.hancock@anansispaceworks.com> Message-ID: <16986.43349.305695.807402@montanaro.dyndns.org> >> I guess the other thing to compare to is something like SciPy, which >> is a kind of specialized distribution of Python for scientific >> applications. Robert> No, Scipy is just a (large) package. Enthon, on the other hand, Robert> is just such a distribution. I'm sorry, you lost me there. What's the difference between a large package and a distribution? Skip From rkern at ucsd.edu Wed Apr 27 17:35:50 2005 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 27 Apr 2005 14:35:50 -0700 Subject: Lexicographical sort for numarray In-Reply-To: <1114636258.399427.181330@f14g2000cwb.googlegroups.com> References: <1114635125.849049.309880@l41g2000cwc.googlegroups.com> <1114636258.399427.181330@f14g2000cwb.googlegroups.com> Message-ID: Jason Mobarak wrote: > It does what the OPs example does, but with numeric types. It certainly does not. In [15]:arr = na.arange(100) In [16]:random.shuffle(arr) In [17]:arr.shape = (10,10) In [18]:arr2 = na.array(arr) In [19]:L = arr.tolist() In [20]:L.sort() In [21]:na.array(L) Out[21]: array([[ 8, 22, 40, 85, 64, 20, 91, 76, 19, 56], [11, 83, 86, 51, 72, 17, 80, 35, 1, 18], [13, 62, 0, 95, 25, 28, 5, 78, 54, 55], [41, 44, 15, 24, 27, 97, 31, 75, 65, 29], [45, 57, 16, 89, 87, 90, 42, 50, 93, 9], [53, 21, 47, 69, 2, 12, 92, 98, 66, 48], [70, 79, 36, 88, 10, 39, 81, 61, 43, 3], [74, 37, 49, 14, 33, 34, 52, 23, 96, 71], [82, 67, 30, 60, 6, 73, 99, 94, 7, 58], [84, 63, 4, 46, 26, 32, 59, 38, 68, 77]]) In [22]:arr2.flat.sort() In [23]:arr2 Out[23]: array([[ 0, 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, 33, 34, 35, 36, 37, 38, 39], [40, 41, 42, 43, 44, 45, 46, 47, 48, 49], [50, 51, 52, 53, 54, 55, 56, 57, 58, 59], [60, 61, 62, 63, 64, 65, 66, 67, 68, 69], [70, 71, 72, 73, 74, 75, 76, 77, 78, 79], [80, 81, 82, 83, 84, 85, 86, 87, 88, 89], [90, 91, 92, 93, 94, 95, 96, 97, 98, 99]]) -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From kent37 at tds.net Sat Apr 30 13:35:51 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat, 30 Apr 2005 13:35:51 -0400 Subject: large dictionary creation takes a LOT of time. In-Reply-To: <4273A36B.5010501@i.com.ua> References: <1114757468.367583.210840@z14g2000cwz.googlegroups.com> <42720ccb$1_2@newspeer2.tds.net> <427255b4$1_3@newspeer2.tds.net> <4273A36B.5010501@i.com.ua> Message-ID: <4273bd7f$1_1@newspeer2.tds.net> Maksim Kasimov wrote: > > sorry for my question, but i've read the documentation, and can't find > where is the explanation of how it is exactly works (but of course i do > believe you). If it is buit in function, can i see the source code of > the method to find it out? > > Kent Johnson wrote: >> http://docs.python.org/lib/built-in-funcs.html From the above page: open( filename[, mode[, bufsize]]) An alias for the file() function above. file( filename[, mode[, bufsize]]) Return a new file object (described in section 2.3.9, ``File Objects''). >> http://docs.python.org/lib/bltin-file-objects.html 2.3.9 File Objects next( ) A file object is its own iterator, for example iter(f) returns f (unless f is closed). When a file is used as an iterator, typically in a for loop (for example, for line in f: print line), the next() method is called repeatedly. This method returns the next input line, or raises StopIteration when EOF is hit. or look at Objects/fileobject.c in the source code. Kent From radam2 at tampabay.rr.com Wed Apr 20 11:24:21 2005 From: radam2 at tampabay.rr.com (Ron) Date: Wed, 20 Apr 2005 15:24:21 GMT Subject: pre-PEP: Simple Thunks In-Reply-To: <86u0m1udf3.fsf@guru.mired.org> References: <3jl2615c5pckknicc32ccv2cktue3nh603@4ax.com> <7og3615g159tgksejbo15oo8jcit3ugec2@4ax.com> <3r2661ltasoktjlgtvp3v03osb372b15j2@4ax.com> <86u0m1udf3.fsf@guru.mired.org> Message-ID: Mike Meyer wrote: > Ron_Adam writes: > >>Here's yet another way to do it, but it has some limitations as well. >> >>import pickle >>def pickle_it(filename, obj, commands): >> try: >> f = open(filename, 'r') >> obj = pickle.load(f) >> f.close() >> except IOError: >> pass >> for i in commands: >> i[0](i[1]) >> f = open(filename, 'w') >> pickle.dump(obj, f) >> f.close() >> >>file = 'filename' >>L = [] >> >>opps = [ (L.append,'more data'), >> (L.append,'even more data') ] >>pickle_it(file, L, opps) > > > Um - it doesn't look like this will work. You pass L in as the "obj" > paremeter, and then it gets changed to the results of a > pickle.load. However, you call L.append in the for loop, so the data > will be appended to L, not obj. You'll lose an list elements that were > in the pickle. > > Hi there... I want to distribute my python apps and the MySQL Database in the easiest way possible. I mean a user just run the installation file and all is automaticly installed. Any suggestions? My knowledge: I know, as many of you, that there's py2exe for compiling python apps for running under Windows. But what about the database structure and data? I think it could be reached through a .qry run in the MySQL database from an installation instruction. But (one more time) what about the automated installation of the MySQL database without user intervention? Daniel Crespo From rkern at ucsd.edu Wed Apr 20 12:56:58 2005 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 20 Apr 2005 09:56:58 -0700 Subject: Troll? was: Re: goto statement In-Reply-To: References: <20050420092359.81900.qmail@web8409.mail.in.yahoo.com> <42664190.6010507@i.com.ua> <87vf6hlkix.fsf@wilson.rwth-aachen.de> <70sc615akd7mfdkmrjls956o1u5rglm74t@4ax.com> Message-ID: Maxim Kasimov wrote: > Andr? Roberge wrote: > >> Maxim Kasimov wrote: >> >>> >>> by the way, "goto" statement will be useful for writing more powerful >>> obfuscators >>> >> Let me get that clear: you want a goto to help with debugging. >> >> And you want to obfuscate your code even more? >> >> !? >> >> Perhaps you need to write in Perl, or some other similar language. >> >> Writing in Python is for those that seek clarity (not obfuscation) and >> less bugs. Which is why a goto statement should definitely never be >> part of Python! >> >> Andr? >> > > so insulting to me - you asking i'm a troll, only becose i'm saing that > goto maybe sometimes usefull. No, because you said that it was useful for obfuscating code. Obfuscating code is generally not a desirable feature of a language construct. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From sjmachin at lexicon.net Mon Apr 18 18:41:06 2005 From: sjmachin at lexicon.net (John Machin) Date: Tue, 19 Apr 2005 08:41:06 +1000 Subject: def a((b,c,d),e): References: <1113854757.229118.137260@g14g2000cwa.googlegroups.com> Message-ID: <66d861tapjp3fo8duoh8oceinae6ands95@4ax.com> On 18 Apr 2005 13:05:57 -0700, "AdSR" wrote: >Fellow Pythonistas, > >Please check out > >http://spyced.blogspot.com/2005/04/how-well-do-you-know-python-part-3.html > >if you haven't done so yet. It appears that you can specify a function >explicitly to take n-tuples as arguments. It actually works, checked >this myself. If you read the reference manual at >http://docs.python.org/ref/function.html >really carefully, you will find that it is indeed part of the language >spec, but it's a likely candidate for the least advertised Python >feature. Small wonder since it looks like one of those language >features that make committing atrocities an order of magnitude easier. > Thanks for pointing this out. However I see no atrocity potential here -- what did you have in mind? See below. Better documentation in the "def" (even better than having say "year_month_day" instead of my lazy "dt_tup"). No overhead; byte-code is the same. >>> def weird_date_from_tuple(dt_tup): ... year, month, day = dt_tup ... return ... >>> import dis >>> dis.dis(weird_date_from_tuple) 2 0 LOAD_FAST 0 (dt_tup) 3 UNPACK_SEQUENCE 3 6 STORE_FAST 3 (year) 9 STORE_FAST 1 (month) 12 STORE_FAST 2 (day) 3 15 LOAD_CONST 0 (None) 18 RETURN_VALUE >>> def weird_date_from_tuple((year, month, day)): ... return ... >>> dis.dis(weird_date_from_tuple) 1 0 LOAD_FAST 0 (.0) 3 UNPACK_SEQUENCE 3 6 STORE_FAST 1 (year) 9 STORE_FAST 2 (month) 12 STORE_FAST 3 (day) 2 15 LOAD_CONST 0 (None) 18 RETURN_VALUE >>> Cheers, John From miki.tebeka at zoran.com Mon Apr 25 07:43:45 2005 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Mon, 25 Apr 2005 14:43:45 +0300 Subject: Is there a package with convolution and related methods? In-Reply-To: References: Message-ID: <20050425114345.GK3652@zoran.com> Hello Charles, > Is there a Python package with Convolution and related methods? > > I'm working on modeling some DSP processes in Python. I've rolled one > up, but don't feel much like reinventing the wheel, especially if > there's already something like "Insanely Efficient FFT for Python" > already. Have you looked at NumArray (http://www.stsci.edu/resources/software_hardware/numarray) and SciPy (http://www.scipy.org/)? I also think that gmp (http://www.swox.com/gmp/) which has Python binding (http://gmpy.sourceforge.net/) has FFT. HTH. -- ------------------------------------------------------------------------ Miki Tebeka http://tebeka.bizhat.com The only difference between children and adults is the price of the toys -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 193 bytes Desc: not available URL: From kent37 at tds.net Wed Apr 20 15:10:12 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 20 Apr 2005 15:10:12 -0400 Subject: Array of Chars to String In-Reply-To: References: <42658990.7739398@news.oz.net> Message-ID: <4266a4d1$1_2@newspeer2.tds.net> Michael Spencer wrote: > Anyway, here are the revised timings... > ... print shell.timefunc(func_translate1, "Bob Carol Ted Alice" * > multiplier, 'adB') What is shell.timefunc? Thanks, Kent From grante at visi.com Wed Apr 27 10:25:38 2005 From: grante at visi.com (Grant Edwards) Date: Wed, 27 Apr 2005 14:25:38 -0000 Subject: PyGTK vs. wxPython References: <1114444582.909431.245450@f14g2000cwb.googlegroups.com> <1114551965.718056.197480@g14g2000cwa.googlegroups.com> <116tf7lm0ivnl6c@corp.supernews.com> <1114600746.599172.163730@o13g2000cwo.googlegroups.com> Message-ID: <116v872cjudbbd8@corp.supernews.com> On 2005-04-27, dcrespo wrote: > And what did you use for deploying either PyGTK and wxPython? In other > words, what were your workspace and logic of the development? To whom is this question addressed? I suggest you quote properly when replying in order to give your question the context required to answer it. -- Grant Edwards grante Yow! Am I elected yet? at visi.com From steven.bethard at gmail.com Fri Apr 8 17:15:47 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 08 Apr 2005 15:15:47 -0600 Subject: Counting iterations In-Reply-To: <1112994185.983954.234650@l41g2000cwc.googlegroups.com> References: <1112994185.983954.234650@l41g2000cwc.googlegroups.com> Message-ID: Derek Basch wrote: > Is there a better way to count iterations that this?: > > pets = 0 > for i in pets: > pets += 1 > print "pet" + "#" + pets for i, pet in enumerate(pets): print 'pet#%i' % (i + 1) STeVe From roy at panix.com Fri Apr 1 07:53:18 2005 From: roy at panix.com (Roy Smith) Date: Fri, 01 Apr 2005 07:53:18 -0500 Subject: Ternary Operator in Python References: Message-ID: praba kar wrote: > Dear All, > I am new to Python. I want to know how to > work with ternary operator in Python. I cannot > find any ternary operator in Python. You answered your own question; there is no ternary operator in Python. There was a major debate on this newsgroup a year or so ago on this subject, and the decision was quite clear that no such feature would be added. If you google for "python ternary", you will find a huge amount of material written on the subject. From jarrod.roberson at gmail.com Fri Apr 22 15:22:41 2005 From: jarrod.roberson at gmail.com (fuzzylollipop) Date: 22 Apr 2005 12:22:41 -0700 Subject: Python licence again In-Reply-To: References: Message-ID: <1114197761.019100.38890@o13g2000cwo.googlegroups.com> try spelling license correctly next time and heading the google suggestions that probably looked like "didn't you mean : Python License" From invalidemail at aerojockey.com Fri Apr 1 20:04:05 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 1 Apr 2005 17:04:05 -0800 Subject: Ternary Operator in Python In-Reply-To: References: <20050401072442.73412.qmail@web8408.mail.in.yahoo.com> <1112391650.018826.274970@l41g2000cwc.googlegroups.com> Message-ID: <1112403845.059741.213410@z14g2000cwz.googlegroups.com> Terry Reedy wrote: > "Carl Banks" wrote in message > news:1112391650.018826.274970 at l41g2000cwc.googlegroups.com... > >> A unary operator has one operand; a binary operator has two operands; > >> ternary operator has three operands. Python has none built-in, > > > > Not so fast, my friend. What about the expression "0.0 < a < 1.0"? > > Gee, what about 0.0 < a < 1.0 < b < 2.0? I see both as synthesized > multinary operators, but your are right in that this combination does act > differently than a+b+c. It seems that Python has an infinite number of operators. -- CARL BANKS From codecraig at gmail.com Thu Apr 21 13:12:36 2005 From: codecraig at gmail.com (codecraig) Date: 21 Apr 2005 10:12:36 -0700 Subject: python classes/file structure In-Reply-To: <1114103206.925440.218520@l41g2000cwc.googlegroups.com> References: <1114091324.679130.294190@g14g2000cwa.googlegroups.com> <1114103206.925440.218520@l41g2000cwc.googlegroups.com> Message-ID: <1114103556.453615.304010@l41g2000cwc.googlegroups.com> also is it common to have one class per file? seems weird to have, MyCustomWidget.MyCustomWidget thanks From stevenaleach at mac.com Thu Apr 28 00:00:08 2005 From: stevenaleach at mac.com (steve.leach) Date: Thu, 28 Apr 2005 00:00:08 -0400 Subject: Can .py be complied? References: <426ec8f7_2@rain.i-cable.com> <1114564416.221686.54300@l41g2000cwc.googlegroups.com> Message-ID: Harlin Seritt wrote: > Hi monkey, > > Not a stupid question especially if you're trying to create commercial > software and don't want to reveal your source. At any rate, you can use > py2exe to create a .exe file. It does have some cons to it since you Some very severe cons considering that would mean his code would only run on a certain infamous legacy operating system that will remain unnamed. The last I checked, ".exe" files were rather useless on most operating systems. From prabapython at yahoo.co.in Wed Apr 6 09:00:59 2005 From: prabapython at yahoo.co.in (praba kar) Date: Wed, 6 Apr 2005 14:00:59 +0100 (BST) Subject: how to parse system functions output In-Reply-To: 6667 Message-ID: <20050406130059.21786.qmail@web8410.mail.in.yahoo.com> Dear all, I want to parse the system functions output but I couldn't do it. Kindly assist me in this task. eg) bytesused = os.system('du -sh /Users/enmail') if I print this bytesused variable the output of bytesused variable is the below 14M /Users/enmail 0 Now From this Output I want only '14M" I cannot split this output by space. If anyone know regarding this mail me ASAP regards Prabahar ________________________________________________________________________ Yahoo! India Matrimony: Find your life partner online Go to: http://yahoo.shaadi.com/india-matrimony From mahs at telcopartners.com Sun Apr 3 14:27:37 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Sun, 03 Apr 2005 11:27:37 -0700 Subject: Corectly convert from %PATH%=c:\\X; "c:\\a; b" TO ['c:\\X', 'c:\\a; b'] In-Reply-To: <1112520171.853820.90010@o13g2000cwo.googlegroups.com> References: <1112484475.908682.278880@f14g2000cwb.googlegroups.com> <1112520171.853820.90010@o13g2000cwo.googlegroups.com> Message-ID: chirayuk wrote: > > However, I just realized that the following is also a valid PATH in > windows. > > PATH=c:\A"\B;C"\D;c:\program files\xyz" > (The quotes do not need to cover the entire path) Too bad! What a crazy format! > > So here is my handcrafted solution. > > def WinPathList_to_PyList (pathList): > pIter = iter(pathList.split(';')) > OddNumOfQuotes = lambda x: x.count('"') % 2 == 1 > def Accumulate (p): > bAcc, acc = OddNumOfQuotes(p), [p] > while bAcc: > p = pIter.next () > acc.append (p) > bAcc = not OddNumOfQuotes (p) > return "".join (acc).replace('"','') > return [q for q in [Accumulate (p) for p in pIter] if q] > Does it work? I get: >>> test2 = r'c:\A"\B;C"\D;c:\program files\xyz"' >>> WinPathList_to_PyList(test2) Traceback (most recent call last): File "", line 1, in ? File "pathsplit", line 31, in WinPathList_to_PyList File "pathsplit", line 27, in Accumulate StopIteration >>> Also, on the old test case, I get: >>> WinPathList_to_PyList("""\"c:\\A;B";c:\\D;""") ['c:\\AB', 'c:\\D'] >>> Should the ';' within the quotes be removed? > > So now I need to check if the os is windows. > > Wishful thinking: It would be nice if something like this (taking care > of the cases for other OS's) made it into the standard library - the > interpreter must already be doing it. > This sort of 'stateful' splitting is a somewhat common task. If you're feeling creative, you could write itertools.splitby(iterable, separator_func) This would be a sister function to itertools.groupby (and possible derive from its implementation). separator_func is a callable that returns True if the item is a separator, False otherwise. splitby would return an iterator of sub-iterators (like groupby) defined by the items between split points You could then implement parsing of crazy source like your PATH variable by implementing a stateful separator_func Michael From olaamigoquepasa at hotmail.com Thu Apr 21 19:52:15 2005 From: olaamigoquepasa at hotmail.com (hawkesed) Date: 21 Apr 2005 16:52:15 -0700 Subject: Dictionary question. In-Reply-To: References: <1114076862.063504.256970@g14g2000cwa.googlegroups.com> <8c7f10c60504210317a51586@mail.gmail.com> Message-ID: <1114127535.805214.109140@o13g2000cwo.googlegroups.com> Here is an example of the input list: [101, 66, 75, 107, 108, 101, 106, 98, 111, 88, 119, 93, 115, 95, 114, 95, 118, 109, 85, 75, 88, 97, 53, 78, 98, 91, 115, 77, 107, 153, 108, 101] Here is the code I am working on now: >>> for num in alist: ... if adict.has_key(num): ... x = adict.get(num) ... x = x + 1 // update the value here else // add the new value here. Its these two commented out lines that I am working on. For the record, I am not in a python class. I am trying to learn python. For one thing I thought it looks like it would be a good tool to work with math and statistics stuff. Thanks for the help. Have a great day. Ed From damiansmom at shaw.ca Mon Apr 4 07:22:27 2005 From: damiansmom at shaw.ca (JustMe) Date: 4 Apr 2005 04:22:27 -0700 Subject: Text file to SDE Message-ID: We have recently purchased ARCSDE 9. I have attended the ARCSDE administrator for Oracle course, but it did not cover how to write data without an the arcgis interfaces. I was told however that I could write data say from a text file directly to the sde using python. Does anyone have a sample script on how to do this, or tell me where I can find this information. Thanks in advance Just me From thn at mail.utexas.edu Fri Apr 15 10:37:28 2005 From: thn at mail.utexas.edu (Thomas Nelson) Date: Fri, 15 Apr 2005 09:37:28 -0500 Subject: new to mac OS10 In-Reply-To: <1113571800.485209.169320@z14g2000cwz.googlegroups.com> References: <1113571800.485209.169320@z14g2000cwz.googlegroups.com> Message-ID: The main thing I would like is to be able to use tkinter with python on my mac. will the command-line-style source allow this? Does it come with IDLE? How is the fink version different from the source i can download at python.org? Here's the result of the requested commands on my Terminal. It would appear that these links are broken, as Python.framework no longer exists. Sorry to be so much trouble, THN Welcome to Darwin! ~ $ ls -all /usr/bin/python* lrwxr-xr-x 1 root wheel 9 20 Jun 2004 /usr/bin/python -> python2.3 lrwxr-xr-x 1 root wheel 72 20 Jun 2004 /usr/bin/python2.3 -> ../../System/Library/Frameworks/Python.framework/Versions/2.3/bin/python lrwxr-xr-x 1 root wheel 10 20 Jun 2004 /usr/bin/pythonw -> pythonw2.3 -rwxr-xr-x 1 root wheel 122 8 Jun 2003 /usr/bin/pythonw2.3 ~ $ ls /System/Library/Framework/Python.framework ls: /System/Library/Framework/Python.framework: No such file or directory ~ $ cd /System/Library/Framework/Python.framwork -bash: cd: /System/Library/Framework/Python.framwork: No such file or directory ~ $ Jorl Shefner wrote: > If you simply want the latest python to run from the command line, then > compiling the source code works fine on the mac. I just installed > 2.4.1 on Os 10.3.8 last week without any problems. > > http://www.python.org/ftp/python/2.4.1/Python-2.4.1.tgz > > "./configure" > "make" > "make install" > > J.S. > From abkhd at earth.co.jp Mon Apr 18 10:28:24 2005 From: abkhd at earth.co.jp (A.B., Khalid) Date: 18 Apr 2005 07:28:24 -0700 Subject: (Python newbie) Using XP-SP2/MSVC6: No Python24_d.lib, winzip barfs on Python-2.4.1.tar, cannot download bzip2 References: Message-ID: <1113834504.919986.129180@z14g2000cwz.googlegroups.com> Bill Davy wrote: > I downlaoded and installed > http://www.python.org/ftp/python/2.4.1/python-2.4.1.msi > > I'm trying to build an extension using SWIG 1.3.24 and the linker needs > python24_d.lib (I do not have the DLL either). I've not found it in any of > the > downloads. > > So I tried to download the source to build it myself. Of > http://www.python.org/ftp/python/2.4.1/Python-2.4.1.tar.bz2 and > http://www.python.org/ftp/python/2.4.1/Python-2.4.1.tgz, WinZip (9.0 SR1) > just says "Error reading header after processing 0 entries". > > Additionally, I've had no joy downloading the unzipper > (ftp://sources.redhat.com/pub/bzip2/v102/bzip2-102-x86-win32.exe) from the > site cited for the unzipper (http://sources.redhat.com/bzip2/). It flashed > up a > black console window momentarily. > > Oh, this is sooooo frustrating! :-( > > Can anyone point me in the right direction? > > And then I can get to grips with my work. > > tia > Bill I am no expert in MSVC6, but it sounds like maybe you need to supply the no-debug switch in your extention setup.py file: /d NDEBUG. In case that does not work and help on this is not forthcoming, you can always try pyMinGW[1]. Regards, Khalid [1] pyMinGW: http://jove.prohosting.com/iwave/ipython/pyMinGW.html From dcrespo at gmail.com Wed Apr 27 23:41:43 2005 From: dcrespo at gmail.com (dcrespo) Date: 27 Apr 2005 20:41:43 -0700 Subject: PyGTK vs. wxPython In-Reply-To: References: <1114444582.909431.245450@f14g2000cwb.googlegroups.com> <1114616192.342452.178720@o13g2000cwo.googlegroups.com> <1114626660.172481.303090@z14g2000cwz.googlegroups.com> Message-ID: <1114659703.325422.195730@l41g2000cwc.googlegroups.com> > Really though, these questions are more suited for the wxPython mailing list. Thank you very much for this acclaration :) From philippe at philippecmartin.com Fri Apr 15 09:31:02 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Fri, 15 Apr 2005 13:31:02 GMT Subject: Using python from a browser/security hole References: Message-ID: I'll take a lok, thanks Roel Schroeven wrote: > Philippe C. Martin wrote: > >> Since I need to access a local/client device from the page and that I >> wish to be cross-platform; does that mean Java is my only way out ? > > Or you could try Jython (http://www.jython.org/). > From jjl at pobox.com Fri Apr 29 15:16:57 2005 From: jjl at pobox.com (John J. Lee) Date: 29 Apr 2005 20:16:57 +0100 Subject: Which IDE is recommended? References: <426f90ac$1_2@rain.i-cable.com> Message-ID: Dave Cook writes: > On 2005-04-27, monkey wrote: [...] > Pydev has some compelling features, but I wish I didn't have to run eclipse [...] What are those compelling features of Pydev, for an emacs user? John From Dennis.Benzinger at gmx.net Fri Apr 15 05:13:06 2005 From: Dennis.Benzinger at gmx.net (Dennis Benzinger) Date: Fri, 15 Apr 2005 11:13:06 +0200 Subject: RE Engine error with sub() In-Reply-To: References: Message-ID: <425f85a2$1@news.uni-ulm.de> Maurice LING schrieb: > Hi, > > I have the following codes: > > from __future__ import nested_scopes > [...] Are you still using Python 2.1? In every later version you don't need the "from __future__ import nested_scopes" line. So, if you are using Python 2.1 I strongly recommend upgrading to Python 2.4.1. > [...] > It all works well for rule count up to 800+ but when my replacement > rules swells up to 1800+, it gives me a runtime error that says > "Internal error in regular expression engine"... traceable to "return > self.regex.sub(self, text)" in substitute() method. > [...] I didn't read your code, but this sounds like you have a problem with the regular expression engine being recursive in Python versions < 2.4. Try again using Python 2.4 or later (i.e. Python 2.4.1). The new regular expression engine is not recursive anymore. Bye, Dennis From duncan.booth at invalid.invalid Tue Apr 5 05:28:35 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 5 Apr 2005 09:28:35 GMT Subject: StopIteration in the if clause of a generator expression References: <424db34c.51543105@news.oz.net> <_2R3e.3341$7b.3033@trndny06> Message-ID: Simon Brunning wrote: > On Apr 5, 2005 2:04 AM, Raymond Hettinger wrote: >> [Steven Bethard] >> > So do I read this right in preferring >> > [ for in ] >> > over >> > list( for in ) >> >> Yes! > > Why? (Serious question. I'm sure that you have a good reason - I just > can't figure out what it is.) > > The generator expression has the advantage of not leaking references > into the enclosing namespace. What's advantage of the list comp? > The list comprehension is about 15-20% faster according to timeit.py: C:\Python24\Lib>..\python.exe timeit.py -s "t = range(1000)" "[ x for x in t]" 10000 loops, best of 3: 116 usec per loop C:\Python24\Lib>..\python.exe timeit.py -s "t = range(1000)" "list(x for x in t)" 1000 loops, best of 3: 144 usec per loop C:\Python24\Lib>..\python.exe timeit.py -s "t = range(100000)" "[ x for x in t]" 10 loops, best of 3: 13.9 msec per loop C:\Python24\Lib>..\python.exe timeit.py -s "t = range(100000)" "list(x for x in t)" 10 loops, best of 3: 16.3 msec per loop Alternatively you could just regard the list comprehension as having less clutter on the screen so it may be clearer. From bokr at oz.net Sun Apr 17 05:26:02 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 17 Apr 2005 09:26:02 GMT Subject: Compute pi to base 12 using Python? References: <7x3btui27t.fsf@ruckus.brouhaha.com> <1113545886.372148.82420@z14g2000cwz.googlegroups.com> Message-ID: <4262261c.159801732@news.oz.net> On Sun, 17 Apr 2005 01:00:46 -0700, Dick Moores wrote: >M.E.Farmer wrote at 23:18 4/14/2005: >> > >Using the GNU "bc" utility: >> > > >> > > $ bc -l >> > > bc 1.06 >> > > Copyright 1991-1994, 1997, 1998, 2000 Free Software Foundation, >>Inc. >> > > This is free software with ABSOLUTELY NO WARRANTY. >> > > For details type `warranty'. >> > > scale = 3000 # number of output places wanted >> > > obase = 12 # output base >> > > print 4 * a(1) # pi = 4*arctan(1) > >Wow! this got me the 3003 (changed from 3000) digits of pi to base 12 in >60.8 secs. No, I didn't count them yet, nor am I sure they're correct. >But I'd bet on them.. > >Could someone remind me how to get the output of bc -l into a text file >on Windows? (I've tried employing " > pi3003.txt" in various ways) OR, >how to copy and paste from the command line window, or whatever that >window is called? (Sorry for the OT question.) To copy from the command window to the clipboard: 1. Scroll top of desired stuff to make it visible near top 2. Hold down Alt 3. Tap Space Bar 4. Release Alt 5. Tap e 6. Tap k 7. Use mouse or arrow keys to place cursor on top left corner of desired box 8. Hold down Shift 9. Use arrow keys or mouse-with-left-button-pressed to go to bottom right character of desired box 9a. If the bottom is out of sight, keep holding shift down and pretend you can cursor down below bottom. the attempt should make the screen scroll up and select more desired material. If you overshoot, don't panic, just keep holding down shift and use arrows (the are slower) or mouse-with-left-button-still-down to move to desired bottom right corner. 10. Release mouse button if using that 11. Release Shift 12. Press Enter That should copy to the clipboard and make the selection box revert to normal display. Pasting from clipboard is up to you. Pasting into the command window from clipboard is 2-5 above, and Tap p HTH PS. Redirecting with > from a script whose interpreter was started by windows extension association doesn't work on some version of windows. To be safe, invoke the interpreter explicitly, e.g., python myscript.py [whatever args here] > pi3003.txt If myscript.py is not in the current directory, use a sufficient path to it. If your windows is having that problem, the same will happen with a perl script or other script when you run it as just myscript.ext ... and depend on windows to start the right interpreter. Regards, Bengt Richter From mark.greenbank at gmail.com Sun Apr 10 12:02:13 2005 From: mark.greenbank at gmail.com (mark.greenbank at gmail.com) Date: 10 Apr 2005 09:02:13 -0700 Subject: email and smtplib modules In-Reply-To: <86d5t3wrtf.fsf@guru.mired.org> References: <1113081060.969295.36900@o13g2000cwo.googlegroups.com> <86d5t3wrtf.fsf@guru.mired.org> Message-ID: <1113148933.012000.139710@f14g2000cwb.googlegroups.com> Hi Mike, Thanks for the quick tutorial :) Quite helpful. From scmarsh at hotmail.com Thu Apr 21 16:46:25 2005 From: scmarsh at hotmail.com (scott) Date: Thu, 21 Apr 2005 20:46:25 GMT Subject: Jython run scripts problem (2.2.0a0 on Mac OSX 10.3.8) Message-ID: I installed darwinports and did a "sudo port install jython" ------------------------- scott$ which jython /opt/local/bin/jython ------------------------- Jython works in interactive mode as shown below: ------------------------- pyprogs$ cd hotbits/ hotbits$ ls flips50.py jythoninstall.py randomX randomflip.py hotbits$ jython Jython 2.2a0 on java1.4.2_05 (JIT: null) >>> # Truly random (radioactive decay triggered) coin flip >>> from randomX import randomHotBits >>> r = randomHotBits() >>> if r.nextByte() < 0: ... print 'tails' ... else: ... print 'heads' ... tails -------------------------- Jython *doesn't* work if I save the above as a script and try to run it. It refuses to run the script and simply starts up in interactive mode: --------------------------- hotbits$ jython randomflip.py Jython 2.2a0 on java1.4.2_05 (JIT: null) >>> --------------------------- Question: How can I run scripts as expected (outside interactive mode)? Thanks in advance. From bokr at oz.net Fri Apr 22 21:42:35 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 23 Apr 2005 01:42:35 GMT Subject: a=[ lambda t: t**n for n in range(4) ] References: <1114206105.666055.33720@g14g2000cwa.googlegroups.com> <1114208333.622909.179640@l41g2000cwc.googlegroups.com> Message-ID: <4269a0ea.275861307@news.oz.net> On 22 Apr 2005 15:18:53 -0700, mehmetmutigozel at gmail.com wrote: >Thanx for your replies. > >I'm looking for array of functions. >Something like a=[ sin(x) , cos(x) ] > >>>> x=0.0 >>>> a >[0, 1] >>>> x=1.0 >>>> a >... > >of course it can be made by >>>> def cratearray(x): >... ~~~~ >... return a >a=createarray(1.0) > >but this isn't what i am asking for. something automized. > I still don't know what you are asking for, but here is a toy, whose code you will be able to improve on later, but at least provides concrete behavior that you can comment on, and maybe explain what you are really asking for. >>> class FunArray(object): ... def __init__(self, *funs): ... self.__dict__['_funs'] = funs ... self.__dict__['_names'] = [] ... vars ... def __getattribute__(self, attr): ... if attr.startswith('_') or hasattr(type(self), attr): ... return object.__getattribute__(self, attr) ... v = vars(self).get(attr) ... if v is None: return ['%r is not set'%attr] ... return [f(v) for f in self._funs] ... def __setattr__(self, attr, v): ... if attr.startswith('_'): raise AttributeError, attr ... else: ... if attr in self._names: self._names.remove(attr) ... self._names.append(attr) ... self.__dict__[attr] = v ... def __repr__(self): ... last = self._names and self._names[-1] or '??' ... d= vars(self) ... return ' %s>'% ( ... ', '.join(['%s=%r'%(k, d[k]) for k in self._names]), ... last, repr(getattr(self, last))) ... >>> from math import sin, cos, pi >>> a = FunArray(sin, cos) >>> a.x = 0.0 >>> a [0.0, 1.0]> >>> a.x [0.0, 1.0] >>> a.y = 1.0 >>> a.y [0.8414709848078965, 0.54030230586813977] >>> a [0.8414709848078965, 0.54030230586813977]> >>> a.z = pi/3 >>> a [0.8660254037844386, 0.50000000000000011]> >>> a.x = pi/6 >>> a [0.49999999999999994, 0.86602540378443871] If you just want an interactive calculator that acts according to your taste, you can program one to prompt and read (use raw_input, not input BTW) what you type in and calculate and print whatever form of result you'd like. See the cmd module for one way not to reinvent some wheels. But why not spend some time with the tutorials, so have a few more cards in your deck before you try to play for real? ;-) Regards, Bengt Richter From cdkrug at worldnet.att.net Fri Apr 29 23:56:19 2005 From: cdkrug at worldnet.att.net (Charles Krug) Date: Sat, 30 Apr 2005 03:56:19 GMT Subject: Data smoothing algorithms? References: <000c01c54c38$313eb580$0201a8c0@mcuf7> Message-ID: "Anthra Norell" writes: > >> Hi, >> > The following are differences of solar declinations from one day to > the next, (never mind the unit). Considering the inertia of a > planet, any progress of (apparent) celestial motion over regular > time intervals has to be highly regular too, meaning that a plot > cannot be jagged. The data I googled out of Her Majesty's Nautical > Almanac are merely nautical precision and that, I suppose, is where > the jitter comes in. There's got to be algorithms out there to iron > it out. If it were a straight line, I could do it. But this, over > the whole year, is a wavy curve, somthing with a dominant sine > component. Suggestions welcome. > Anything you do to your samples is going to distort the samples, either in frequency or in time. Luckily for you, all of the interesting information in your signal is in the time domain representation, unless you consider a 3.1709791983764586504312531709792e-8Hz sinusoid interesting. A simple moving average filter is often helpful in these cases, along with being the Simplest Possible Thing That Might Work. Take a look at: http://www.dspguide.com/pdfbook.htm "The Scientist and Engineer's Guide to DSP," which is well regarded by the denizens of comp.dsp. Check out Chapter 14 for an overview, and 15 for moving average filters. You can also try a single-pole recursive filter with a cutoff of 1/360 of your sample rate, but that slightly more complicated. Try the moving average first. It's the simplest and very often Good Enough. From tundra at tundraware.com Thu Apr 21 04:37:31 2005 From: tundra at tundraware.com (Tim Daneliuk) Date: 21 Apr 2005 04:37:31 EDT Subject: python LEX In-Reply-To: References: Message-ID: Tim Daneliuk wrote: > jozo wrote: > >> I have to work on python lexical definition in Lex. I spent lots of my >> time to find regular expresions written for Lex of Python language but >> nothing. >> Can somebody help me? >> >> I nEED hELP >> > http://systems.cs.uchicago.edu/ply/ > Whoops - I did not read your question carefully enough ... sorry, cannot help with what you actually asked. -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From Ugo_DiGirolamo at invision.iip.com Fri Apr 29 12:34:09 2005 From: Ugo_DiGirolamo at invision.iip.com (Ugo Di Girolamo) Date: Fri, 29 Apr 2005 09:34:09 -0700 Subject: Problem with embedded python - bug? Message-ID: <3D4A0A4A0225484B965A23CFD127B82F4A6811@invnmail.invision.iip.com> I have been having a few more discussions around about this, and I'm starting to think that this is a bug. My take is that, when I call Py_Finalize, the python thread should be shut down gracefully, closing the file and everything. Maybe I'm missing a call to something (?PyEval_FinalizeThreads?) but the docs seem to say that just PyFinalize should be called. The open file seems to be the issue, since if I remove all the references to the file I cannot get the program to crash. I can reproduce the same behavior on two different wxp systems, under python 2.4 and 2.4.1. Ugo -----Original Message----- From: Ugo Di Girolamo Sent: Tuesday, April 26, 2005 2:16 PM To: 'python-dev at python.org' Subject: Problem with embedded python I have the following code, that seems to make sense to me. However, it crashes about 1/3 of the times. My platform is Python 2.4.1 on WXP (I tried the release version from the msi and the debug version built by me, both downloaded today to have the latest version). The crash happens while the main thread is in Py_Finalize. I traced the crash to _Py_ForgetReference(op) in object.c at line 1847, where I have op->_ob_prev == NULL. What am I doing wrong? I'm definitely not too sure about the way I'm handling the GIL. Thanks in adv for any suggestion/ comment Cheers and ciao Ugo ////////////////////////// TestPyThreads.py ////////////////////////// #include #include "Python.h" int main() { PyEval_InitThreads(); Py_Initialize(); PyGILState_STATE main_restore_state = PyGILState_UNLOCKED; PyGILState_Release(main_restore_state); // start the thread { PyGILState_STATE state = PyGILState_Ensure(); int trash = PyRun_SimpleString( "import thread\n" "import time\n" "def foo():\n" " f = open('pippo.out', 'w', 0)\n" " i = 0;\n" " while 1:\n" " f.write('%d\\n'%i)\n" " time.sleep(0.01)\n" " i += 1\n" "t = thread.start_new_thread(foo, ())\n" ); PyGILState_Release(state); } // wait 300 ms Sleep(300); PyGILState_Ensure(); Py_Finalize(); return 0; } From manatlan at localhost.localdomain Mon Apr 25 16:55:23 2005 From: manatlan at localhost.localdomain (manatlan) Date: Mon, 25 Apr 2005 22:55:23 +0200 Subject: pygtk, gtk.treeview and virtuallist ? Message-ID: Hello, I'm new to pygtk (but i know wxpython very well) I'm trying to play with this example : http://www.pygtk.org/pygtk2tutorial/sec-CellRenderers.html#filelistingfig (the code is here : http://www.pygtk.org/pygtk2tutorial/examples/filelisting.py) I'd like to be able to use a virtual list (like wx.ListCtrl in mode LC_VIRTUAL) ... This example use a gtk.treeview with a listStore ... There are callbacks to display "image, texts and info" (via set_cell_data_func() ) But if there are 1000000 of items, the callbacks will be called 1000000 times before the window appears ;-( I'd like that theses callbacks are called only when items are displayed in the window (on demand) ... is it possible to do that in pygtk ? From jae at elkins.org Sun Apr 24 06:41:19 2005 From: jae at elkins.org (jeff elkins) Date: Sun, 24 Apr 2005 10:41:19 +0000 Subject: GUI woes In-Reply-To: References: Message-ID: <200504241041.19200.jae@elkins.org> On Sunday 24 April 2005 03:11 am, Roger Binns wrote: > "jeff elkins" wrote in message > news:mailman.2361.1114307134.1799.python-list at python.org... > > > under debian sid, I installed (via apt-get) the various wxpython stuff > > available.: > > > > libwxgtk2.4-python > > libwxgtk2.5.3-python > > python-opengl > > python-pythoncard > > python2.1-opengl > > python2.2-opengl > > python2.3-opengl > > python2.3-pythoncard > > pythoncard > > pythoncard-doc > > pythoncard-tools > > wx2.5-examples > > wxpython2.5.3 > > wxwin2.4-examples > > You have a mixture of different versions of wxPython in there. > > > AttributeError: MyFrame instance has no attribute 'Bind' > > Bind was introduced in wxPython 2.5. Looks like you are > running against thr 2.4 library. > > Roger Thanks. I'll see if I can delete/reinstall and fix things. From bokr at oz.net Sun Apr 3 03:53:07 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 03 Apr 2005 07:53:07 GMT Subject: Docorator Disected References: <4p9t419ockcg8578g6guse3a14t16orebf@4ax.com> <424f04d0.137947037@news.oz.net> <1112500967.391604.289760@f14g2000cwb.googlegroups.com> <0mqu41pham7n91vb1qgtoe567unn1cffb6@4ax.com> Message-ID: <424f982c.175671582@news.oz.net> On Sun, 03 Apr 2005 05:09:07 GMT, Ron_Adam wrote: >On 2 Apr 2005 20:02:47 -0800, "El Pitonero" >wrote: > >>Ron_Adam wrote: >>> >>> So I didn't know I could do this: >>> >>> def foo(a1): >>> def fee(a2): >>> return a1+a2 >>> return fee >>> >>> fum = foo(2)(6) <------ !!! >> >>Ah, so you did not know functions are objects just like numbers, >>strings or dictionaries. I think you may have been influenced by other >>languages where there is a concept of static declaration of functions. > >No, I did not know that you could pass multiple sets of arguments to That phraseology doesn't sound to me like your concept space is quite isomorphic with reality yet, sorry ;-) It sounds like you are thinking of "multiple sets of arguments" as an aggregate that is passed as such, and that isn't happening, as I believe El Pitonero is trying to indicate with his parenthesized visualization below. What is happening is that an expression "foo(2)(6)" is being evaluated left to right. First foo as a name evaluates to whatever it is bound to, which is the foo function. Then () is the calling operator, which says evaluate the list inside the parens left to right and call the thing you had so far, which was foo here. The arg list was just 2, so foo is called with 2, and foo returns something, with which we will do the next operation if there is one. If the next operation was "." (i.e., attribute getting) the next thing following would have had to be an attribute name, e.g. like func_name. foo(2).func_name would evaluate to the same as fee.func_name for the fee returned by foo(2). But we are not doing .func_name, we are doing (6) as the next operation in the left-to-right evaluation of the expression. And whatever we have at the foo(2) stage, the (6) means we should take it and call it with 6 as an argument. So if you are seeing (2)(6) as something to pass, as opposed to a sequence of operations, I think there's a misconception involved. Perhaps I am taking your words askew ;-) >nested defined functions in that manner. Just haven't ran acrossed it >in the two years I've been playing around with python. I haven't had a >reason to try it either. But maybe now that I'm aware of it, I'll >find more uses for it. > > > >>The last line can be better visualized as: >> >>fum = (foo(2)) (6) >> >>where foo(2) is a callable. >> That's clear to me, anyway ;-) The code shows it too: >>> import dis, compiler >>> dis.dis(compiler.compile('foo(2)','','eval')) 1 0 LOAD_NAME 0 (foo) 3 LOAD_CONST 1 (2) 6 CALL_FUNCTION 1 9 RETURN_VALUE The (6) just calls whatever the result of the preceding was >>> dis.dis(compiler.compile('foo(2)(6)','','eval')) 1 0 LOAD_NAME 0 (foo) 3 LOAD_CONST 1 (2) 6 CALL_FUNCTION 1 9 LOAD_CONST 2 (6) 12 CALL_FUNCTION 1 15 RETURN_VALUE HTH Regards, Bengt Richter From mefjr75 at hotmail.com Sun Apr 17 15:47:15 2005 From: mefjr75 at hotmail.com (M.E.Farmer) Date: 17 Apr 2005 12:47:15 -0700 Subject: whitespace , comment stripper, and EOL converter References: <2ab23d7a.0504120857.14ef094a@posting.google.com> <2ab23d7a.0504130738.622a3605@posting.google.com> <1113410094.102181.315080@l41g2000cwc.googlegroups.com> <1113680973.635576.310510@g14g2000cwa.googlegroups.com> <1113713669.255207.39580@f14g2000cwb.googlegroups.com> <1113726606.945042.71820@z14g2000cwz.googlegroups.com> <1113730429.336626.81360@g14g2000cwa.googlegroups.com> <1113732226.165477.295890@o13g2000cwo.googlegroups.com> Message-ID: <1113767235.173452.224680@z14g2000cwz.googlegroups.com> I found the bug and hope I have squashed it. Single and qouble quoted strings that were assignments and spanned multilines using \ , were chopped after the first line. example: __date__ = 'Apr 16, 2005,' \ 'Jan 15 2005,' \ 'Oct 24 2004' became: __date__ = 'Apr 16, 2005,' \ Not good :( tokenizer sends this as: name operator string string string newline I added test for string assignments that end in \. A flag is set and then all strings till a newline are ignored. Also rearranged the script a little. Maybe that will do it ... Updates available at > The script is located at: > http://bellsouthpwp.net/m/e/mefjr75/python/stripper.py > > M.E.Farmer From axel at straschil.com Fri Apr 8 13:07:01 2005 From: axel at straschil.com (Axel Straschil) Date: 08 Apr 2005 17:07:01 GMT Subject: Can dictionary values access their keys? References: Message-ID: Hello! > thousands more entries. So we're talking about maybe a million+ total > nested key:values. I don't know if that counts as large or not. I can't > even guess how much k memory that is. Mhh, maybe you should use a SQL-Database ;-) Lg, AXEL. -- "Aber naja, ich bin eher der Forentyp." Wolfibolfi's outing in http://www.informatik-forum.at/showpost.php?p=206342&postcount=10 From peter at engcorp.com Wed Apr 13 14:57:44 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 13 Apr 2005 14:57:44 -0400 Subject: printing with wxPython In-Reply-To: References: Message-ID: <6MKdnTTF5KM29sDfRVn-hQ@powergate.ca> Fabio Pliger wrote: > Yeah, > There are two about printing... there is also an example in the wxDemo... > but they all talk about printing text... In my case i need to print (or at > least to make a print preview) a bitmap (or a panel...) The technique used should be the same. Basically you need to be doing draws directly to a Device Context (or whatever DC stands for...temporary memory lapse) and then you can draw to the screen or to a printer, as required. I don't know offhand what routine is used to draw a Bitmap into a DC, but I'm sure it's reasonably well documented under the various DC methods. -Peter From steve at holdenweb.com Mon Apr 4 15:56:13 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 04 Apr 2005 15:56:13 -0400 Subject: How to reload local namespace definitions in the python interpreter? In-Reply-To: <797fe3d4050404122377c77588@mail.gmail.com> References: <1112435996.697236.231800@l41g2000cwc.googlegroups.com> <3b7an1F6gf5b4U1@individual.net> <797fe3d4050404122377c77588@mail.gmail.com> Message-ID: <42519BDD.3020107@holdenweb.com> Bill Mill wrote: > On Apr 4, 2005 11:10 AM, Steve Holden wrote: > >>Tim Jarman wrote: >> >>>test1dellboy3 at yahoo.co.uk wrote: >>> >>> >>> >>>>Hi, >>>> >>>>I am a beginner using the python interpreter. To reduce typing effort, >>>>I created a module called "aliases.py" containing some aliases for >>>>objects I commonly use like - >>>> >>>>aliases.py : >>>> >>>> >>>>import filecmp, os, commands >>>> >>>>op = os.path > > > >>>By the way, are you aware of the import ... as ... idiom? >>>e.g. import os.path as op >>> >> >>This would, of course, require the user to qualify the names by >>prefixing them with "op.". >> > > > What the OP listed above requires that too. > I believe the OP was suggesting from aliases import * which specifically loads the names in the module (or those specified in module.__all__) into the importing namespace for use without qualification. regards Steve -- Steve Holden +1 703 861 4237 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ From edcjones at comcast.net Wed Apr 27 01:35:39 2005 From: edcjones at comcast.net (Edward C. Jones) Date: Wed, 27 Apr 2005 01:35:39 -0400 Subject: Lexicographical sort for numarray Message-ID: Suppose arr is a two dimensional numarray array. Suppose we do the following: def rowsort(arr): a = arr.tolist() a.sort() return numarray.array(a) Can this sort be done efficiently in numarray? This function is called "rowsort" in MatLab. From gsmith at Oxfam.org.uk Fri Apr 15 10:01:49 2005 From: gsmith at Oxfam.org.uk (gsmith at Oxfam.org.uk) Date: Fri, 15 Apr 2005 15:01:49 +0100 Subject: MS SQL Server/ODBC package for Python Message-ID: I do have a standard install of Python as well as Plone. Can you have two? I have run the mxInstaller for both instances .... however, whether I run the ide from my standard install or my plone install the pythonpath is the same (ie c:\...\plone 2\python). My machine registry now has the python entries all pointing at plone. Sorry to trouble you like this but do you know how I can get myself out of this mess? Cheers. graham Simon Brunning mail.com> cc: python-list at python.org Subject: Re: MS SQL Server/ODBC package for Python 15/04/2005 14:21 Please respond to simon :3 Kb On 4/15/05, Graham wrote: > Thanks Simon > I have just installed mxODBC and tried one of their samples. > Am getting an error on trying to import mx.ODBC > > ImportError: No module named mx.ODBC > > After the install the mx folder has been place in my C:\Program Files\Plone > 2\Python\lib\site-packages folder however when I browse the PythonPath and > look under Standard Python Library I can't see mx. Hmmm. Have you got more than one instance of Python installed? Do you have a 'standard' installation in addition to Plone's? If so, perhaps mxODBC has been installed for the wrong one. -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From mwm at mired.org Fri Apr 22 02:53:29 2005 From: mwm at mired.org (Mike Meyer) Date: Fri, 22 Apr 2005 01:53:29 -0500 Subject: regarding system function References: Message-ID: <86sm1js3o6.fsf@guru.mired.org> praba kar writes: > Dear All, > > In Php If I send a command to system function > then It will return 1 on success and 0 on failure. So > based upon that value I can to further work. > > But In Python If I send a command to system > function then It will return 0 only for both > conditions(success and failure). So What I need > to do for this. I want the result like php system > function. You don't say what platform you're on, but from your description of the problem, it's not Unix: py> os.system("grep foo /dev/null") 256 py> os.system("grep foo /no_such_file") grep: /no_such_file: No such file or directory 512 os.system is a simple wrapper around the C system() function. It's return value is the same as that function. On unix, that's the 1/0 you want in the upper byte, and status information in the lower byte - so you divide by 256. I have no idea what Windows does in this case. I'd recommend using the subprocess routines instead of os.system. They are much more powerful/flexible than os.system. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From mensanator at aol.com Thu Apr 14 12:22:07 2005 From: mensanator at aol.com (mensanator at aol.com) Date: 14 Apr 2005 09:22:07 -0700 Subject: Compute pi to base 12 using Python? In-Reply-To: References: <1113390479.738210.49530@z14g2000cwz.googlegroups.com> <1113430615.592715.78440@f14g2000cwb.googlegroups.com> Message-ID: <1113495726.884203.326670@f14g2000cwb.googlegroups.com> Nick Craig-Wood wrote: > mensanator at aol.com wrote: > > I'm using GMPY (see code). > [snip] > > If you are using gmpy you might as well do it like this..... > > gmpy.pi() uses the Brent-Salamin Arithmetic-Geometric Mean formula for > pi IIRC. This converges quadratically, and it will calculate you a > million places without breaking a sweat. It would be nice if that were documented. What do I have to do, go get the documentation for the original GMP to find out what else is in GMPY that they didn't include in the doc file? > > >>> import gmpy > >>> from math import log > >>> bits = int(3003*log(12)/log(2)) > >>> pi=gmpy.pi(bits+100) > >>> gmpy.fdigits(pi, 12, 3003) > '3.184809493b918664573a6211bb151551a05729290a7809a492742140a60a55256a0661a03753a3aa54805646880181a3683083272bbba0a370b12265529a828903b4b256b8403759a71626b8a54687621849b849a8225616b442796a31737b229b2391489853943b8763725616447236b027a421aa17a38b52a18a838b01514a51144a23315a3009a8906b61b8b48a62253a88a50a43ba0944572315933664476b3aabb77583975120683526b75b462060bb03b432551913772729a2147553531793848a0402b999b5058535374465a68806716644039539a8431935198527b9399b112990abb0383b107645424577a51601b3624a88b7a676a3992912121a213887b92873946a61332242217aa7354115357744939112602ba4b888818a3269222b528487747839994ab223b65b8762695422822669ba00a586097842a51750362073b5a768363b21bb1a97a4a194447749399804922175a068a46739461990a2065bb0a30bbab7024a585b1a84428195489784a07a331a7b0a1574565b373b05b03a5a80a13ab87857734679985558a5373178a7b28271992a3894a5776085083b9b238b2220542462888641a2bab8b3083ab49659172a312b78518654494a068662586a181835a64440b2970a122813975898815367208905801032881449223841428763329617531239b9a657405584014534390b587625606bb80923795944b43757a431b039556282978a6a49590553490ba1844947175637a908247b50127722464441380a852b0847b5813019bb70a67663b426565434069884476132193344ba55a2128a03838974606b851b2979321a408067225a5aa4b3464a1a17473595333909ab9127079655b3164b68b9b28a9b818a220a025ab0934203995b7a62a7aa739355340539ba3182905b193905603a43b660b9426a92294697144a896a5b2339358bb2b7294bb89635b071a6351211360b820b1882ab8433b54757b87a373284b1ba182a10326476b369a4a6365b58b8018994bb152556765475a704bb94b6b2a39458971a8b90512786b5029404818644323552916170b3abb7363496427b088b68725a68570040617949289077b278069a09b559324b8a66828b40549b0296065b2300330592569a7b76b92ba1293585b6a9b604567a0901362856373b4b56897946256b4172b1b50474351364749a33996a81ba8847347a8411b850b79a03018291672aa0945656a159aa6aa0a845531a592005b8a34366b882257107b190969a846474836a9800750778920ba797297a2791101b0685a86bb704b9baa17b055293679843b35215b0a8b1182b611953b080aa5431b219907a8448a81b1a9493245676b88013b470335240859594158621014216619553246570601967448b470174b9244892444817453865a4003b5aa7176451aab90681a949786154aa040477382ba69371041710b8728458a23979252b254236753a44a1900aa283536a227648812525743868b410a567794663359a6726a5286783328135114789b7645505b047848020a730a9557b206776aa56a19682744107901306b29008808619866b4911a05264b872a46b5376383932699531b449195640b62a63622830886247a47b3957169861239358041aa281333622aa15912b0a636047a489bb0726282a78b96671b27305a9652496b9b999011a7ba36898891665b1a6009058978850a21b01a158a1473b84a192b8672542a2a7056581995207a436a5b3ba2824637a3112abb57176468206a071200a327b3216425148100786502aa21236abb35499277670a1269730583403b1922a483856007301983989159bb688a58b602339806b63002a339a50b0ba533b84827793913081070a32595a101803a9a20234691b1a0b623274b69b0b44688195169461059543a252bb05208720ba13118266a872b26b9b584959b45179519534b221a335a2bb6971b3276b3a63a5b791723109b176529bb90651584279b7825712521b8269800738b07a62b14547884414451224092937165625696557a78799a82126613535a36b410309b759976119777b895801074b9779b9b5137538b2799951012273399bb818b722 at 0' > > -- > Nick Craig-Wood -- http://www.craig-wood.com/nick From jdhunter at ace.bsd.uchicago.edu Fri Apr 15 01:10:48 2005 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Fri, 15 Apr 2005 00:10:48 -0500 Subject: ANN: matplotlib-0.80 Message-ID: matplotlib is a 2D graphics package that produces plots from python scripts, the python shell, or embeds them in your favorite python GUI -- wx, gtk, tk, fltk and qt. Unlike many python plotting alternatives it is written in python, so it is easy to extend. matplotlib is used in the finance industry, web application servers, and many scientific and engineering disciplines. With a large community of users and developers, matplotlib is approaching the goal of having a full featured, high quality, 2D plotting library for python. A lot of development has gone into matplotlib since the last major release, which I'll summarize here. For details, see the incremental release notes at http://matplotlib.sf.net/whats_new.html. Improvements since 0.70 -- contouring: Lots of new contour functionality with line and polygon contours provided by contour and contourf. Automatic inline contour labeling with clabel. See http://matplotlib.sourceforge.net/screenshots.html#pcolor_demo -- QT backend Sigve Tjoraand, Ted Drain and colleagues at the JPL collaborated on a QTAgg backend -- Unicode strings are rendered in the agg and postscript backends. Currently, all the symbols in the unicode string have to be in the active font file. In later releases we'll try and support symbols from multiple ttf files in one string. See examples/unicode_demo.py -- map and projections A new release of the basemap toolkit - See http://matplotlib.sourceforge.net/screenshots.html#plotmap -- Auto-legends The automatic placement of legends is now supported with loc='best'; see examples/legend_auto.py. We did this at the matplotlib sprint at pycon -- Thanks John Gill and Phil! Note that your legend will move if you interact with your data and you force data under the legend line. If this is not what you want, use a designated location code. -- Quiver (direction fields) Ludovic Aubry contributed a patch for the matlab compatible quiver method. This makes a direction field with arrows. See examples/quiver_demo.py -- Performance optimizations Substantial optimizations in line marker drawing in agg -- Robust log plots Lots of work making log plots "just work". You can toggle log y Axes with the 'l' keypress -- nonpositive data are simply ignored and no longer raise exceptions. log plots should be a lot faster and more robust -- Many more plotting functions, bugfixes, and features, detailed in the 0.71, 0.72, 0.73 and 0.74 point release notes at http://matplotlib.sourceforge.net/whats_new.html Downloads at http://matplotlib.sourceforge.net JDH From newsuser at stacom-software.de Mon Apr 25 03:12:57 2005 From: newsuser at stacom-software.de (Alexander Eisenhuth) Date: Mon, 25 Apr 2005 09:12:57 +0200 Subject: Nice documentation Python / SWIG / C++ Message-ID: Hi alltogether, I found a nice and useful article for extenting python with C++ using SWIG. It describe from the scratch especially for Windows. Maybe this can be included somewhere on www.python.org. Here is the link: http://www.geocities.com/foetsch/python/extending_python.htm Alexander From radam2 at tampabay.rr.com Tue Apr 5 17:32:12 2005 From: radam2 at tampabay.rr.com (Ron_Adam) Date: Tue, 05 Apr 2005 21:32:12 GMT Subject: Decorator Maker is working. What do you think? References: <1112686545.380929.142740@g14g2000cwa.googlegroups.com> Message-ID: <17r551p9jp665caaf2m6b4egs41levq5bh@4ax.com> On 5 Apr 2005 00:35:45 -0700, "Kay Schluehr" wrote: >Ron_Adam wrote: >> Ok... it's works! :) >> >> So what do you think? > >Not much. As long as You do not present any nontrivial examples like >Guidos MultiMethod decorator or an implementation of the dispatching >"case" decorator I proposed that would benefit from factoring into pre- >and postprocessing the pattern has only limited use and worse it >suggests a misnomer: it obscures the semantics that is clearly >functional/OO not procedural. > >Regards, >Kay No good points at all? :/ Are you saying I need to present a non trivial example such as Guido's MultiMethod decorator, or the one you proposed? If I'm not mistaken, there is a difference. Those axamples are specific applications to solve specific problems using decorator expressions. While what I'm attempting here is a general purpose object in which many specific uses could more easily be built with. What about commonly used trivial cases? As a whole are they not non-trivial? How is it limited? I'm still not sure when, and what type of things, should and should not be done with decorators. It seems to me they may be good tools for validating inputs and outputs, and for getting data on program performance. In those cases, it would be good to be able to disable them when they aren't needed. Another use is to redefine a decorator as needed to adapt a function to a specific input or output. Is that what Guido's multimethod does? And they might also be used as a way to change the behavior of a group of related functions all at once at run time in order to save a lot of code duplication. I also think they could be abused easily and used when it would be better to just use a class to do it in the first place. Cheers, Ron] From mwm at mired.org Sat Apr 16 17:51:05 2005 From: mwm at mired.org (Mike Meyer) Date: Sat, 16 Apr 2005 16:51:05 -0500 Subject: A little request about spam References: <1113416856.914310.63930@l41g2000cwc.googlegroups.com> <740c3aec05041405157cb90625@mail.gmail.com> <7ee3dcd80504140551385ce25e@mail.gmail.com> <425E7CB8.85DD2BA4@pauahtun.org> <20050414143640.GA94191@isis.sigpipe.cz> Message-ID: <86y8bitmpi.fsf@guru.mired.org> Ivan Van Laningham writes: > Of course I wouldn't base decisions _only_ on whether or not [PYTHON] > appears in the subject. But I ordinarily do base decisions on the whole > subject line, and I think that's perfectly reasonable. There's nothing > else to go on without opening the message, and for HTML-based mail > there's no surer way to let spammers know they've found a live email > addres than to open it. You know that. No, I don't. My mail reader has a separate "decode" step. I can open HTML email, and see the HTML. Actually, I usually see the ascii version of the HTML followed by the HTML. If I want to see the HTML, I have to tell the reader to "decode" the mail. Then it renders the HTML. Further, I have the HTML renderer set to *not* fetch inline objects unless/until I click on them. So even rendering the HTML won't tell spammers anything. In short - your mail reader needs an upgrade. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From bior_jobs at yahoo.com Thu Apr 28 11:20:28 2005 From: bior_jobs at yahoo.com (Joe Deasy) Date: 28 Apr 2005 08:20:28 -0700 Subject: Job openings for scientifically-oriented programmers In-Reply-To: <1114697719.643475.284220@o13g2000cwo.googlegroups.com> References: <1114697719.643475.284220@o13g2000cwo.googlegroups.com> Message-ID: <1114701628.647054.219810@o13g2000cwo.googlegroups.com> Email was scrambled by google: Correct email address is: bior _jobs @ yahoo.com (remove spaces). I apologize for that. - Joe Deasy From g.brandl at gmx.net Mon Apr 4 12:51:31 2005 From: g.brandl at gmx.net (Georg Brandl) Date: Mon, 04 Apr 2005 18:51:31 +0200 Subject: "specialdict" module In-Reply-To: <1112631551.683072.80970@f14g2000cwb.googlegroups.com> References: <3bamhhF6j009lU1@individual.net> <3bb433F6fn6t3U1@individual.net> <1112631551.683072.80970@f14g2000cwb.googlegroups.com> Message-ID: <3bd9jgF6heia2U1@individual.net> Michele Simionato wrote: > About not using super: you might have problems in multiple inheritance. > Suppose I want to use both your defaultdict and a thirdpartdict. A > subclass > > class mydict(defaultdict, thirdpartdict): > pass > > would not work if thirdpartdict requires a non-trivial __init__ , since > without super in defaultdict.__init__ you would just call dict.__init__ > and not thirdpartdict. Right. I thought about a combined defaultdict/keytransformdict, which seems to be easy to create with the current implementation: class defaultkeytransformdict(defaultdict, keytransformdict): pass At least I hope so. This is another argument against the initializing of defaultfactory or keytransformer in __init__. mfg Georg Here comes the current module (keytransformdict should be working now for all dict methods): # specialdict - subclasses of dict for common tasks # class NoDefaultGiven(Exception): pass class defaultdict(dict): __slots__ = ['_default'] def __init__(self, *args, **kwargs): self._defaulttype = 0 super(defaultdict, self).__init__(*args, **kwargs) def setdefaultvalue(self, value): def defaultfactory(): return value self._default = (defaultfactory, (), {}) def setdefaultfactory(self, factory, *args, **kwargs): if not callable(factory): raise TypeError, 'default factory must be a callable' self._default = (factory, args, kwargs) def cleardefault(self): def defaultfactory(): raise NoDefaultGiven self._default = (defaultfactory, (), {}) def __getitem__(self, key): try: return super(defaultdict, self).__getitem__(key) except KeyError, err: try: return self.setdefault(key, self._default[0](*self._default[1], **self._default[2])) except NoDefaultGiven: raise err class keytransformdict(dict): __slots__ = ['_transformer'] def __init__(self, *args, **kwargs): self._transformer = lambda x: x super(keytransformdict, self).__init__(*args, **kwargs) def settransformer(self, transformer): if not callable(transformer): raise TypeError, 'transformer must be a callable' self._transformer = transformer def __setitem__(self, key, value): print "setitem" super(keytransformdict, self).__setitem__(self._transformer(key), value) def __getitem__(self, key): print "getitem" return super(keytransformdict, self).__getitem__(self._transformer(key)) def __delitem__(self, key): super(keytransformdict, self).__delitem__(self._transformer(key)) def has_key(self, key): return super(keytransformdict, self).has_key(self._transformer(key)) def __contains__(self, key): return self.has_key(key) def get(self, key, default): return super(keytransformdict, self).get(self._transformer(key), default) def setdefault(self, key, default): return super(keytransformdict, self).setdefault(self._transformer(key), default) def pop(self, key, default): return super(keytransformdict, self).pop(self._transfomer(key), default) def update(self, other=None, **kwargs): if other is not None: if hasattr(other, "keys"): super(keytransformdict, self).update((self._transformer(k), other[k]) for k in other.keys()) else: super(keytransformdict, self).update((self._transformer(k), v) for (k, v) in other) if kwargs: super(keytransformdict, self).update((self._transformer(k), v) for (k, v) in kwargs.iteritems()) class sorteddict(dict): def __iter__(self): for key in sorted(super(sorteddict, self).__iter__()): yield key def keys(self): return list(self.iterkeys()) def items(self): return list(self.iteritems()) def values(self): return list(self.itervalues()) def iterkeys(self): return iter(self) def iteritems(self): return ((key, self[key]) for key in self) def itervalues(self): return (self[key] for key in self) From radam2 at tampabay.rr.com Sun Apr 3 00:09:07 2005 From: radam2 at tampabay.rr.com (Ron_Adam) Date: Sun, 03 Apr 2005 05:09:07 GMT Subject: Docorator Disected References: <4p9t419ockcg8578g6guse3a14t16orebf@4ax.com> <424f04d0.137947037@news.oz.net> <1112500967.391604.289760@f14g2000cwb.googlegroups.com> Message-ID: <0mqu41pham7n91vb1qgtoe567unn1cffb6@4ax.com> On 2 Apr 2005 20:02:47 -0800, "El Pitonero" wrote: >Ron_Adam wrote: >> >> So I didn't know I could do this: >> >> def foo(a1): >> def fee(a2): >> return a1+a2 >> return fee >> >> fum = foo(2)(6) <------ !!! > >Ah, so you did not know functions are objects just like numbers, >strings or dictionaries. I think you may have been influenced by other >languages where there is a concept of static declaration of functions. No, I did not know that you could pass multiple sets of arguments to nested defined functions in that manner. Just haven't ran acrossed it in the two years I've been playing around with python. I haven't had a reason to try it either. But maybe now that I'm aware of it, I'll find more uses for it. >The last line can be better visualized as: > >fum = (foo(2)) (6) > >where foo(2) is a callable. > >----------- > >Since a function is an object, they can be assigned (rebound) to other >names, pass as parameters to other functions, returned as a value >inside another function, etc. E.g.: > >def g(x): > return x+3 > >h = g # <-- have you done this before? assignment of function Sure, I have no problem with that. Been doing it for quite a while. :) >print h(1) # prints 4 > >def f(p): > return p # <-- function as return value > >p = f(h) # <-- passing a function object > >print p(5) # prints 8 > >Python's use of "def" keyword instead of the "=" assignment operator >makes it less clear that functions are indeed objects. As I said >before, this is something to think about for Python 3K (the future >version of Python.) I've always equated 'def' as if it were 'make', or in Python its just a variation of 'class' for a subset of objects of type 'function'. >------------ > >Function modifiers exist in other languages. Java particularly is >loaded with them. > >public static synchronized double random() { >... >} > >So your new syntax: > >@decorator(a1)(foo) >def foo(): > pass > >is a bit out of the line with other languages. So? Why would it need to be the same as other languages? I like Python because it's not the same. :) The above syntax suggestion, just matches the already existing behavior, Thanks for helping BTW, I think I have it down pretty good now. Cheers, Ron From exogen at gmail.com Thu Apr 28 05:34:09 2005 From: exogen at gmail.com (Brian Beck) Date: Thu, 28 Apr 2005 05:34:09 -0400 Subject: Which IDE is recommended? In-Reply-To: References: <426f90ac$1_2@rain.i-cable.com> Message-ID: Ville Vainio wrote: > What version? PyDev has increased in maturity quite a bit lately. PyDev 0.9.2 with Eclipse 3.0.2. It's a nice effort currently, but some of my issues are: * Code completion doesn't work properly for me, and I have no idea why. I have to type the '.' then ADD A SPACE, *then* press Ctrl+Space. If I type Ctrl+Space after the dot, nothing happens. So basically it's not very useful, because I'd have to go back and get rid of the stupid space. * Code completion isn't nearly as fast as WingIDE. * Auto-indentation could be smarter, such as dedenting after a 'return' statement. * The Problems view finds 52 errors in a file with 0. * Run As doesn't dump me into an interactive shell. -- Brian Beck Adventurer of the First Order From ivanlan at pauahtun.org Thu Apr 14 10:22:48 2005 From: ivanlan at pauahtun.org (Ivan Van Laningham) Date: Thu, 14 Apr 2005 08:22:48 -0600 Subject: A little request about spam References: <1113416856.914310.63930@l41g2000cwc.googlegroups.com> <740c3aec05041405157cb90625@mail.gmail.com> <7ee3dcd80504140551385ce25e@mail.gmail.com> Message-ID: <425E7CB8.85DD2BA4@pauahtun.org> Hi All-- The listowner could turn on the [PYTHON] headers. I'm not using spambayes yet, although I'm leaning toward it, but that step alone could save me some work when trying to decide based on subject line alone whether or not an email is spam. As it stands now, it's too easy to decide incorrectly that "Subject: Inelegant" is a spamdunk. Metta, Ivan mark hellewell wrote: > > On 4/14/05, James wrote: > > Yes - it's been like that for the last month or so now and it's quite > > annoying, especially seeing as before it was working at near enough > > 100% accuracy. > > And I don't suppose there's much we can do about it? > ---------------------------------------------- Ivan Van Laningham God N Locomotive Works http://www.andi-holmes.com/ http://www.foretec.com/python/workshops/1998-11/proceedings.html Army Signal Corps: Cu Chi, Class of '70 Author: Teach Yourself Python in 24 Hours From python-url at phaseit.net Mon Apr 11 15:47:46 2005 From: python-url at phaseit.net (Simon Brunning) Date: Mon, 11 Apr 2005 19:47:46 +0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Apr 11) Message-ID: QOTW: "I think my code is clearer, but I wouldn't go so far as to say I'm violently opposed to your code. I save violent opposition for really important matters like which text editor you use." - Roy Smith "You need to recursively subdivide the cake until you have a piece small enough to fit in your input buffer. Then the atomicity of the cake-ingestion operation will become apparent." - Scott David Daniels Various Python Meetup groups are meeting this week: http://python.meetup.com/ wxPython 2.5.5.1 is out... http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/7ca6358d54c9c617/84330473f542e5a6 ... for those that don't hate it. http://fraca7.free.fr/blog/index.php?2005/04/04/10-a-word-about-guis A couple of nice cookbook recipes - check your docstring coverage, and let Python tell you what you meant to type. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/355731 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/409000 Exceptions are't just for errors in Python. http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/925f0b16cf56c2ab/793e0ab436c91d48 The martellibot's working for Google! http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/c9d075e5f6b1f934/d6256652f5ffcc50 Backup your del.icio.usly linked pages to Gmail. http://llimllib.f2o.org/blog/serve/entry/delbackup How to tell whether a wave function corresponds to bosons or fermions. http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/e9cce91f429bc540/d78c7eec409154a4 No, I'm none the wiser, either. Still, some interesting algorithms in there. Rolling your own __deepcopy__. http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/41269228e1827a87/444ac776c4ffe00f IronPython is getting good coverage these days. http://informationweek.com/story/showArticle.jhtml?articleID=160403713 ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. For far, FAR more Python reading than any one mind should absorb, much of it quite interesting, several pages index much of the universe of Pybloggers. http://lowlife.jp/cgi-bin/moin.cgi/PythonProgrammersWeblog http://www.planetpython.org/ http://mechanicalcat.net/pyblagg.html comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Brett Cannon continues the marvelous tradition established by Andrew Kuchling and Michael Hudson of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ The Python Business Forum "further[s] the interests of companies that base their business on ... Python." http://www.python-in-business.org Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Cetus collects Python hyperlinks. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ (requires subscription) http://groups-beta.google.com/groups?q=python-url+group:comp.lang.python*&start=0&scoring=d& http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From jerf at jerf.org Sun Apr 10 20:12:02 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Sun, 10 Apr 2005 20:12:02 -0400 Subject: workaround for generating gui tools References: <1113061810.530359.172720@g14g2000cwa.googlegroups.com> <3bqgh6F6larilU1@individual.net> Message-ID: On Sun, 10 Apr 2005 13:02:27 -0700, Ken Godee wrote: > The original poster was just asking for an example of > how to sub class his code generated form into his program > for easy future updates, a "VERY STANDARD" way of doing it. I recognize your sarcasm, and I recognize the poor attitude it shows, but underneath it you do have a point. Continuing the (still IMHO very good) OO vs. procedural metaphor, the problem is that posting a trivial example of a dynamic interface, even were I to take the time to create one for you for free, would meet with exactly the same response that posting an OO snippet of some reasonable newsgroup size would receive from someone skeptical of OO. "Well, heck, I can do that all in a procedural program, and it would be a little shorter, too!" I am *particularly* not inclined to post a trivial example because it would do nothing to blunt your skepticism, or your sarcasm, and regardless, people who are genuinely curious simply need to try it for themselves. The advantages only start kicking in with large programs. But I do recall a book with similar themes, though I do not endorse it whole-heartedly: "Software Development On A Leash", which also gives you sample code for his particular framework. http://www.apress.com/book/bookDisplay.html?bID=29 My opinion of this book is like my opinion of XP: Every serious programmer ought to be exposed to the ideas contained in it (even if not by exposure to this book or the actual XP writings), and ought to give them serious thought, but 100% acceptance is not necessary. To address your sarcasm directly, there's 456 pages of examples in professionally written prose and real code samples, which I don't entirely agree with but they do serve to show the point, available for the price of $39.95. I consider my "obligation" to you discharged on this point; if you prefer sarcasm to investing anything into your personal development, that's your problem, not mine. (If this were a private email, I would have just deleted it, but the underlying criticisms, even if uncivilly phrased, bore answering.) Even though you probably won't adopt this guys framework, if you're paid anything at all for programming you'll recover the $40 in no time with the ideas in that book. From roy at panix.com Wed Apr 20 10:39:28 2005 From: roy at panix.com (Roy Smith) Date: 20 Apr 2005 10:39:28 -0400 Subject: Why Python does *SLICING* the way it does?? References: <1113976729.450677.261130@o13g2000cwo.googlegroups.com> Message-ID: Antoon Pardon wrote: >Op 2005-04-20, Roy Smith schreef : >> Antoon Pardon wrote: >> >>> Personnaly I would like to have the choice. Sometimes I prefer to >>> start at 0, sometimes at 1 and other times at -13 or +7. >> >> Argggh. Having two (or more!) ways to do it, would mean that every time I >> read somebody else's code, I would have to figure out which flavor they are >> using before I could understand what their code meant. That would be evil. > >This is nonsens. table[i] = j, just associates value j with key i. >That is the same independend from whether the keys can start from >0 or some other value. Do you also consider it more ways because >the keys can end in different values? There are certainly many examples where the specific value of the first key makes no difference. A good example would be for element in myList: print element On the other hand, what output does myList = ["spam", "eggs", "bacon"] print myList[1] produce? In a language where some lists start with 0 and some start with 1, I don't have enough information just by looking at the above code. From lothar at ultimathule.nul Tue Apr 5 12:11:05 2005 From: lothar at ultimathule.nul (lothar) Date: Tue, 5 Apr 2005 16:11:05 -0000 Subject: re module non-greedy matches broken References: Message-ID: <1155e6kak0ufk60@corp.supernews.com> give an re to find every innermost "table" element: innertabdoc = """
n

y

z
""" give an re to find every "pre" element directly followed by an "a" element: preadoc = """
a r n
l y
r
f g z
m b u c v
u
""" "John Ridley" wrote in message news:mailman.1325.1112651826.1799.python-list at python.org... > > Could you post some real-world examples of the problems you are trying > to deal with, please? Trying to come up with general solutions for > arbitrarily complex patterns is a bit to hard for me :) From onurb at xiludom.gro Mon Apr 18 11:42:16 2005 From: onurb at xiludom.gro (bruno modulix) Date: Mon, 18 Apr 2005 17:42:16 +0200 Subject: Zope3 and Plone In-Reply-To: <1113835544.983163.202080@z14g2000cwz.googlegroups.com> References: <1113835544.983163.202080@z14g2000cwz.googlegroups.com> Message-ID: <4263d559$0$24682$626a14ce@news.free.fr> Mir Nazim wrote: > Hi, > > I wanted to know what will happen to plone once Zope3 will be official > version. (snip) > what should be done. > Ask on the Plone mailing list ?-) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From sizer at nospam.com Thu Apr 14 15:51:04 2005 From: sizer at nospam.com (Sizer) Date: 14 Apr 2005 14:51:04 -0500 Subject: Looking for a very specific type of embedded GUI kit References: Message-ID: Thanks for your suggestions - after digging into SDL it looks pretty darn easy to add your own primitive devices at the low level (in src/video/), so that seems like the way to go. Once SDL is working, plenty of kits run on top of it. From flippa at flippac.org Thu Apr 7 18:04:21 2005 From: flippa at flippac.org (Philippa Cowderoy) Date: Thu, 7 Apr 2005 23:04:21 +0100 Subject: Lambda: the Ultimate Design Flaw In-Reply-To: References: <1498066.d23UzBfE8y@yahoo.com> <3b5ui7F6h0vgtU1@individual.net> Message-ID: On Thu, 7 Apr 2005, Frank Wilde wrote: >> Continuations rule! > > While continuations are a very interesting abstraction, the improvement > of structured programming was to be able to prove properties of your > programs in time linear to the size of the program instead of quadratic. > I don't see how giving arguments to the GOTO would help there. > By allowing you to build your own control structures, whose properties you prove once before using them to prove properties in the programs that use them. -- flippa at flippac.org There is no magic bullet. There are, however, plenty of bullets that magically home in on feet when not used in exactly the right circumstances. From Sylvain.Thenault at logilab.fr Thu Apr 14 10:04:40 2005 From: Sylvain.Thenault at logilab.fr (Sylvain =?iso-8859-1?Q?Th=E9nault?=) Date: Thu, 14 Apr 2005 16:04:40 +0200 Subject: [ANN] pylint 0.6.4 Message-ID: <20050414140440.GC5591@logilab.fr> Hello all, I'm pleased to announce a new release of PyLint. This release mainly fixes multivalued options bug and a systematic crash with python 2.2. Users should also use the latest logilab's common library (0.9.3). What's new ? ------------ * allow to parse files without extension when a path is given on the command line (test noext) * don't fail if we are unable to read an inline option (e.g. inside a module), just produce an information message (test func_i0010) * new message E0103 for break or continue outside loop (close #8883, test func_continue_not_in_loop) * fix bug in the variables checker, causing non detection of some actual name error (close #8884, test func_nameerror_on_string_substitution) * fix bug in the classes checker which was making pylint crash if "object" is assigned in a class inheriting from it (test func_noerror_object_as_class_attribute) * fix problem with the similar checker when related options are defined in a configuration file * new --generate-man option to generate pylint's man page (require the latest logilab.common (>= 0.9.3) * packaged (generated...) man page What is pylint ? ---------------- Pylint is a python tool that checks if a module satisfy a coding standard. Pylint can be seen as another pychecker since nearly all tests you can do with pychecker can also be done with Pylint. But Pylint offers some more features, like checking line-code's length, checking if variable names are well-formed according to your coding standard, or checking if declared interfaces are truly implemented, and much more (see http://www.logilab.org/pylint/ for the complete check list). The big advantage with Pylint is that it is highly configurable, customizable, and you can easily write a small plugin to add a personal feature. The usage it quite simple : $ pylint mypackage.mymodule This command will output all the errors and warnings related to the tested code (here : mypackage.mymodule), will dump a little summary at the end, and will give a mark to the tested code. Pylint is free software distributed under the GNU Public Licence. Home page --------- http://www.logilab.org/projects/pylint Download -------- ftp://ftp.logilab.org/pub/pylint Mailing list ------------ mailto://python-projects at logilab.org -- Sylvain Th?nault LOGILAB, Paris (France). http://www.logilab.com http://www.logilab.fr http://www.logilab.org From fabio.pliger at siavr.it Sat Apr 9 08:58:09 2005 From: fabio.pliger at siavr.it (Fabio Pliger) Date: Sat, 09 Apr 2005 12:58:09 GMT Subject: change the date string into timestamp References: Message-ID: You can use some date/time modules as: time built in module datetime wxDatetime from wx just take a look in the documentation... they are very simple to use. F.P. "praba kar" ha scritto nel messaggio news:mailman.1610.1113039505.1799.python-list at python.org... > Dear All, > > In Php strtotime() will change a date > string into timestamp. I want to know which > python function will change a date string > into timestamp. > > > Date string format is below > > Fri, 8 Apr 2005 09:22:14 +0900 > > regards > Prabahar > > ________________________________________________________________________ > Yahoo! India Matrimony: Find your life partner online > Go to: http://yahoo.shaadi.com/india-matrimony From eldiener_no_spam_here at earthlink.net Sat Apr 2 13:05:49 2005 From: eldiener_no_spam_here at earthlink.net (Edward Diener) Date: Sat, 02 Apr 2005 18:05:49 GMT Subject: Name of IDLE on Linux Message-ID: <1aB3e.2319$44.1393@newsread1.news.atl.earthlink.net> What is the name of the IDLE program on Linux and where is it installed in a normal Linux distribution ? I have installed all the Python 2.3.5 RPMs on my Fedora 3 system but I have no idea where they are installed or what IDLE is called. I lloked in the Python web pages to try to find a list of the files in the various installations, but was unable to find the information. From codecraig at gmail.com Fri Apr 15 09:54:35 2005 From: codecraig at gmail.com (codecraig) Date: 15 Apr 2005 06:54:35 -0700 Subject: Is Python appropriate for web applications? In-Reply-To: <425fbed1$0$10366$636a15ce@news.free.fr> References: <425fbed1$0$10366$636a15ce@news.free.fr> Message-ID: <1113573275.035694.281060@g14g2000cwa.googlegroups.com> for more information on web application frameworks check out http://pyre.third-bit.com/pyweb/ It is a project aimed at helping web app developers to figure out which frameworks to use, etc. good luck! From rkern at ucsd.edu Fri Apr 22 03:45:11 2005 From: rkern at ucsd.edu (Robert Kern) Date: Fri, 22 Apr 2005 00:45:11 -0700 Subject: regarding system function In-Reply-To: <20050422073533.28224.qmail@web8408.mail.in.yahoo.com> References: <20050422073533.28224.qmail@web8408.mail.in.yahoo.com> Message-ID: praba kar wrote: > I agree above statement but When I delete a directory > os.system('rm -rf test') > 0 > if directory is not present then I again try to > delete > os.system('rm -rf test') > now this time also It will print > 0 As Roman Neuhauser says, this is the correct behavior of the -f switch for rm. In [4]:os.system('rm -r foo') rm: foo: No such file or directory Out[4]:256 In [5]:os.system('rm -rf foo') Out[5]:0 -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From bogus@does.not.exist.com Fri Apr 15 11:55:02 2005 From: bogus@does.not.exist.com () Date: Fri, 15 Apr 2005 15:55:02 -0000 Subject: (no subject) Message-ID: #! rnews 2153 Newsgroups: comp.lang.python Path: news.xs4all.nl!newsspool.news.xs4all.nl!transit.news.xs4all.nl!195.241.76.212.MISMATCH!transit1.news.tiscali.nl!transit0.news.tiscali.nl!tiscali!newsfeed1.ip.tiscali.net!proxad.net!proxad.net!newshosting.com!nx02.iad01.newshosting.com!novia!feed2.newsreader.com!newsreader.com!newsread.com!news-xfer.newsread.com!nntp.abs.net!attws2!ip.att.net!NetNews1!xyzzy!nntp From: Harry George Subject: Re: Python's use in RAD X-Nntp-Posting-Host: cola2.ca.boeing.com Content-Type: text/plain; charset=us-ascii Message-ID: User-Agent: Gnus/5.09 (Gnus v5.9.0) Emacs/21.3 Lines: 46 Sender: hgg9140 at cola2.ca.boeing.com Organization: The Boeing Company References: Mime-Version: 1.0 Date: Fri, 15 Apr 2005 15:33:58 GMT Xref: news.xs4all.nl comp.lang.python:372620 "Ross Cowie" writes: > Hi, > > I am currenly a second year university student and was wondering if > you could help me ut. As part of a project i have decided to write > about python, i am not having very much luck with regards to finding > infrmation on pythons use in Rapid Application Development, and was > wondering of you could highlight some of the features that make it > suitable for RAD. Like the use of dinamic binding. > > Your healp would be appreciated. > > Hope to hear from you soon. > > Ross > > Generally we don't do homework here. But we can give you pointers. 1. Searching google for "python RAD" shows 148,000 hits, and at least the first few pages look relevant. Did you check? 2. "RAD" means different things to different people. Do you mean: a) Agile/Extreme Programming (2 or more people working together) b) Test-driven c) GUI builder d) Rapid edit-run cycle e) Lots of libraries so your work is just hooking together existing tools f) Dynamic, code-generated-on-the-fly, or other meta programming g) Project management experience in life cycle flow times and labor costs You need to understand your assignment in these terms, then you can investigate Python. 3. As a practical matter, Python does "a"-"g" quite well. Originally this was because of the rich-yet-clean syntax and batteries-included libraries. These days those factors still count, but they are enhanced by large numbers of "other" libraries and tools which have Python bindings. -- harry.g.george at boeing.com 6-6M21 BCA CompArch Design Engineering Phone: (425) 294-4718 From bvande at po-box.mcgill.ca Thu Apr 21 16:46:04 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Thu, 21 Apr 2005 16:46:04 -0400 Subject: New line In-Reply-To: <42680edf_3@mk-nntp-2.news.uk.tiscali.com> References: <42680a8a_1@mk-nntp-2.news.uk.tiscali.com> <42680edf_3@mk-nntp-2.news.uk.tiscali.com> Message-ID: <4268110C.2090704@po-box.mcgill.ca> ionic said unto the world upon 2005-04-21 16:34: > Ok sorry guys, > > using the python gui, if i hit the 'enter' key python just executes what > ever ive typed. It doesnt take me to the next line. > > How do i type several lines without executing after each line? > > Cheers A bit more precision in your question would help. I'm going to assume that by "Python GUI" you mean IDLE. You are likely trying to work in the interactive prompt. Very useful, but not for writing programs to save. For that, File->New and you will be in an IDLE window that lets you edit, run, and save files. (Be sure to save them with the .py extension, as IDLE doesn't automatically do so.) Best, brian vdB From steve at holdenweb.com Thu Apr 21 11:21:40 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 21 Apr 2005 11:21:40 -0400 Subject: python classes/file structure In-Reply-To: <1114091324.679130.294190@g14g2000cwa.googlegroups.com> References: <1114091324.679130.294190@g14g2000cwa.googlegroups.com> Message-ID: codecraig wrote: > What is the best/common way to structure ur python code for an > application? > > For example...if I create some custom GUI widgets I have this > > C:\stuff > --> gui > --: MyCustomWidget.py > --: TestWidgets.py > > so MyCustomWidget.py has one class, class MyCustomWidget: ... > > so from TestWidgets.py i have to do this > > from gui import * > > widget = gui.MyCustomWidget.MyCustomWidge() > > ...seems weird, how should I structure this? Is it not common to have > one class in a .py? > > thanks > gui/__init__.py should import MyCustomWidget. Then from gui import * will inject the "MyCustomWidget" name into the namespace of the TestWidgets module along with all other names defined by gui/__init__.py - you can control this by putting the names as strings in the "__all__" variable in __init__.py. regards Steve -- Steve Holden +1 703 861 4237 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ From beman at acm.org Tue Apr 5 12:12:40 2005 From: beman at acm.org (Beman Dawes) Date: Tue, 05 Apr 2005 16:12:40 GMT Subject: os.path query functions behavior incorrect? Message-ID: The docs for os.path.exists(), isdir(), and the like, do not describe behavior when an I/O error occurs. Testing on Windows XP SP2 with Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] on win32, on a machine with no a: drive, c: is a hard disk with a top level directory named "path" but without a top level directory named "foo", and d: is a CD drive (with no disc inserted): >>> import os >>> print os.path.exists("c:\\") True >>> print os.path.isdir("c:\\") True >>> print os.path.isdir("c:\\boost") True >>> print os.path.isdir("c:\\foo") False OK, that meets my expectations. But now: >>> print os.path.exists("a:\\") False >>> print os.path.isdir("a:\\") False >>> print os.path.exists("d:\\") True >>> print os.path.isdir("d:\\") True These to me are I/O errors that should result in an exception. Doing a command line dir a:\ reports "The system cannot find the path specified." Dir d:\ reports "The device is not ready." So are these os.path functions specified and implemented incorrectly? Should they instead throw exceptions for the above examples? If they are specified and implemented correctly, what is the rationale for this behavior? Thanks, --Beman From dan at dontspammecauseidontlikit.com Thu Apr 21 20:23:12 2005 From: dan at dontspammecauseidontlikit.com (Dan) Date: Fri, 22 Apr 2005 08:23:12 +0800 Subject: New line References: <42680a8a_1@mk-nntp-2.news.uk.tiscali.com> <42680edf_3@mk-nntp-2.news.uk.tiscali.com> Message-ID: On Thu, 21 Apr 2005 21:34:03 +0100, "ionic" wrote: Open a text editor and write your code. Save the file with a .py extension, i.e., myprogram.py. From the command line type 'python myfile.py' Dan > >Ok sorry guys, > >using the python gui, if i hit the 'enter' key python just executes what >ever ive typed. It doesnt take me to the next line. > >How do i type several lines without executing after each line? > >Cheers From steven.bethard at gmail.com Mon Apr 11 14:49:53 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 11 Apr 2005 12:49:53 -0600 Subject: singleton objects with decorators In-Reply-To: References: Message-ID: Uwe Mayer wrote: > Hi, > > I've been looking into ways of creating singleton objects. With Python2.3 I > usually used a module-level variable and a factory function to implement > singleton objects. > > With Python2.4 I was looking into decorators. The examples from PEP 318 > http://www.python.org/peps/pep-0318.html#examples > > don't work - AFAIK because: > - you cannot decorate class definitions (why was it left out?) > - __init__ must return None > > > However, you can use the decorator: > > def singleton(f): > instances = {} > def new_f(*args, **kwargs): > if (f not in instances): > instances[f] = f(*args, **kwargs) > return instances[f] > new_f.func_name = f.func_name > new_f.func_doc = f.func_doc > return new_f > > with a class that overwrites the __new__ methof of new-style classes: > > class Foobar(object): > def __init__(self): > print self > > @singleton > def __new__(self): > return object.__new__(Foobar) > > Is this particularly ugly or bad? Seems a little confoluted. Why can't you just use something like: class Singleton(object): def __new__(cls, *args, **kwargs): try: return cls.__instance__ except AttributeError: instance = cls.__instance__ = super(Singleton, cls).__new__( cls, *args, **kwargs) return instance class Foobar(Singleton): def __init__(self): print self ? STeVe From peter at engcorp.com Tue Apr 5 09:09:31 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 05 Apr 2005 09:09:31 -0400 Subject: Super Newbie Question In-Reply-To: <1112694325.360762.53260@z14g2000cwz.googlegroups.com> References: <1112657967.156094.75040@f14g2000cwb.googlegroups.com> <3be704F6gh9p1U1@individual.net> <1112694325.360762.53260@z14g2000cwz.googlegroups.com> Message-ID: Joey C. wrote: > To reply to many of your messages (I'm using Google right now due to > lack of a better newsreader at the moment), the issue with the > temporary file is that when I write something new to it, if the old > contents of the file was larger, not all of it will be overwritten. That's not likely true, unless you're doing something unusual here. Are you somehow terminating the process before it closes the file (and not using flush())? Or are you opening the file in some kind of "update" mode (with a "+") instead of just using "w"? Or something else? Or are you just assuming that what you describe will happen, but haven't actually tried it? -Peter From __peter__ at web.de Wed Apr 20 03:14:40 2005 From: __peter__ at web.de (Peter Otten) Date: Wed, 20 Apr 2005 09:14:40 +0200 Subject: Enumerating formatting strings References: <3cm9r2F6nif67U1@individual.net> Message-ID: Greg Ewing wrote: > Steve Holden wrote: > >> I've been wondering whether it's possible to perform a similar analysis >> on non-mapping-type format strings, so as to know how long a tuple to >> provide, > > I just tried an experiment, and it doesn't seem to be possible. > > The problem seems to be that it expects the arguments to be > in the form of a tuple, and if you give it something else, > it wraps it up in a 1-element tuple and uses that instead. > > This seems to happen even with a custom subclass of tuple, > so it must be doing an exact type check. No, it doesn't do an exact type check, but always calls the tuple method: >>> class Tuple(tuple): ... def __getitem__(self, index): ... return 42 ... >>> "%r %r" % Tuple("ab") # would raise an exception if wrapped "'a' 'b'" > So it looks like you'll have to parse the format string. Indeed. Peter From tzot at sil-tec.gr Mon Apr 25 10:24:36 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Mon, 25 Apr 2005 17:24:36 +0300 Subject: Python, Perl & PDF files References: Message-ID: On Mon, 25 Apr 2005 09:23:43 -0400, rumours say that rbt might have written: >Are there any plans in the near future to support PDF files in Python as > thoroughly and completely as Perl does? Before we let you know about our plans, what are *your* plans on this subject? :) [0] >http://cpan.uwinnipeg.ca/search?query=pdf&mode=dist >I love Python's clean syntax and ease of use, etc. But on some things >(PDF for example) as barbaric as Perl's syntax is, it does outshine >Python... I hate having to use Perl just to deal with PDF files. There are two issues here: a) a language, b) its library. You imply that the Perl syntax outshines Python's because it has _more thorough and complete support for PDF_, as you say. I don't see a connection, but rather I see a lure to provoke answers, which doesn't always work for you. For example, my reply would be more helpful and to the point if that reasoning was missing from your post. >What do others do??? Search google perhaps? Why do you feel that the first result of the query "python pdf" does not help you? [0] there's an ancient myth about a peasant's cart getting stuck in the mud, so the peasant starts calling out for help from goddess Athena. Another peasant passing by tells him: "Syn Athena kai kheira kinei", which means, more or less, "keep on calling Athena, but start also using your hands." I don't know any related myth of anglo-saxon origin to quote. -- TZOTZIOY, I speak England very best. "Be strict when sending and tolerant when receiving." (from RFC1958) I really should keep that in mind when talking with people, actually... From http Thu Apr 7 13:00:40 2005 From: http (Paul Rubin) Date: 07 Apr 2005 10:00:40 -0700 Subject: sorting a list and counting interchanges References: <1112826641.728979.278530@f14g2000cwb.googlegroups.com> Message-ID: <7xvf6yzflz.fsf@ruckus.brouhaha.com> Peter Nuttall writes: > I would just write a quicksort and have a counter in the swap function. > A cunning way to do it would be to multiply the counter by -1 for each > swap. if you want I can write what I had in mind. Wikipedia has a good > article of quicksort. Writing a sorting function from scratch for this purpose seems like reinventing the wheel. Tim's answer of simply counting the cycles (without having to pay attention to their length) is really clever. I didn't realize you could do that. Proving it is a cute exercise. Hint: any cycle of odd length has an even number of swaps, and any cycle of even length has an odd number of swaps (another exercise). http://en.wikipedia.org/wiki/Even_and_odd_permutations http://en.wikipedia.org/wiki/Permutation From __peter__ at web.de Wed Apr 20 09:03:17 2005 From: __peter__ at web.de (Peter Otten) Date: Wed, 20 Apr 2005 15:03:17 +0200 Subject: exception handling References: Message-ID: Mage wrote: > def error_msg(msg): > sys.exit(msg) > > try: > do_something() > if value != my_wish: > error_msg('Invalid input') > except: > print "Fatal IO or Network error" > > This doesn't work because sys.exit raises an exception. > > I know that I can define exception types after except, but there might > be many. Also I know I can write: > except: > if str(sys.exc_info()[0]) == 'exceptions.SystemExit': > raise > > But honestly I would like simething like that: > > except (!SystemExit): > > Is this possible somehow? try: # may raise any exception except SystemExit: raise # propagate SystemExit (and subclasses) except: # handle everything else Peter From timothy at open-networks.net Sat Apr 16 01:28:18 2005 From: timothy at open-networks.net (Timothy Smith) Date: Sat, 16 Apr 2005 15:28:18 +1000 Subject: pysvn install on freebsd Message-ID: <4260A272.2030205@open-networks.net> has anyone used or installed this on fbsd the install for it is totally redundant. i get this error for it make -f freebsd.mak clean all test cd ../Source && make -f pysvn_freebsd_py.mak clean make: cannot open pysvn_freebsd_py.mak. *** Error code 2 Stop in /usr/home/timothy/pysvn-1.1.2/Extension/Builder. From jeffrey at fro.man Sun Apr 17 17:39:00 2005 From: jeffrey at fro.man (Jeffrey Froman) Date: Sun, 17 Apr 2005 14:39:00 -0700 Subject: Decorator Syntax For Recursive Properties References: <11640g942e65da1@corp.supernews.com> Message-ID: <1165lrv6s0k5l22@corp.supernews.com> Peter Otten wrote: >> something like this didn't work for me: > But this will, I suppose: > > @property > def ancestors(self): > if self.parent: > return self.parent.ancestors + [self.parent] > return [] > > A non-recursive variant: > > @property > def ancestors(self): > result = [] > node = self.parent > while node: > result.append(node) > node = node.parent > result.reverse() > return result Indeed, both of these patterns suit my needs. Thanks very much for the eye-opening insights. Jeffrey From finite.automaton at gmail.com Mon Apr 25 18:04:04 2005 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: 25 Apr 2005 15:04:04 -0700 Subject: Bounding box on clusters in a 2D list References: <1114287475.805112.42550@o13g2000cwo.googlegroups.com> <1114305334.875783.235380@f14g2000cwb.googlegroups.com> <1114361783.478573.70430@g14g2000cwa.googlegroups.com> <1114378980.909132.216600@f14g2000cwb.googlegroups.com> <1114456596.990810.233630@z14g2000cwz.googlegroups.com> <1114457990.995627.224160@z14g2000cwz.googlegroups.com> <1114463614.451494.79010@o13g2000cwo.googlegroups.com> Message-ID: <1114466644.928560.284990@o13g2000cwo.googlegroups.com> def floodFill4(m, r, c, newCol, oldCol): stack = [ (r, c) ] while stack: r, c = stack.pop() if c >=0 and c < maxc and r >=0 and r< maxr and m[r][c]==oldCol: m[r][c] = newCol stack += [ (r+1, c), (r-1, c), (r, c+1), (r, c-1) ] From mwm at mired.org Sat Apr 30 17:27:44 2005 From: mwm at mired.org (Mike Meyer) Date: Sat, 30 Apr 2005 16:27:44 -0500 Subject: bytecode non-backcompatibility References: <1114418065.581779.52480@l41g2000cwc.googlegroups.com> <86wtqqm27r.fsf@guru.mired.org> <86is29n9cg.fsf@guru.mired.org> <86is29kkaw.fsf@guru.mired.org> Message-ID: <86u0loj6pb.fsf@guru.mired.org> Maurice LING writes: >>>Python can then have a built-in mechanism to read the description file >>>and download the source codes and do the standard "sudo python >>>setup.py install" to install the library into site-package. >> I don't like this - it would make Python depend on sudo being >> available. I'd rather it not do that, and let each systems >> administrator issue the command according to *their* security policy. > > If you are installing packages into your home directory, then sudo is > not needed. But if you are installing it for everybody's use, then it > is necessary. Fink runs using superuser privileges. No, sudo isn't necessary. It isn't provided by default for all Unix installations, so Python would have to add a dependency on it, which would be a bad thing. sudo is sufficient. Other means are also sufficient. It would be wrong for Python to assume a specific Unix security model (i.e. - "sudo") for installations. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From tjreedy at udel.edu Sun Apr 24 21:32:46 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 24 Apr 2005 21:32:46 -0400 Subject: Is this a bug? References: <426bb3e9$0$83084$ed2619ec@ptn-nntp-reader01.plus.net> <116nfblc10i9340@corp.supernews.com> Message-ID: > According to the language reference, > > An augmented assignment expression like x += 1 can be > rewritten as x = x + 1 to achieve a similar, but not > exactly equal effect. In the augmented version, x is only > evaluated once. > > I don't consider the two results you posted "similar". It continues "Also, when possible, the actual operation is performed in-place, meaning that rather than creating a new object and assigning that to the target, the old object is modified instead. ...Similarly, with the exception of the possible in-place behavior, the binary operation performed by augmented assignment is the same as the normal binary operations. " I take the behavior observed to be the exceptional in-place behavior referred to. But this could certainly be clearer. Also, Lib Ref 2.3.6.4 Mutable Sequence Types could have a line added to the table specifying the the operation 's+=x' is the same as s.extend(x). Terry J. Reedy From bokr at oz.net Thu Apr 21 13:32:27 2005 From: bokr at oz.net (Bengt Richter) Date: Thu, 21 Apr 2005 17:32:27 GMT Subject: Array of Chars to String References: <42673B51.4040804@v.loewis.de> Message-ID: <4267e35a.161797031@news.oz.net> On Thu, 21 Apr 2005 07:34:09 +0200, =?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?= wrote: >James Stroud wrote: >> astr = "Bob Carol Ted Alice" >> letters = "adB" > >Apparently nobody has proposed this yet: > >>>> filter(letters.__contains__, astr) >'Bad' >>>> filter(set(letters).__contains__, astr) >'Bad' > Baaad ;-) But since I'm playing the other side of the table for the moment, isn't filter to be deprecated? Regards, Bengt Richter From peter at engcorp.com Mon Apr 4 10:09:58 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 04 Apr 2005 10:09:58 -0400 Subject: redundant imports In-Reply-To: References: <86zmwgx0he.fsf@guru.mired.org> Message-ID: Serge Orlov wrote: > Mike Meyer wrote: > > >>The semantic behavior of "include" in C is the same as "from module >>import *" in python. Both cases add all the names in the included >>namespace directly to the including namespace. This usage is >>depreciated in Python ... > > > Did you mean discouraged? Or it's really slated for deprecation? Deprecated basically means "the use of this is discouraged", though because it is often followed by a comment like "and it will be removed in a future release", people sometimes are misled into thinking "deprecate" refers to the pending act of removal rather than the discouragement itself. So, yes, its use is deprecated (though I'm not sure if that's by any official statement, or simply by widespread convention), but no, that doesn't mean it is going to go away any time soon. -Peter From kasimov at i.com.ua Thu Apr 21 04:44:45 2005 From: kasimov at i.com.ua (Maxim Kasimov) Date: Thu, 21 Apr 2005 11:44:45 +0300 Subject: goto statement In-Reply-To: References: Message-ID: <426767FD.5050104@i.com.ua> 1. comment for debug It can be used in the same way, as the comments for debugging are used, but it will be easier than to use """ or ''', or using features of text-editors, when it is necessary to comment piece of code which already contains ''' or/and """ strings already, or there is another #-comments. Using goto, you do not need to edit a code, which is unfamiliar to you. 2. obfuscators goto can be used in the same way, as many of java-obfuscators do Speaking in other words: 1) goto exempts from necessity to install new software (it is critical for remote working, for example, installing X11 may be impossible at all) 2) enables to make new, better software (better obfuscators) -- Best regards, Maxim Kasimov mailto: kasimov at i.com.ua From radam2_ at _tampabay.rr.com Sat Apr 16 16:18:58 2005 From: radam2_ at _tampabay.rr.com (Ron_Adam) Date: Sat, 16 Apr 2005 20:18:58 GMT Subject: pre-PEP: Simple Thunks References: Message-ID: <3jl2615c5pckknicc32ccv2cktue3nh603@4ax.com> On Fri, 15 Apr 2005 16:44:58 -0700, Brian Sabbey wrote: > >Simple Thunks >------------- > >Thunks are, as far as this PEP is concerned, anonymous functions that >blend into their environment. They can be used in ways similar to code >blocks in Ruby or Smalltalk. One specific use of thunks is as a way to >abstract acquire/release code. Another use is as a complement to >generators. I'm not familiar with Ruby or Smalltalk. Could you explain this without referring to them? >A Set of Examples >================= > >Thunk statements contain a new keyword, 'do', as in the example below. The >body of the thunk is the suite in the 'do' statement; it gets passed to >the function appearing next to 'do'. The thunk gets inserted as the first >argument to the function, reminiscent of the way 'self' is inserted as the >first argument to methods. > >def f(thunk): > before() > thunk() > after() > >do f(): > stuff() > >The above code has the same effect as: > >before() >stuff() >after() You can already do this, this way. >>> def f(thunk): ... before() ... thunk() ... after() ... >>> def before(): ... print 'before' ... >>> def after(): ... print 'after' ... >>> def stuff(): ... print 'stuff' ... >>> def morestuff(): ... print 'morestuff' ... >>> f(stuff) before stuff after >>> f(morestuff) before morestuff after >>> This works with arguments also. >Other arguments to 'f' get placed after the thunk: > >def f(thunk, a, b): > # a == 27, b == 28 > before() > thunk() > after() > >do f(27, 28): > stuff() Can you explain what 'do' does better? Why is the 'do' form better than just the straight function call? f(stuff, 27, 28) The main difference I see is the call to stuff is implied in the thunk, something I dislike in decorators. In decorators, it works that way do to the way the functions get evaluated. Why is it needed here? When I see 'do', it reminds me of 'do loops'. That is 'Do' involves some sort of flow control. I gather you mean it as do items in a list, but with the capability to substitute the named function. Is this correct? Cheers, Ron From bdesth.quelquechose at free.quelquepart.fr Thu Apr 14 15:58:10 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 14 Apr 2005 21:58:10 +0200 Subject: How to debug SOAP using TCpMon and Python? In-Reply-To: References: Message-ID: <425ec741$0$865$636a15ce@news.free.fr> Jim a ?crit : > Hello, > > I am trying to debug a Python SOAP What about unit tests ? From simon.brunning at gmail.com Thu Apr 14 10:10:45 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Thu, 14 Apr 2005 15:10:45 +0100 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Apr 11) In-Reply-To: References: <3c670tF6jdeqrU1@individual.net> Message-ID: <8c7f10c605041407103f0fa367@mail.gmail.com> On 4/14/05, Peter Hansen wrote: > Greg Ewing wrote: > > (Darn. I finally say something that gets into Quote of the > > Week, and it's attributed to someone else! :-) :-) :-) > > +1 on this for meta-QOTW, solving both problems... Yeah, but to whom do I attribute it? ;-) -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From Grossi Fri Apr 15 23:21:03 2005 From: Grossi (Grossi) Date: 15 Apr 2005 22:21:03 -0500 Subject: Do You Want To Know For Sure That You Are Going To Heaven? The reason some people don't know for sure if they are going to Heaven when they die is because they just don't know. The good news is that you can know for sure that you are going to Heaven which is described in the Holy Bible as a beautiful place with no death, sorrow, sickness or pain. (newsgroup-post 140) References: <1113613608.511723.298610@o13g2000cwo.googlegroups.com> Message-ID: <901161dqkqtr2gkhf3qb4j6mvecgb8ivuf@4ax.com> Nuf said. From iny+news at iki.fi Sun Apr 24 03:36:37 2005 From: iny+news at iki.fi (Ilpo =?iso-8859-1?Q?Nyyss=F6nen?=) Date: Sun, 24 Apr 2005 10:36:37 +0300 Subject: Object oriented storage with validation (was: Re: Caching compiled regexps across sessions (was Re: Regular Expressions - Python vs Perl)) References: <1114092105.964664.211430@l41g2000cwc.googlegroups.com> Message-ID: [reorganized a bit] Ville Vainio writes: > Why don't you use external validation on the created xml? Validating > it every time sounds like way too much like Javaic B&D to be fun > anymore. Pickle should serve you well, and would probably remove about > half of your code. "Do the simplest thing that could possibly work" > and all that. What is the point in doing validation if it isn't done every time? Why wouldn't I do it every time? It isn't that slow thing to do. Pickle doesn't have validation. I am not comfortable for using it as storage format that should be reliable over years when the program evolves. It also doesn't tell me if my program has put something other to the data than I meant to. The program will just throw some weird exception. I want to do the simplest thing, but I also want something that helps me keep the program usable also in the future. I prefer putting some resources to get some validation to it initially than use later more resouces to do something with undetermined lump of data. > >> python has shipped with a fast XML parser since 2.1, or so. > > Ilpo> With what features? validation? I really want a validating > Ilpo> parser with a DOM interface. (Or something better than DOM, > Ilpo> must be object oriented.) > > Check out (coincidentally) Fredrik's elementtree: > > http://effbot.org/zone/element-index.htm At least the interface looks quite simple and usable. With some validation wrapping over it, it might be ok... > Ilpo> And my point is that the regular expression compilation can > Ilpo> be a problem in python. The current regular expression > Ilpo> engine is just unusable slow in short lived programs with a > Ilpo> bit bigger amount of regexps. And fixing it should not be > Ilpo> that hard: an easy improvement would be to add some kind of > Ilpo> storing mechanism for the compiled regexps. Are there any > Ilpo> reasons not to do this? > > It should start life as a third-party module (perhaps written by you, > who knows :-). If it is deemed useful and clean enough, it could be > integrated w/ python proper. This is clearly something that should not > be in the python core, because the regexps themselves aren't there > either. How can it work automatically in separate module? Replacing the re.compile with something sounds possible way of getting the regexps, but how and where to store the compiled data? Is there a way to put it to the byte code file? Maybe I need to take a look at it when I find the time... -- Ilpo Nyyss?nen # biny # /* :-) */ From franz.steinhaeusler at utanet.at Thu Apr 28 03:52:53 2005 From: franz.steinhaeusler at utanet.at (Franz Steinhaeusler) Date: Thu, 28 Apr 2005 09:52:53 +0200 Subject: Which IDE is recommended? References: <426f90ac$1_2@rain.i-cable.com> <1114612588.435456.296960@z14g2000cwz.googlegroups.com> Message-ID: On 27 Apr 2005 07:36:28 -0700, "Matt" wrote: >The ActiveGrid IDE is a sample app with wxPython. It has a lot of good >features including a source code debugger that allows you to debug wx >apps and set breakpoints from the code editor. I am also biased >though--I work on that IDE and use it for all my coding. Its pretty far >along on Windows and getting better on Linux. We just got it working on >a Mac yesterday so that version won't be out for a bit. Little OT: I tried to run or debug the current open file. but it didn't work. As I found no forum, I ask here: Traceback (most recent call last): File "C:\Python24\Lib\site-packages\wx-2.6-msw-ansi\wx\lib\pydocview.py", line 930, in ProcessEvent return DocMDIParentFrameMixIn.ProcessEvent(self, event) File "C:\Python24\Lib\site-packages\wx-2.6-msw-ansi\wx\lib\pydocview.py", line 325, in ProcessEvent return wx.GetApp().ProcessEvent(event) File "C:\Python24\Lib\site-packages\wx-2.6-msw-ansi\wx\lib\pydocview.py", line 1636, in ProcessEvent if service.ProcessEvent(event): File "C:\Programme\wxPython2.6 Docs and Demos\samples\ide\activegrid\tool\Debu ggerService.py", line 1534, in ProcessEvent self.OnRunProject(event) File "C:\Programme\wxPython2.6 Docs and Demos\samples\ide\activegrid\tool\Debu ggerService.py", line 1633, in OnRunProject dlg = CommandPropertiesDialog(self.GetView().GetFrame(), 'Run', projectServi ce, None) File "C:\Programme\wxPython2.6 Docs and Demos\samples\ide\activegrid\tool\Debu ggerService.py", line 1933, in __init__ self._selectedProjectDocument = self._projectDocumentList[selectedIndex] IndexError: list index out of range Where to ask for help otherwise? -- Franz Steinh?usler http://drpython.sourceforge.net/ http://mitglied.lycos.de/drpython/ From jorl.shefner at comcast.net Fri Apr 15 09:30:00 2005 From: jorl.shefner at comcast.net (Jorl Shefner) Date: 15 Apr 2005 06:30:00 -0700 Subject: new to mac OS10 In-Reply-To: References: Message-ID: <1113571800.485209.169320@z14g2000cwz.googlegroups.com> If you simply want the latest python to run from the command line, then compiling the source code works fine on the mac. I just installed 2.4.1 on Os 10.3.8 last week without any problems. http://www.python.org/ftp/python/2.4.1/Python-2.4.1.tgz "./configure" "make" "make install" J.S. From timothy.grant at gmail.com Thu Apr 14 10:45:08 2005 From: timothy.grant at gmail.com (Timothy Grant) Date: Thu, 14 Apr 2005 07:45:08 -0700 Subject: A little request about spam In-Reply-To: References: <1113416856.914310.63930@l41g2000cwc.googlegroups.com> <740c3aec05041405157cb90625@mail.gmail.com> Message-ID: On 4/14/05, mark hellewell wrote: > On 4/14/05, BJ?rn Lindqvist wrote: > > Please do not reply to spam. Replying to spam makes it much harder for > > spam filters to catch all the spam or will produce very many false > > positives. Atleast that's how gmail's filter works. And if you must > > reply, please change the subject line. > > Is anybody else finding that Gmails spam filter has started > labelling a lot of python-list emails as spam? About 20 > python-list emails a day end up getting caught by their > filter and I'm having to manually go in and mark them > as "Not spam". Absolutely! I didn't know if it were just me or what but starting a couple of weeks ago, The filter went from near perfect to trapping 20+ good emails per day. Very annoying. -- Stand Fast, tjg. From rkern at ucsd.edu Mon Apr 25 07:27:18 2005 From: rkern at ucsd.edu (Robert Kern) Date: Mon, 25 Apr 2005 04:27:18 -0700 Subject: What's do list comprehensions do that generator expressions don't? In-Reply-To: <426CBF86.4040407@freemail.gr> References: <86ll77pgqz.fsf@guru.mired.org> <426CB5DC.1050301@freemail.gr> <426CBF86.4040407@freemail.gr> Message-ID: jfj wrote: > Robert Kern wrote: > >> jfj wrote: >> >>> 2) to convert a list/tuple/string to a list, which is >>> done extremely fast. >> >> Add "any iteratable". Genexps are iterables. > > The thing is that when you want to convert a tuple to a list > you know already the size of it and you can avoid using append() > and expanding the list gradually. For iterables you can't avoid > appending items until StopIteration so using list() doesn't have > any advantage. But no real disadvantage either. > The OP was about genexps vs list comprehensions > but this is about list() vs. list comprehensions. Yes, and list(genexp) replaces list comprehensions rather handily. There's very little reason to prefer list comprehensions over the list(genexp) construction. If anything, it's pretty much a wash. That was the OP's question: [mike] > when would I use a list comp instead of a generator expression if > I'm going to require 2.4 anyway? >> Possibly. I find them too similar with little enough to choose between >> them, hence the OP's question. > > One solution is to forget about list(). If you want a list use []. > Unless you want to convert a tuple... > > I think a better question would be "What do *generator expressions* do > that list comprehensions don't?". And always use list comprehensions > unless you want the extra bit. What we have now are two very similar constructs, one of which is more general and subsumes nearly all the uses of the other. The presence of both is confusing, as evidenced by the fact that the OP asked his question. In the Great Breaking of Backwards Compatibility, list comprehensions should go away. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From dalke at dalkescientific.com Sat Apr 9 14:17:27 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Sat, 09 Apr 2005 18:17:27 GMT Subject: Counting iterations References: <1112994185.983954.234650@l41g2000cwc.googlegroups.com> <4256f4c0$0$2603$da0feed9@news.zen.co.uk> <1112998861.316958.152060@g14g2000cwa.googlegroups.com> <1113064744.144787.315120@o13g2000cwo.googlegroups.com> Message-ID: runes wrote: > You should avoid the "a" + "b" + "c" -kind of concatenation. As strings > at immutable in Python you actually makes copies all the time and it's > slow! The OP wrote print "pet" + "#" + num_pets (properly str(num_pets) ) You recommended the "alternative used in Steven Bethard's example" print 'pet#%i' % (i + 1) because "it's slow". I disagree, it isn't for this code. It's comparable in performance to interpolation and most of the time is spent in converting int -> string. Indeed if the object to be merged is a string then the addition version is faster than interpolation. Here's the details. The string concatenation performance that you're talking about doesn't hit until there are multiple appends to the same string, where "multiple" is rather more than 2. The advice usually applies to things like text = "" for line in open(filename, "U"): text += line which is much slower than, say lines = [] for line in open(filename, "U") lines.append(line) text = "".join(lines) or the more modern text = "".join(open(filename, "U")) to say nothing of text = open(filename, "U").read() :) Anyway, to get back to the example at hand, consider what happens in "pet#%i" % (i+1) (NOTE: most times that's written %d instead of %i) The run-time needs to parse the format string and construct a new string from the components. Internally it does the same thing as "pet#" + str(i+1) except that it's done at the C level instead Python and the implementation overallocates 100 bytes so there isn't an extra allocation in cases like this. Personally I would expect the "%" code to be about the same performance as the "+" code. Of course the real test is in the timing. Here's what I tried. NOTE: I reformatted by hand to make it more readable. Line breaks and the \ continuation character may have introduced bugs. First, the original code along with the 'str()' correction. % python /usr/local/lib/python2.3/timeit.py -s \ 'pets = ["cat", "dog", "bird"]' \ 'num_pets=0' 'for pet in pets:' \ ' num_pets += 1' \ ' s="pet" + "#" + str(num_pets)' 100000 loops, best of 3: 14.5 usec per loop There's no need for the "pet" + "#" so I'll turn that into "pet#" % python /usr/local/lib/python2.3/timeit.py -s \ 'pets = ["cat", "dog", "bird"]' \ 'num_pets=0' \ 'for pet in pets:' \ ' num_pets += 1' \ ' s="pet#" + str(num_pets)' 100000 loops, best of 3: 12.8 usec per loop That's 1.3 extra usecs. By comparison here's the "%" version. % python /usr/local/lib/python2.3/timeit.py -s \ 'pets = ["cat", "dog", "bird"]'\ 'num_pets=0' \ 'for pet in pets:' \ ' num_pets += 1' \ ' s="pet#%s" % num_pets' 100000 loops, best of 3: 10.8 usec per loop I'm surprised that it's that much faster - a good 2 microseconds and that isn't the only code in that loop. But both the "%" and "+" solutions need to convert the number into a string. If I use an existing string I find % python /usr/local/lib/python2.3/timeit.py -s \ 'pets = ["cat", "dog", "bird"]' \ 'num_pets=0' \ 'for pet in pets:' \ ' num_pets += 1' \ ' s="pet#" + pet' 100000 loops, best of 3: 4.62 usec per loop So really most of the time - about 8 usec - is spent in converting int -> string and the hit for string concatenation or interpolation isn't as big a problem. Compare with the string interpolation form of the last version % python /usr/local/lib/python2.3/timeit.py -s \ 'pets = ["cat", "dog", "bird"]' \ 'num_pets=0' 'for pet in pets:' \ ' num_pets += 1' \ ' s="pet#%s" % pet' \ 100000 loops, best of 3: 7.55 usec per loop In this case you can see that the % version is slower (by 2usec) than the + version. I therefore disagree with the idea that simple string concatenation is always to be eschewed over string interpolation. Andrew dalke at dalkescientific.com From chris at angband.org Wed Apr 27 15:52:19 2005 From: chris at angband.org (Operation Latte Thunder) Date: Wed, 27 Apr 2005 19:52:19 +0000 (UTC) Subject: Shutting down twisted reacotr Message-ID: I have a simple ( I hope ) problem that I have been baning my head against all day. I have isolated it down to a very small demo script, which I will include below. Basically, I want to have twisted run until an event makes it stop. My problem is that my reactor.stop() doesn't seem to do anything if its not called via a calllater or an equivilent. Unfortunately, my google-fu seems weak today, as I have not been able to discern its solution. Without further adieu: from thread import start_new_thread import time from twisted.internet import reactor def shutdown(): time.sleep( 1 ) print "Stopping" reactor.stop() start_new_thread ( shutdown, () ) reactor.run() print "done" This will continue to run even after printing "Stopping" any ideas? -- chris at acheris.net | Roma Invicta! From benmarkwell at gmail.com Fri Apr 1 22:53:55 2005 From: benmarkwell at gmail.com (Ben) Date: 1 Apr 2005 19:53:55 -0800 Subject: New to programming question In-Reply-To: <424d1573.11134991@news.oz.net> References: <1112325275.120122.100800@o13g2000cwo.googlegroups.com> <0_63e.19914$C7.11056@news-server.bigpond.net.au> <424d1573.11134991@news.oz.net> Message-ID: <1112414035.125070.226060@f14g2000cwb.googlegroups.com> Joal was right. It is a bit beyond me. But I appreciate your response. From martin.witte at gmail.com Sat Apr 30 07:32:46 2005 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 30 Apr 2005 04:32:46 -0700 Subject: Library Naming Conventions. In-Reply-To: <1114851378.781754.194030@z14g2000cwz.googlegroups.com> References: <1114851378.781754.194030@z14g2000cwz.googlegroups.com> Message-ID: <1114860766.488589.152380@o13g2000cwo.googlegroups.com> see http://www.python.org/peps/pep-0008.html for naming conventions and other style issues From bokr at oz.net Sat Apr 2 16:59:54 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 02 Apr 2005 21:59:54 GMT Subject: Performance issue References: Message-ID: <424f118c.141207545@news.oz.net> On Sat, 02 Apr 2005 10:29:19 -0800, Shalabh Chaturvedi wrote: >Tom Carrick wrote: >> Hi, >> >> In my attempted learning of python, I've decided to recode an old >> anagram solving program I made in C++. The C++ version runs in less >> than a second, while the python takes 30 seconds. I'm not willing to >> think it's just python being slow, so I was hoping someone could find >> a faster way of doing this. Also, I was wondering if there was a more >> builtin, or just nicer way of converting a string to a list (or using >> the sort function on a list) than making a function for it. > > > >Others have already given a good commentary and alternate suggestions. >Here is some more (and some disagreements): > >* Know your data structures (and how long different operations take). >Like don't do del L[0] unless required. This generally comes from >experience (and asking on this list). > >* list(any_sequence_here) will build a list from the sequence. There are >usually easy ways of converting built-in types - the Python docs will >help you here. > >* Try to write code as close to an english description of the problem as >possible. For example 'for word in words:' rather than using counters >and []. This is usually faster, clearer and IMO an important ingredient >of being 'Pythonic'. > >Anyway here's my rendition of your program: > >### >anagram = raw_input("Find anagrams of word: ") >lanagram = list(anagram) >lanagram.sort() >sorted_anagram = ''.join(lanagram).lower() > >f = open('/usr/share/dict/words', 'r') > >found = [] > >for word in f: > word = word.strip('\n') > if len(word)==len(sorted_anagram): > sorted_word = list(word) > sorted_word.sort() > sorted_word = ''.join(sorted_word) > if sorted_word == sorted_anagram: > found.append(word) > >print "Anagrams of %s:" % anagram > >for word in found: > print word >### > >Hopefully it is fast enough. > If doing more than one anagram, I think making a set of anagram dictionaries (one for each word length) and pickling them in separate files for later re-use might help. E.g., (untested!!) to make a dict (by wordlength) of anagram dicts, something like d = {} for word in open('/usr/share/dict/words'): word = word.strip().lower() d.setdefault(len(word), {}).setdefault(''.join(sorted(word)), []).append(word))) Then for wlen, adic in d.items(): pickle_file_name = 'anagram_%s'% wlen # pickle adic and write it out to the file ... Then the anagram utility can look for the appropriate pickle file per word length, (i.e., 'anagram_%s'%len(word.strip())) and just load it to anadict and print anadict(''.join(sorted(word.strip().lower())). That's a sketch. Untested!! Gotta go ;-/ Regards, Bengt Richter From dcrespo at gmail.com Mon Apr 11 16:10:46 2005 From: dcrespo at gmail.com (dcrespo) Date: 11 Apr 2005 13:10:46 -0700 Subject: Distributing Python Apps and MySQL In-Reply-To: References: <1112887332.324949.318960@z14g2000cwz.googlegroups.com> Message-ID: <1113250246.331556.308900@z14g2000cwz.googlegroups.com> Hi. Thank you for your answer. I had been working on NSInstaller since it was the first one I looked up. I take advantage of this comment to say that NSInstaller really works (for whoever that is reading this) ;) From jdh2358 at gmail.com Mon Apr 18 16:40:09 2005 From: jdh2358 at gmail.com (jdh2358 at gmail.com) Date: 18 Apr 2005 13:40:09 -0700 Subject: ANN: Veusz 0.5 - a scientific plotting package References: <1113810917.134164.113060@g14g2000cwa.googlegroups.com> Message-ID: <1113856809.069302.17250@g14g2000cwa.googlegroups.com> Hi Jeremy, I'm the matplotlib author -- I'm writing under a different email address since my email server seems to be dying... I'll start by saying that I for one won't criticize you for rolling you own plotting package rather than join forces with an existing project. I've been accused of the same, on more than one occasion :-) But I'm also aware of the problem that this creates -- the tyranny of choice. python is so fun to code in that many developers are looking for a reason to find an existant package inadequate so they have an excuse to write their own replacement. Hence we have a proliferation of web-app frameworks, plotting packages, array objects and so on. There is a lot of duplicated effort in many arenas and it would be nice to collaborate more. I read over your scipy list of problems that you found in matplotlib -- some were helpful and some, as you note, have been long fixed. One critique you might flesh out for me is the notion that matplotlib's object model is baroque -- most of the developers feel the object model is fairly solid. You weren't by chance, trying to use the procedural pylab (aka matlab) interface, were you, since pylab itself is just a wrapper of the OO matplotlib API? One area in the object model that we plan to change is to make high level plot objects (scatter, error, histogram) etc, proper objects, ala gnuplot. Right now they are methods that generate primitive objects (lines, rectangles, text, etc). Another area you identify as a problem with matplotlib is the need to regenerate the entire graph when one property is changed. This is true in one way and false in another. matplotlib does have a proper object model -- eg, you can selectively change the facecolor of a marker w/o regenerating the graph scene. But the *drawing* hierarchy (as opposed to the object hierarchy) needs some work . Once you have changed a property, the entire graph is redrawn. This is a known limitation and will change in the not-too-distant-future. One advantage of working in mainstream in open source software is the network effect. With 10 some-odd developers including institutions such as the U of C, STScI, JPL and NOAA, bugs and limitations of matplotlib tend to be fixed within minutes, days, weeks or months. Your package looks very nice. It specifically addresses two limitations in matplotlib that we would like to address -- a GUI interface for creating figures and a way to save the figure at any point as a high level description (rather than an image). I do wish you had publicly voiced the problems you ran into along the way; I just searched the archives and saw only one post from you on the users list which I answered 28 minutes later with http://sourceforge.net/mailarchive/message.php?msg_id=10124206 after which I never heard from you again. Such response times are fairly typical on the list, but if you don't report the bugs and follow up on the suggested fixes, we can't fix them. Anyway, nice work on veusz. Are you committed to the GPL license? matplotlib uses a more permissive license (PSF compatible) mainly to encourage contributions from the commercial sector. As you suggest, it is still possible for someone to take the work you've done on the GUI frontend and expose matplotlib as a backend based on your prior experiments. The NASA Jet Propulsion Laboroatory and others are supporting the QT backend, and they might be willing to contribute some time to porting your GUI frontend to matplotlib, provided the license of veusz was compatible with the mpl license. There are two specific issues you raised in the scipy post you linked to that I'll take issue with: >> In my experience, the plotting code isn't that hard to do. >> The hardest part was making the axes look good. In my experience, the hardest part of plotting code is supporting all the ways in which people want to use the code, and that includes embedding the plot in their GUI of choice, working across platforms, supporting script based, interactive shell work, application developers, web app developers and so on. There are quite a few plotting idioms that are mission critical to many developers, and supporting them all is a complex task. I'm fond of pointing out the combinatorial problem -- take every GUI, cross two major versions in the wild, cross the big-three platforms, cross the standard ways in which people want to work with their plots and you have a lot of work to do. veusz "solves" this problem by restricting choice, which is a respectable solution. matplotlib takes the opposite tack and tries to support the user in the environment in which they want to work. The second point is >> I've done 90% of what's needed there. Basically, I'll be happy >> when contouring and images are added. I tend to disagree that contouring and images are only 10% -- good contouring, contour labeling, and image support strong enough to satisfy people for whom images are their lifeblood is hard, and almost impossible to do efficiently in pure python. matplotlib isn't there yet, but the support for both is pretty strong and getting better, and matplotlib is increasingly being used by astronomers for image display. But I see from your web page that you too are an astronomer, so I expect that you will handle these areas nicely; again, too bad we couldn't collaborate more. Another tough area to do right of course is nonlinear transformations (polar, log, mapping projections) with the associated problems of proper tick locating and labeling... Cheers, JDH From gandalf at geochemsource.com Fri Apr 8 03:39:01 2005 From: gandalf at geochemsource.com (Laszlo Zsolt Nagy) Date: Fri, 08 Apr 2005 09:39:01 +0200 Subject: __builtins__ wreidness Message-ID: <42563515.8080401@geochemsource.com> Given this module "test.py": print type(__builtins__) I ran into a wreid thing. Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> __builtins__ >>> type(__builtins__) >>> import test >>> What? __builtins__ is a dict when used in a module, but it is a module when used interactively? Why? -- _________________________________________________________________ Laszlo Nagy web: http://designasign.biz IT Consultant mail: gandalf at geochemsource.com Python forever! From fred at adventistcare.org Sat Apr 9 06:36:24 2005 From: fred at adventistcare.org (Sells, Fred) Date: Sat, 9 Apr 2005 06:36:24 -0400 Subject: Equivalent string.find method for a list of strings Message-ID: <777056A4A8F1D21180EF0008C7DF75EE03317438@sunbelt.org> linenums = [i for i in range(len(lines)) if lines[i].find(searchstring) >=0] -----Original Message----- From: Joshua Ginsberg [mailto:listspam at flowtheory.net] Sent: Friday, April 08, 2005 4:12 PM To: python-list at mail.python.org Subject: Re: Equivalent string.find method for a list of strings try: filter(lambda x: lines[x].find(searchstring) != -1, range(len(lines))) That will return a list with the indices of every line containing a hit for your search string. -jag Joshua Ginsberg -- joshg at brainstorminternet.net Brainstorm Internet Network Operations 970-247-1442 x131 On Apr 8, 2005, at 1:52 PM, Jeremy Conlin wrote: > Joshua Ginsberg wrote: > >> Try: >> >> filter(lambda x: x.find(searchstring) != -1, lines) >> > I really like this option, but what I want to know where in the file > this line exists (i.e. line 42). Can I somehow access this line and > the lines immediately following? > Thanks, > Jeremy > -- http://mail.python.org/mailman/listinfo/python-list From none Wed Apr 27 15:03:55 2005 From: none (Hansan) Date: Wed, 27 Apr 2005 21:03:55 +0200 Subject: Problem with sending a variable(python) while using html Message-ID: <426fe1f8$0$636$ba624c82@nntp02.dk.telia.net> Hi all. I am working on a webpage where I use python and html. When I want to send one variable to a new script/page I use the following code: 0) print '''''' This works fine, the problem occurs when I want to send a variable to a page while using a 1)meta refresh or a 2)Href. 1) and 2) works fine as they are but not when I try to send the variable with them. The working version of 1) and 2) could look like 1) print ''''' 2) print "", "some text", "" What I have to do is to combine 0) with 1) so that I can send the variable while using a meta refresh and 0) and 2) But I no matter how hard I try I cant get it done. Can any of you experienced users give me some guidance. I would really appreciate it. Thanks From sunnan at handgranat.org Fri Apr 1 22:39:53 2005 From: sunnan at handgranat.org (Sunnan) Date: Sat, 02 Apr 2005 03:39:53 GMT Subject: Pseudocode in the wikipedia In-Reply-To: References: <1112362451.848227.208120@z14g2000cwz.googlegroups.com> Message-ID: James Stroud wrote: > bob == (carol = 2): > if bob = (bob or carol): > bob == 4 > > But no one could figure out what bob was supposed to equal anyway. Wouldn't bob equal the boolean result of the expression (carol = 2)? From prabapython at yahoo.co.in Sat Apr 9 05:51:16 2005 From: prabapython at yahoo.co.in (praba kar) Date: Sat, 9 Apr 2005 10:51:16 +0100 (BST) Subject: change the date string into timestamp In-Reply-To: 6667 Message-ID: <20050409095116.4371.qmail@web8409.mail.in.yahoo.com> --- Michael Hoffman wrote: > praba kar wrote: > > > In Php strtotime() will change a date > > string into timestamp. I want to know which > > python function will change a date string > > into timestamp. > > What do you mean by "a timestamp?" > -- Time stamp means datestring will converted as seconds example is below Fri, 8 Apr 2005 09:22:14 +0900 this date value time stamp is 1112962934 ________________________________________________________________________ Yahoo! India Matrimony: Find your life partner online Go to: http://yahoo.shaadi.com/india-matrimony From andrea.gavana at agip.it Fri Apr 29 03:26:40 2005 From: andrea.gavana at agip.it (andrea.gavana at agip.it) Date: Fri, 29 Apr 2005 09:26:40 +0200 Subject: Webbrowser On Windows Message-ID: Hello NG, I am using the webbrowser module (on Windows 2000/XP), and I am wondering if anyone knows how to use the input arguments "new". On Windows, it seems to be ignored. By looking at the commands it does on Windows: class WindowsDefault: def open(self, url, new=0, autoraise=1): os.startfile(url) def open_new(self, url): self.open(url) It seems to me that there is no way to create a new instance of Internet Explorer (if there are already some IE windows opened). Does anyone know a possible solution? Or a workaround (without using startfile, maybe?) that will force IE to create a new instance? Thank you for every suggestions. Andrea. ------------------------------------------------------------------------------------------------------------------------------------------ Message for the recipient only, if received in error, please notify the sender and read http://www.eni.it/disclaimer/ From Scott.Daniels at Acm.Org Thu Apr 7 20:40:12 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Thu, 07 Apr 2005 17:40:12 -0700 Subject: curious problem with large numbers In-Reply-To: References: <723eb693050407124816431b6a@mail.gmail.com> Message-ID: <4255cd93$1@nntp0.pdx.net> Terry Reedy wrote: > On my Windows machine with 2.2.1, I get exactly what you expected: > >>>>1e10000 > 1.#INF > ... > If you get wrong behavior on a later version, then a bug has been > introduced somewhere, even perhaps in VC 7, used for 2.4. Nope, it is also there for 2.3.4 (May 25 2004, 21:17:02). This is not necessarily a bug in the sense of a fixable bug; floating point has vagaries that are not necessarily easily controllable from the C source side. --Scott David Daniels Scott.Daniels at Acm.Org From rdm at rcblue.com Sun Apr 17 04:00:46 2005 From: rdm at rcblue.com (Dick Moores) Date: Sun, 17 Apr 2005 01:00:46 -0700 Subject: Compute pi to base 12 using Python? In-Reply-To: <1113545886.372148.82420@z14g2000cwz.googlegroups.com> References: <7x3btui27t.fsf@ruckus.brouhaha.com> <1113545886.372148.82420@z14g2000cwz.googlegroups.com> Message-ID: <6.2.1.2.2.20050417004715.05ada940@rcblue.com> M.E.Farmer wrote at 23:18 4/14/2005: > > >Using the GNU "bc" utility: > > > > > > $ bc -l > > > bc 1.06 > > > Copyright 1991-1994, 1997, 1998, 2000 Free Software Foundation, >Inc. > > > This is free software with ABSOLUTELY NO WARRANTY. > > > For details type `warranty'. > > > scale = 3000 # number of output places wanted > > > obase = 12 # output base > > > print 4 * a(1) # pi = 4*arctan(1) Wow! this got me the 3003 (changed from 3000) digits of pi to base 12 in 60.8 secs. No, I didn't count them yet, nor am I sure they're correct. But I'd bet on them.. Could someone remind me how to get the output of bc -l into a text file on Windows? (I've tried employing " > pi3003.txt" in various ways) OR, how to copy and paste from the command line window, or whatever that window is called? (Sorry for the OT question.) BTW I found a nice set of SCO UNIX man pages at . Dick From danb_83 at yahoo.com Sun Apr 3 18:58:05 2005 From: danb_83 at yahoo.com (Dan Bishop) Date: 3 Apr 2005 15:58:05 -0700 Subject: string goes away References: <87d5tcouct.fsf@pobox.com> Message-ID: <1112569085.884702.165410@o13g2000cwo.googlegroups.com> John J. Lee wrote: > Duncan Booth writes: > [...] > > str.join(sep, list_of_str) > [...] > > Doesn't work with unicode, IIRC. >>> u" ".join(["What's", "the", "problem?"]) u"What's the problem?" From roy at panix.com Tue Apr 19 10:50:19 2005 From: roy at panix.com (Roy Smith) Date: 19 Apr 2005 10:50:19 -0400 Subject: Why does python class have not private methods? Will this never changed? References: <311b5ce105041902165a0969a0@mail.gmail.com> Message-ID: In article , Peter Hansen wrote: >Roy Smith wrote: >> Simon Brunning wrote: >>>On 4/19/05, could ildg wrote: >>>>Private stuff always makes programming much easier. >>> >>>That contention is, at best, debatable. See >>>http://groups-beta.google.com/group/comp.lang.python/msg/b977ed1312e10b21. >> >> Nice essay. Now, for another look at the same issue... >> http://thedailywtf.com/forums/32534/ShowPost.aspx > >Where in the original posting or in the 86 replies >in that massive page are we supposed to find something >pointed about this issue? There are several comments in there speculating that the intent was to find a way around private data hiding. It's a WTF -- you can't take it too seriously. From nospam at nospam.com Mon Apr 4 18:54:37 2005 From: nospam at nospam.com (3c273) Date: Mon, 4 Apr 2005 15:54:37 -0700 Subject: Insert database rows from CSV file References: Message-ID: Thanks for the link, but this is the step I am trying to save (for someone else). Every time he goes to run a report, he must stop and import any new csv files. Since the files are generated by a Python script, I thought I could just insert them into his table and save him some steps. I'm also just trying to learn the basics Python and SQL . Thanks again. Louis "Larry Bates" wrote in message news:CuSdndFAEfVYIczfRVn-iw at comcast.com... > You may want to take a look at this link. It should > be much faster than any programmatic technique. > > http://www.its.niu.edu/its/CSupport/tipoftheweek/tip_080502.shtml > > If you still want to do it programmatically, you will need to > look at csv module to parse the lines. > > Larry Bates > > > > 3c273 wrote: > > Hello, > > I have a really simple Access database table with a format similar to this: > > CustomerName - ProductOrdered - QtyOrdered > > > > I have a CSV file with the appropriate values as follows: > > Customer1, Widget1, 1000 > > Customer2, Widget2, 3000 > > etc > > > > I have figured out how to insert the data manually from the interactive > > prompt: > > cursor.execute(""" INSERT INTO "Table1" Values ('Customer1', "Widget1', > > '1000') """) > > > > What I would like to do is iterate over the CSV file like this: > > for lines in file: > > cursor.execute(""" INSERT INTO "Table1" lines """) > > > > I have googled and found some examples that use string formatting, but > > without documentation I can't seem to find the right formula. I don't have > > any problem with the iteration part, I just can't seem to figure out how to > > use a variable to insert an entire row with the INSERT statement. Can anyone > > get me going in the right direction? I'm using odbc from win32all, > > Python2.3, and Access2000 if it matters. Thanks. > > Louis > > > > From simon.brunning at gmail.com Fri Apr 15 08:28:59 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Fri, 15 Apr 2005 13:28:59 +0100 Subject: MS SQL Server/ODBC package for Python In-Reply-To: <425faff2$0$298$ed9e5944@reading.news.pipex.net> References: <425faff2$0$298$ed9e5944@reading.news.pipex.net> Message-ID: <8c7f10c605041505281f9f4414@mail.gmail.com> On 4/15/05, Graham wrote: > I need a SQL Server or ODBC package for Python. Can anyone help please? > Have search the Python packages under Database and there is no reference to > either SQL Server or ODBC. Top of the line is probably mxODBC (). It's the Rolls Royce of DB-API modules. It's not free for commercial use, but it's worth every penny/cent/groat/whatever. For commercial work where I've not been able to justify spending money (in my bosses opinion at least), adodbapi () works a treat. -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From rbt at athop1.ath.vt.edu Mon Apr 25 10:32:11 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Mon, 25 Apr 2005 10:32:11 -0400 Subject: Python, Perl & PDF files In-Reply-To: References: Message-ID: Christos TZOTZIOY Georgiou wrote: > On Mon, 25 Apr 2005 09:23:43 -0400, rumours say that rbt > might have written: > > >>Are there any plans in the near future to support PDF files in Python as >> thoroughly and completely as Perl does? > > > Before we let you know about our plans, what are *your* plans on this > subject? :) [0] I just want to read PDF files in a portable way (windows, linux, mac) from within Python. > > >>http://cpan.uwinnipeg.ca/search?query=pdf&mode=dist > > >>I love Python's clean syntax and ease of use, etc. But on some things >>(PDF for example) as barbaric as Perl's syntax is, it does outshine >>Python... I hate having to use Perl just to deal with PDF files. > > > There are two issues here: a) a language, b) its library. You imply > that the Perl syntax outshines Python's because it has _more thorough > and complete support for PDF_, as you say. I don't see a connection, > but rather I see a lure to provoke answers I do not seek to provoke. Sorry if my question comes across that way to you. From fredrik at pythonware.com Fri Apr 8 17:03:24 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 8 Apr 2005 23:03:24 +0200 Subject: Registering File Extension?!? References: <4200063400024066@ims9c.cp.tin.it> Message-ID: wrote: > probably this question has been asked before, but I am unable to find > an answer... I have a big application (written in Python + a GUI in wxPython) > which allows the user to save its work in a file with an extension .glb. > Does anyone know if is there a way (on Windows, but also on other platforms < if possible, thought I know almost nothing about Unix/Linux/Mac things) > to automatically register the extension .glb so that when the user double-clicks > the project file my application is launched with the project file name as > a first argument? briefly, register an "extension => progid" mapping under HKEY_CLASSES_ROOT/extension and a "program identity => command" mapping under HKEY_CLASSES_ROOT/progid/shell/open/command under HKEY_CLASSES_ROOT (use regedit to see how it's done for other applications) for more info, see http://msdn.microsoft.com/library/en-us/shellcc/platform/shell/programmersguide/shell_basics/shell_basics_extending/extending.asp From bill.mill at gmail.com Tue Apr 12 08:41:15 2005 From: bill.mill at gmail.com (Bill Mill) Date: Tue, 12 Apr 2005 08:41:15 -0400 Subject: some sort of permutations... In-Reply-To: References: <9468aec7.0504112228.5d018278@posting.google.com> Message-ID: <797fe3d405041205413e96df2d@mail.gmail.com> On Apr 12, 2005 2:37 AM, Fredrik Lundh wrote: > "Bernard A." wrote: > > > i'm looking for a way to have all possible length fixed n-uples from a > > list, i think generators can help, but was not able to do it myself, > > maybe some one could point me out to an idea to do it ? > > did you try googling for "python permutations" ? > > here's the first hit: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/190465 > I've used that recipe a significant amount, and I feel like its recursion really slows it down (but I haven't been profiled it). Does anyone know of a non-recursive algorithm to do the same thing? And, while I'm asking that question, is there a good reference for finding such algorithms? Do most people keep an algorithms book handy? Peace Bill Mill bill.mill at gmail.com From sxanth at cs.teiath.gr Sat Apr 2 05:10:29 2005 From: sxanth at cs.teiath.gr (stelios xanthakis) Date: Sat, 02 Apr 2005 13:10:29 +0300 Subject: Looking for Benchmarklets to improve pyvm In-Reply-To: References: <424D5BD0.10601@cs.teiath.gr> Message-ID: <424E6F95.3090607@cs.teiath.gr> Skip Montanaro wrote: > > Take a look around for Marc Andre Lemburg's pybench suite. > Thanks! Although pybench needs module.re and module.pickle, so I'll post results later. Moreover, I have similar tests. I'd prefer scripts that do *real* calculations. Stelios From newsgroups at jhrothjr.com Fri Apr 1 08:37:35 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Fri, 1 Apr 2005 07:37:35 -0600 Subject: Ternary Operator in Python References: Message-ID: <114qjnjg54nnkd3@news.supernews.com> "praba kar" wrote in message news:mailman.1172.1112340286.1799.python-list at python.org... > Dear All, > I am new to Python. I want to know how to > work with ternary operator in Python. I cannot > find any ternary operator in Python. So Kindly > clear my doubt regarding this There isn't one, and there won't be one unless Guido changes his mind, and that's quite unlikely. There are a number of workarounds; the most used one seems to be based on a feature of the 'and' and 'or' operators. I believe Pep 308 has a summary of the different ways you can do it, and the advantages and drawbacks of each. John Roth > > > > __________________________________ > Yahoo! Messenger > Show us what our next emoticon should look like. Join the fun. > http://www.advision.webevents.yahoo.com/emoticontest From hancock at anansispaceworks.com Mon Apr 25 21:37:20 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Mon, 25 Apr 2005 20:37:20 -0500 Subject: a=[ lambda t: t**n for n in range(4) ] In-Reply-To: <4269FCB8.5010402@mage.hu> References: <1114206105.666055.33720@g14g2000cwa.googlegroups.com> <42698692$1@nntp0.pdx.net> <4269FCB8.5010402@mage.hu> Message-ID: <200504252037.20911.hancock@anansispaceworks.com> On Saturday 23 April 2005 02:43 am, Mage wrote: > Scott David Daniels wrote: > > See, the body of your anonymous function just looks for "the current > > value of n" when it is _invoked_, not when it is _defined_. > > The "lambda functions" was an unclear part of the tutorial I read. > Should I use them? Are they pythonic? > As far I see they are good only for type less a bit. Lambda has two main uses, IMHO: 1) You need to create a whole lot of functions which all follow a certain pattern, but must evaluate "late" (i.e. the arguments will be added later, so you can't just compute the result instead). This is basically the case the OP presented with his list of increasing powers. You can, of course, use named functions for each, but it may become impractical. 2) You are going to apply the same (arbitrary) function to many sets of arguments. This argues for taking a function as an argument. Python Imaging Library does this with the 'point' method, for example. Frequently you will run into a trivial case such as: def squared_plus_one(x): return x**2 + 1 result_ob = source_ob(transform=squared_plus_one) or something like that. It gets pretty silly to clutter up your code with such trivial functions, and lambda gives you a neat way to simply define the function for the moment you need it and throw it away: result_ob = source_ob(transform=lambda x: x**2 + 1) Note that in this case, the expression is probably the clearest way to document the function (clearer than the function name, IMHO). So, yeah, they have some real uses. But you can live without them most of the time. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From exarkun at divmod.com Thu Apr 28 20:56:27 2005 From: exarkun at divmod.com (Jp Calderone) Date: Fri, 29 Apr 2005 00:56:27 GMT Subject: Shutting down twisted reacotr In-Reply-To: Message-ID: <20050429005627.15422.842044080.divmod.quotient.6632@ohm> On Thu, 28 Apr 2005 12:34:33 +0000 (UTC), Operation Latte Thunder wrote: >Jason Mobarak wrote: >> Why do you want to do this in a thread? What's wrong with >> reactor.callLater? >> >> import time >> from twisted.internet import reactor >> >> def shutdown(): >> >> time.sleep(3) >> print "stopping" >> reactor.callFromThread(reactor.stop) >> >> reactor.callInThread(shutdown) >> reactor.run() > >In the app I am playing with, I have a thread that reads from the console. >When it terminates, I wanted it to shut down the reactor and couldn't use >callLater. However, callFromThread worked perfectly. I guess I need to >look at the docs some more to understand why its necessary In general, you cannot call Twisted APIs from a thread other than that in which the reactor is executing. There are a few exceptions, callFromThread being one of them, but in general doing so has unpredictable behavior and is not supported. You also may be interested in twisted.internet.stdio and, in Twisted 2.0, twisted.conch.insults. Jp From mwm at mired.org Tue Apr 26 22:33:52 2005 From: mwm at mired.org (Mike Meyer) Date: Tue, 26 Apr 2005 21:33:52 -0500 Subject: delete will assure file is deleted? References: <1114510350.912358.21990@f14g2000cwb.googlegroups.com> <8664y9n8hy.fsf@guru.mired.org> <1114512016.930540.164920@g14g2000cwa.googlegroups.com> <01os61t4vg97o4seimge9sppqf9shj7pns@4ax.com> Message-ID: <86mzrlkkxb.fsf@guru.mired.org> Dennis Lee Bieber writes: > On 26 Apr 2005 03:40:16 -0700, "ajikoe at gmail.com" > declaimed the following in comp.lang.python: > >> Hello Mike, >> I have to know this topic otherwise my program has to check whether the >> file / files are already deleted and this is a little bit messy. >> > Ah, but this requirement is different from the one you > originally asked. > > In either event, the best solution is probably to wrap the call > with a try block... > > try: > os.remove(fileName) > except : > # do whatever you need for the error > except : > # do whatever this error needs... > > If the error is that the file didn't exist to be deleted, you > can probably use a "pass" as the except processing. This is just a little bit tricky. os.remove (on FreeBSD 5-STABLE, anyway) throws an OSError exception if it doesn't have permission to remove the file, *or* if the file doesn't exist. You have to examine the exception for it's value, which is the result of a strerror call. I believe that the result of strerror is platform dependent. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From mefjr75 at hotmail.com Thu Apr 21 00:55:01 2005 From: mefjr75 at hotmail.com (M.E.Farmer) Date: 20 Apr 2005 21:55:01 -0700 Subject: Python instances References: <1113982340.156937.75530@f14g2000cwb.googlegroups.com> Message-ID: <1114059301.558816.155630@z14g2000cwz.googlegroups.com> henrikpierrou at hotmail.com wrote: > Hi, > > How do python instances work? > Why does the code at the end of my posting produce this output: > > list in a: > [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] > list in b: > [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] > > instead of > > list in a: > [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] > list in b: > [] > > ---------------------------- > > class MyClass: > list = [] > > def add(self, x): > self.list.append(x) > > def printer(self): > print self.list > > a = MyClass() > b = MyClass() > > for n in range(10): > a.add(n) > > print "list in a:" > a.printer() > print "list in b:" > b.printer() > > /H As others have noted, you are using a class name and not an instance name. Class names are shared by all instances.Instance names are not shared. Also this next bit can bite you. Don't use list it is builtin name and can cause problems when you rebind it. Others to avoid are keywords and file, dict, tuple, object, etc... They can be tempting to use, resist, it will save you debug time later. hth, M.E.Farmer From kay.schluehr at gmx.net Fri Apr 1 03:17:17 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 1 Apr 2005 00:17:17 -0800 Subject: Our Luxurious, Rubinesque, Python 2.4 In-Reply-To: <1112320986.513473.79510@g14g2000cwa.googlegroups.com> References: <1112320986.513473.79510@g14g2000cwa.googlegroups.com> Message-ID: <1112343437.396733.300400@f14g2000cwb.googlegroups.com> Larry Hastings wrote: > Also, how much would I be > able to trim away if I recompiled it myself? Is a lot of it native > implementations of Python libraries that I might not care about > including, or is it all fundamental VM stuff that couldn't possibly be > removed? In Pythons config.c file You can determine which ext-modules will be compiled into the core. I estimate that a lean core would have a size around ~600kb. Trimming down further may become hard because You may have to decide what to sacrifice: tuples, classes or objects ;) Regards, Kay From xah at xahlee.org Mon Apr 25 14:48:04 2005 From: xah at xahlee.org (Xah Lee) Date: 25 Apr 2005 11:48:04 -0700 Subject: Python documentation moronicities (continued) In-Reply-To: References: <1113301533.054410.203710@z14g2000cwz.googlegroups.com> Message-ID: <1114454884.549187.122440@o13g2000cwo.googlegroups.com> I have produced my doc. ( http://xahlee.org/perl-python/python_re-write/lib/module-re.html ) isn't there a hundred dollars due to me? Xah xah at xahlee.org ? http://xahlee.org/PageTwo_dir/more.html Steve Holden wrote: > Xah Lee wrote: > [mountains of irrelevant drivel which normal people would boil down to > "I don't understand the doicumentation]. Even then, I'd still be on the > side of the documentation. > > > The answer to the questions are resounding yeses, you fucking asses. > > > > paypal me a hundred dollars and i'll rewrite the whole re doc in a few > > hours. > > > I will personally pay you a hundred dollars if you can find enough time > between now and this time next week - you should be able to find "a few > hours" in 168 without unduly conveniencing yourself. > > The condition for winning the prize is that at least five regular > posters to c.l.py have to mail me and saythey think your version is better. > > If no such document gets produced, we must assume you are too busy? > > > Fuck you the standard IT morons. Excuse me for i didn't have time to > > write a more coherent and detailed analysis of the stupidities of the > > re doc. > > I have learned not to expect coherent and detailed analysis, so I have > managed to contain my disappointment. > > non-standard-moronical-ly y'rs - steve > -- > Steve Holden +1 703 861 4237 +1 800 494 3119 > Holden Web LLC http://www.holdenweb.com/ > Python Web Programming http://pydish.holdenweb.com/ From max2 at fisso.casa Sun Apr 10 06:57:24 2005 From: max2 at fisso.casa (max(01)*) Date: Sun, 10 Apr 2005 10:57:24 GMT Subject: very simple tkinter demo program In-Reply-To: <9NidnQVTQ9LKMMXfRVn-tQ@adelphia.com> References: <9NidnQVTQ9LKMMXfRVn-tQ@adelphia.com> Message-ID: Samantha wrote: > I can not get it to run. > S sorry about that. baybe it is a conflict between tabstop width in my editor and in my newsreader. i substituted tabs with spaces and i hope now you can run it. bye macs ----cuthere---- from Tkinter import * class MiaApp: def __init__(self, genitore): self.MioGenitore = genitore fonte = ("Helvetica", "12") self.campi = ["Cognome", "Nome" , "Data di nascita"] quadro_grande = Frame(genitore) quadro_grande.pack(expand = YES, fill = BOTH) quadro_menu = Frame(quadro_grande) quadro_menu.configure( bd = 1, relief = RAISED ) quadro_menu.pack(side = TOP, fill = X) pm_file = Menubutton(quadro_menu) pm_file.configure(text = "File") pm_file.pack(side = LEFT) m_file = Menu(pm_file) pm_file.configure(menu = m_file) m_file.configure(tearoff = NO) m_file.add_command( label = "Scrivi", command = self.premuto_scrivi ) m_file.add_command( label = "Leggi", command = self.premuto_leggi ) m_file.add_separator() m_file.add_command( label = "Chiudi", command = genitore.destroy ) pm_mod = Menubutton(quadro_menu) pm_mod.configure(text = "Modifica") pm_mod.pack(side = LEFT) pm_aiuto = Menubutton(quadro_menu) pm_aiuto.configure(text = "?") pm_aiuto.pack(side = RIGHT) msg = Label(quadro_grande) msg.configure( font = fonte, relief = RIDGE, wraplength = "10c", justify = LEFT, text = u"Questo \u00E8 un programma in Python \ che trae ispirazione da un analogo lavoro del collega \ G. Renda. Il programma originale era scritto \ in linguaggio Java, e sfruttava le librerie JFC \ (\u00ABJava Foundation Class\u00BB, dette anche \ \u00ABSwing\u00BB); questo invece usa le librerie Tk, \ mediante il modulo Tkinter." ) msg.pack( side = TOP, padx = "2m", pady = "2m" ) quadro_pulsanti = Frame(quadro_grande) quadro_pulsanti.pack( side = BOTTOM, fill = X, padx = "2m", pady = "2m" ) scrivi = Button(quadro_pulsanti) scrivi.configure( text = "Scrivi", command = self.premuto_scrivi ) scrivi.pack(side = LEFT, expand = YES) leggi = Button(quadro_pulsanti) leggi.configure(text = "Leggi", command = self.premuto_leggi) leggi.pack(side = LEFT, expand = YES) chiudi = Button(quadro_pulsanti) chiudi.configure(text = "Chiudi", command = genitore.destroy) chiudi.pack(side = LEFT, expand = YES) def premuto_scrivi(self): InserimentoRecord() def premuto_leggi(self): ConsultazioneRecord() class InserimentoRecord(Toplevel): def __init__(self): Toplevel.__init__(self) self.titolo = "Inserimento" self.wm_title(self.titolo) quadro_grande = Frame(self) quadro_grande.pack(expand = YES, fill = BOTH) self.quadro_pulsanti = Frame(quadro_grande) self.quadro_pulsanti.pack( side = BOTTOM, fill = X, padx = "2m", pady = "2m" ) quadri_ing = [] self.n = len(miaApp.campi) self.var = [] eti = [] larg_eti = max(map(len, miaApp.campi)) ing = [] for i in range(self.n): quadri_ing.append(None) self.var.append(None) ing.append(None) eti.append(None) quadri_ing[i] = Frame(quadro_grande) quadri_ing[i].pack(side = TOP, expand = YES, fill = BOTH) self.var[i] = StringVar() eti[i] = Label(quadri_ing[i]) eti[i].configure( text = miaApp.campi[i] + ": ", width = larg_eti, anchor = E ) eti[i].pack(side = LEFT, pady = 5, padx = 10, fill = X) ing[i] = Entry(quadri_ing[i], textvariable = self.var[i]) ing[i].pack(side = LEFT, pady = 5, padx = 10, fill = X) self.salva = Button(self.quadro_pulsanti) self.salva.configure( text = "Salva", command = self.premuto_salva ) self.salva.pack(side = LEFT, expand = YES) self.annulla = Button(self.quadro_pulsanti) self.annulla.configure( text = "Annulla", command = self.premuto_annulla ) self.annulla.pack(side = LEFT, expand = YES) def premuto_salva(self): import tkFileDialog import pickle dati = [] for i in range(self.n): dati.append(None) dati[i] = self.var[i].get() nomefile = tkFileDialog.asksaveasfilename( defaultextension = ".ana", filetypes = [ ("Record anagrafici", "*.ana"), ("Tutti i file", "*") ] ) if nomefile: f = open(nomefile, "w") pickle.dump(dati, f) f.close() self.destroy() def premuto_annulla(self): self.destroy() class ConsultazioneRecord(Toplevel): def __init__(self): import tkFileDialog nomefile = tkFileDialog.askopenfilename( defaultextension = ".ana", filetypes = [ ("Record anagrafici", "*.ana"), ("Tutti i file", "*") ] ) if nomefile: try: ### Il metodo 'pickle.load' potrebbe generare una ### eccezione se l'utente cerca di aprire un file ### non del formato giusto Toplevel.__init__(self) self.titolo = "Consultazione" self.wm_title(self.titolo) quadro_grande = Frame(self) quadro_grande.pack(expand = YES, fill = BOTH) eti_rec = Label(quadro_grande) eti_rec.configure( text = "Record: " + nomefile, relief = RIDGE ) eti_rec.pack( side = TOP, fill = X, padx = "5m", pady = "5m" ) self.quadro_pulsanti = Frame(quadro_grande) self.quadro_pulsanti.pack( side = BOTTOM, fill = X, padx = "2m", pady = "2m" ) import pickle quadri_eti = [] eti_campi = [] eti_val = [] larg_eti_campi = max(map(len, miaApp.campi)) f = open(nomefile, "r") valori = pickle.load(f) ### Potrebbe generare una ### eccezione 'KeyError' larg_eti_val = max(map(len, valori)) n = len(miaApp.campi) for i in range(n): quadri_eti.append(None) eti_campi.append(None) eti_val.append(None) quadri_eti[i] = Frame(quadro_grande) quadri_eti[i].pack(side = TOP, expand = YES, fill = BOTH) eti_campi[i] = Label( quadri_eti[i], text = miaApp.campi[i] + ": ", width = larg_eti_campi, anchor = E ) eti_campi[i].pack(side = LEFT, pady = 5, padx = 10, fill = X) eti_val[i] = Label( quadri_eti[i], text = valori[i], anchor = W, width = larg_eti_val, relief = SUNKEN ) eti_val[i].pack(side = LEFT, pady = 5, padx = 10, fill = X) self.chiudi = Button(self.quadro_pulsanti) self.chiudi.configure( text = "Chiudi", command = self.premuto_chiudi ) self.chiudi.pack(side = LEFT, expand = YES) except KeyError: ### Eventualmente generato da ### 'pickle.load()' import tkMessageBox tkMessageBox.showwarning( "Bad input", "Illegal values, please try again" ) self.destroy() f.close() def premuto_chiudi(self): self.destroy() radice = Tk() radice.wm_title("Versione Python di un programma Java di G. Renda") radice.wm_iconname("giuseppe") radice.minsize(400, 300) miaApp = MiaApp(radice) radice.mainloop() From timr at probo.com Fri Apr 1 03:00:58 2005 From: timr at probo.com (Tim Roberts) Date: Fri, 01 Apr 2005 00:00:58 -0800 Subject: urllib problem (maybe bugs?) References: Message-ID: Timothy Wu <2huggie at gmail.com> wrote: > >I'm trying to fill the form on page >http://www.cbs.dtu.dk/services/TMHMM/ using urllib. > >There are two peculiarities. First of all, I am filling in incorrect >key/value pairs in the parameters on purpose because that's the only >way I can get it to work.. For "version" I am suppose to leave it >unchecked, having value of empty string. And for name "outform" I am >suppose to assign it a value of "-short". Instead, I left out >"outform" all together and fill in "-short" for version. I discovered >the method my accident. > >After I've done that it works fine for small SEQ values. Then, when I >try to send large amount of data (1.4MB), it fails miserably with >AttributeError exception. > >I highly suspect the two problems I have are the result of some bugs >in the urllib module. Any suggestions? The
on that page wants multipart/form-data encoding, where each parameter is embedded in a separate MIME section. That is common with very large data, and is _required_ when the form includes a file upload. urllib doesn't do that. It always sends plain old application/x-www-form-urlencoded data. I think you're going to have to roll your own sender. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From http Thu Apr 21 23:12:40 2005 From: http (Paul Rubin) Date: 21 Apr 2005 20:12:40 -0700 Subject: How to run Python in Windows w/o popping a DOS box? References: <7xekd66ra3.fsf@ruckus.brouhaha.com> <4265d7b4.27743873@news.oz.net> Message-ID: <7xk6mvh5cn.fsf@ruckus.brouhaha.com> bokr at oz.net (Bengt Richter) writes: > I would try right-clicking the shortcut icon and selecting > properties, then select the shortcut tab and edit the target string > with s/python/pythonw/ and then click ok. > > Then try double clicking the shortcut icon again. If that does it, > you're home ;-) If not, post more symptoms. Hmm, I clicked properties and the word python doesn't appear in the shortcut string. The shortcut string simply points to the .py file. I think Windows knows to run Python because of some registry entry that maps the .py extension to python.exe. I don't know which entry and changing it sounds a little bit dangerous. I did see that I could select a button launch the dos box minimized, so it doesn't clutter up the screen. That mostly solves the immediate problem. A more complete solution (eliminate dos box altogether) would be nice, but I can live with an auto-minimized box. Thanks. From roy at panix.com Mon Apr 11 09:03:34 2005 From: roy at panix.com (Roy Smith) Date: Mon, 11 Apr 2005 09:03:34 -0400 Subject: database in python ? References: <1113197530.990898.46130@z14g2000cwz.googlegroups.com> Message-ID: In article <1113197530.990898.46130 at z14g2000cwz.googlegroups.com>, "ajikoe at gmail.com" wrote: > Hello I need to build table which need searching data which needs more > power then dictionary or list in python, can anyone help me what kind > of database suitable for python light and easy to learn. Is mySQL a > nice start with python ? > > Sincerely Yours, > Pujo MySQL lacks some of the more advanced features of commercial SQL databases like Oracle or Sybase, but other than that, it's an excellent and very popular choice. It's free, easy to install, runs on many platforms and has interfaces to many languages (including Python). It's also been around a long time and used on many large-scale projects, so you can have confidence that it's stable. It's also well documented, both with on-line material from the makers, and from third party publishers (I like the O'Reily book). From jorgen.cederberg at gmail.com Tue Apr 19 09:46:45 2005 From: jorgen.cederberg at gmail.com (=?ISO-8859-1?Q?J=F8rgen_Cederberg?=) Date: Tue, 19 Apr 2005 15:46:45 +0200 Subject: Update Label when Scale value changes In-Reply-To: <1113916746.841747.274550@l41g2000cwc.googlegroups.com> References: <1113916746.841747.274550@l41g2000cwc.googlegroups.com> Message-ID: <9Z79e.969$cL6.77@news.get2net.dk> codecraig wrote: > Hi, > I am using Tkinter and I have a Label and a Scale. I want to update > my label everytime the Scale value changes. What is the best way of > doing this? Do i have to bind for every event type? Or is there some > better way? If I do have to bind each type of event to the scale, what > types occur for a Scale? > > Thanks. > Hi you could use a variable. Below is simple program that connects the value of the scale to the label. from Tkinter import * root = Tk() var = IntVar() Label(root, textvariable=var).pack() Scale(root, from_=-2.0, to=10.0, variable=var).pack() root.mainloop() Hope this helps Jorgen Cederberg From kay.schluehr at gmx.net Sun Apr 10 04:20:54 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 10 Apr 2005 01:20:54 -0700 Subject: Thoughts on some stdlib modules In-Reply-To: References: Message-ID: <1113121254.874488.111250@f14g2000cwb.googlegroups.com> Steve Holden wrote: > You are correct in suggesting that the library could be better organized > than it is, but I felt we would be better off deferring such change > until the emergence of Python 3.0, which is allowed to break backwards > compatibility. So, start working on your scheme now - PEP 3000 needs > contributions. I fear that Python 3.0 becomes some kind of vaporware in the Python community that paralyzes all redesign efforts on the std-lib. The argument goes like this: one has to wait until the BDFL has made his syntax/feature/builtin decisions. It is not usefull to redesign a std-library of a language that becomes somehow deprecated - but the BDFL thinks that Python 3.0 is still py-in-the-sky. PEP 3000 seems to be nothing more than a summary of the BDFLs musings about Python warts and some wishfull but highly controversial features like type guards that would have a great overall impact on the std-lib. Regards, Kay From jfine at pytex.org Wed Apr 13 14:34:41 2005 From: jfine at pytex.org (Jonathan Fine) Date: Wed, 13 Apr 2005 19:34:41 +0100 Subject: Simple Python + Tk text editor Message-ID: <425D6641.5050906@pytex.org> Hi I'm looking for a simple Python + Tk text editor. I want it as a building block/starting point. I need basic functions only: open a file, save a file, new file etc. It has to be open source. Anyone know of a candidate? -- Jonathan http://qatex.sourceforge.org From bvande at po-box.mcgill.ca Sun Apr 17 17:11:00 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sun, 17 Apr 2005 17:11:00 -0400 Subject: pydoc preference for triple double over triple single quotes-- anyreason? In-Reply-To: <4262c00e$1_3@newspeer2.tds.net> References: <42617449_3@newspeer2.tds.net> <4262c00e$1_3@newspeer2.tds.net> Message-ID: <4262D0E4.6090206@po-box.mcgill.ca> Kent Johnson said unto the world upon 2005-04-17 16:17: > Brian van den Broek wrote: > >> Kent Johnson said unto the world upon 2005-04-16 16:41: >> >>> Brian van den Broek wrote: >>> >>>> I've just spent a frustrating bit of time figuring out why pydoc >>>> didn't extract a description from my module docstrings. Even though >>>> I had a well formed docstring (one line, followed by a blank line, >>>> followed by the rest of the docstring), when I ran Module docs, my >>>> modules showed up as having "no description". ("Module docs" >>>> referring to the shortcut installed on Windows that launches the >>>> pydoc server.) >>> >>> >>> ?? It works for me with triple-single quoted strings...from a quick >>> look it appears that pydoc uses inspect which looks at the __doc__ >>> attribute; do your modules have __doc__ attributes? >>> >> Kent, that's odd. My module does have a valid docstring and hence a >> __doc__ attribute (I did explicitly check). help(my_module) works fine >> at the prompt. It is just the results list in the TKinter interface to >> the pydoc server application that doesn't seem to pick up my module's >> description (in the first line of its docstring) when the docstring is >> triple-single quoted. > > > I'm not sure what you mean by "the results list in the TKinter interface > to the pydoc server". I ran the server, clicked "open browser" and > browsed to a module in site-packages; that worked fine for me under > Win2K and Python 2.4.1. > > Kent By "the TKinter interface to the pydoc server" I mean the window that pops up when you select the Module Docs shortcut. It is pictured here , which is Fig.1 in an article on pydoc by Cameron Laird . By "results list" I mean the gray-backround'ed box immediately below the "Search for" input box in the illustration. The puzzle for me was that if I enter my module name in the "Search for" box, it shows up in the list of results, as expected. But whether the results list entry for my module incorporates the description form my module's docstring or instead shows my module as having "(no description)" is a function of which style of triple quotes I used. (If my module docstring is enclosed by triple double quotes, the description is extracted from my module's docstring. If it uses triple single quotes instead, for purposes of the results list my module's docstring is ignored, and the module is listed as having "(no description)".) At any rate, such was the (minor) irritation which caused me to launch the thread. It took me a bit to work out that the quote-style was what made the difference, and a preliminary google didn't cast light. 2/3rd's the point of the post was to make the problem resolvable by google. Thanks for your continued efforts to understand what I'm on about. :-) Best to all, Brian vdB From __peter__ at web.de Fri Apr 15 11:33:20 2005 From: __peter__ at web.de (Peter Otten) Date: Fri, 15 Apr 2005 17:33:20 +0200 Subject: eval function not working how i want it dag namn References: <1113567261.483667.198430@z14g2000cwz.googlegroups.com> Message-ID: robcarlton wrote: > hi everybody > I've written this function to make a list of all of an objects > attributes and methods (not for any reason, I'm just learning) > > def list_members(obj) > l = dir(obj) > return map(lambda x : eval('obj.'+x), l) > > but I get an error saying that obj isn't defined. As I understand it > eval has access to the current local namespace, which does contain > object, so I'm not sure whats going wrong. > > ps Im sure there are better ways of doing the above which doesn't call > the eval function, and while I'd be glad to know what it is, I'd still > like to understand why my way isnt working It would work if obj were in the local namespace like so: >>> def f(obj="x"): ... return eval("obj") ... >>> f() 'x' but with the lambda you are introducing a nested namespace. >>> def f(obj="x"): ... return (lambda: eval("obj"))() ... >>> f() Traceback (most recent call last): File "", line 1, in ? File "", line 2, in f File "", line 2, in File "", line 0, in ? NameError: name 'obj' is not defined You are doing the equivalent to >>> def f(obj="x"): ... def g(): # no obj in g()'s namespace ... return eval("obj") ... return g() ... >>> f() Traceback (most recent call last): File "", line 1, in ? File "", line 4, in f File "", line 3, in g File "", line 0, in ? NameError: name 'obj' is not defined only in a convoluted way. Let's make f()'s local variable obj visible in g(), too: >>> def f(obj="x"): ... def g(): ... obj # now you can see me ... return eval("obj") ... return g() ... >>> f() 'x' Here's another way that is viable with lambda, too. >>> def f(obj="x"): ... return (lambda obj=obj: eval("obj"))() ... >>> f() 'x' I'm sure you can fix your list_members() accordingly. Note that rebinding obj between the definition and call of g() will affect the result only in the first of the last two examples. And now for something completely different: >>> def list_members(obj): ... return [getattr(obj, name) for name in dir(obj)] ... >>> import os >>> list_members(os)[:5] [73, 78, 65, 74, 68] >>> Peter From rkern at ucsd.edu Sat Apr 23 23:35:55 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sat, 23 Apr 2005 20:35:55 -0700 Subject: Variables In-Reply-To: <426B083A.70104@cloudthunder.com> References: <426B0283.40602@cloudthunder.com> <426B083A.70104@cloudthunder.com> Message-ID: Richard Blackwood wrote: > Indeed, this language is math. My friend says that foo is a constant and > necessarily not a variable. If I had written foo = raw_input(), he would > say that foo is a variable. Which is perfectly fine except that he > insists that since programming came from math, the concept of variable > is necessarily the identical. This can not be true. For example, I may > define foo as being a dictionary, but I can not do this within math > because there is no concept of dictionaries within mathematics; yet foo > is a variable, a name bound to a value which can change. Your friend needs to learn, and very quickly if he persists in inflicting his erroneous pedantry on other people, that technical terms have different meanings in different fields, even if one can imagine that one "came from" the other. Hell, even in the same field, it can mean different things. Ask him what "domain" means in mathematics. And check his answer[1]. While one could argue that using the term "variable" for Python names is incorrect for good programming reasons, your friend's reasoning is ridiculous. [1] http://mathworld.wolfram.com/Domain.html -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From jdh2358 at gmail.com Fri Apr 22 14:43:07 2005 From: jdh2358 at gmail.com (jdh2358 at gmail.com) Date: 22 Apr 2005 11:43:07 -0700 Subject: trying to read from dying disk Message-ID: <1114195387.535143.76860@o13g2000cwo.googlegroups.com> I have a python file that is trying to read raw data from a raw partition on a dying dist, eg f = file('/dev/sda') f.seek(SOMEWHERE) s = f.read(SOMEBYTES) On some blocks, the read succeeds, on others it fails and an IOError is thrown, and on others it appears to hang indefinitely and will not respond to any attempt to kill it with 'kill -9 PID', etc. Is there anyway to do a timeout read on this kind of file, or even to kill the process once it hangs? linux kernel 2.6.10 python 2.4.1 Thanks! JDH From tzot at sil-tec.gr Wed Apr 20 11:15:18 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 20 Apr 2005 18:15:18 +0300 Subject: goto statement References: <20050420092359.81900.qmail@web8409.mail.in.yahoo.com> <42664190.6010507@i.com.ua> <87vf6hlkix.fsf@wilson.rwth-aachen.de> Message-ID: <70sc615akd7mfdkmrjls956o1u5rglm74t@4ax.com> On Wed, 20 Apr 2005 16:13:32 +0300, rumours say that Maxim Kasimov might have written: >but what if i just can't to do this becouse i'm working thrue ssh, and have to use only installed editors (such as vi) If you use plain vi (not vim) and you want to comment e.g. 5 lines of code, go to the first of these five and: - if autoindent type: 5>>O^Dif 0:{ESC} ^D above is Ctrl-D, {ESC} is your Escape key - if noautoindent type: YP^Cif 0:{ESC}j5>> ^C above is literal ^, literal C, *NOT* Ctrl-C; {ESC} is your Escape key To control autoindent, you can type: :se ai or :se noai If you need more help, I would gladly send you the output of `man vi' from a non-GNU Unix. I can also send you the output of `man vim' from a GNU system. -- TZOTZIOY, I speak England very best. "Be strict when sending and tolerant when receiving." (from RFC1958) I really should keep that in mind when talking with people, actually... From kent37 at tds.net Sun Apr 17 16:21:07 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 17 Apr 2005 16:21:07 -0400 Subject: Accessing multidimensional lists with an index list In-Reply-To: <32903d4e.0504171150.73b7feb0@posting.google.com> References: <32903d4e.0504171150.73b7feb0@posting.google.com> Message-ID: <4262c100_3@newspeer2.tds.net> Gabriel Birke wrote: > Given the multidimensional list l: > l = [ {'v1': 1, 'v2': 2}, > [ {'v1':4, 'v2': 7}, > {'v1': 9, 'v2': 86}, > [ {'v1': 77, 'v2': 88}] > ] > ] > > I want to access specific items the indices of which are stored in > another list. For now, I created a function to do this: > > def getNestedValue(l, indices): > while len(indices) > 0: > i = indices.pop(0) > l = l[i] #In future versions, put error checking here > return l > > Is there a more elegant or performant language construct to accomplish > my task? def getNestedValue(l, indices): for i in indices: l = l[i] #In future versions, put error checking here return l Kent From cjw at sympatico.ca Sat Apr 23 19:59:12 2005 From: cjw at sympatico.ca (Colin J. Williams) Date: Sat, 23 Apr 2005 19:59:12 -0400 Subject: Using Ming on Windows In-Reply-To: References: Message-ID: <426AE150.5030109@sympatico.ca> Jack Diederich wrote: > On Sat, Apr 23, 2005 at 05:13:29PM -0300, Andr? Roberge wrote: > >>I tried to install Ming >>(http://sourceforge.net/projects/ming/) >>on Windows to use with Python *but* >>I can't [/don't know how to] use "make" to install it. >> >>Does anyone know where I could find a ready-made compiled >>version for Windows to just "put in" my site-packages directory. >> >>Any help would be appreciated. >> > > Ming seems to be abandoded/unsupported. Use groups.google.com to > find some hints on how to install it. I've done it on linux, but > never tried on windows (why would I?) and replied with some > suggestions last time it came up on c.l.py > > -jackdied I installed MinGW on a Windows XP with no trouble. One needs to install MSYS, as well as MinGW, since some modules (eg. make) are only available in MSYS. Currently, I am trying to build a package from source and have some unresolved problems. Earlier I had tried to use the Borland commandline, without success. Colin W. From steven.bethard at gmail.com Thu Apr 28 21:56:53 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 28 Apr 2005 19:56:53 -0600 Subject: how can I sort a bunch of lists over multiple fields? In-Reply-To: <1114724023.743271.275710@g14g2000cwa.googlegroups.com> References: <1114623282.855415.132040@l41g2000cwc.googlegroups.com> <1114634355.348110.141690@o13g2000cwo.googlegroups.com> <1114710873.292998.128090@f14g2000cwb.googlegroups.com> <1114714105.582253.12150@f14g2000cwb.googlegroups.com> <1114724023.743271.275710@g14g2000cwa.googlegroups.com> Message-ID: Lonnie Princehouse wrote: >>Likewise, the above is basically just an inefficient way of writing: >> >>def date_key(book): >> return book.data >> >>def author_and_date_key(book): >> return (author_key(book), date_key(book)) > > > It's certainly more elegant, but I wanted to talk about the mechanics > of comparison functions =) > > I don't know that it's more or less efficient in execution. That > depends on a few factors. For most cases, key= will be more efficient than cmp=. The key= argument will only be called once for each item in the list. The cmp= argument will be called once for each comparison: py> class Cmp(object): ... def __init__(self): ... self.count = 0 ... def __call__(self, x, y): ... self.count += 1 ... return cmp(x, y) ... py> class Key(object): ... def __init__(self): ... self.count = 0 ... def __call__(self, x): ... self.count += 1 ... return x ... py> import random py> lst = range(1000) py> random.shuffle(lst) py> lst2 = list(lst) py> c = Cmp() py> lst.sort(cmp=c) py> c.count 8599 py> k = Key() py> lst.sort(key=k) py> k.count 1000 Since in all but a few corner cases (e.g. where the list is already sorted) there will be way more comparisons than items, the key= argument will minimize the number of function calls. Since function calls are one of the more expensive operations in Python, my guess is that there are very few cases where you would want to use the cmp= argument if you know you can use the key= argument. STeVe From firstname.lastname at iki.fi-spam Sat Apr 2 01:35:02 2005 From: firstname.lastname at iki.fi-spam (Simo Melenius) Date: 02 Apr 2005 09:35:02 +0300 Subject: How To Do It Faster?!? References: Message-ID: <87sm29fzzd.fsf@sme.intra.citec.fi> andrea_gavana at tin.it writes: > Every user of thsi big directory works on big studies regarding oil > fields. Knowing the amount of data (and number of files) we have to > deal with (produced by simulators, visualization tools, and so on) > and knowing that users are usually lazy in doing clean up of > unused/old files, this is a way for one of us to "fast" scan all the > directories and identify which files belong to him. Having them in > an organized, size-sorted wxPython list, the user can decide if he > want to delete some files (that almost surely he forgot even that > they exist...) or not. It is easy as a button click (retrieve the > data-->delete the files). Correct me if I'm wrong but since it _seems_ that the listing doesn't need to be up-to-date each minute/hour as the users will be looking primarily for old/unused files, why not have a daily cronjob on the Unix server to produce an appropriate file list on e.g. the root directory of your file server? Your Python client would then load that (possibly compressed) text file from the network share and find the needed bits in there. Note that if some "old/unneeded" files are missing today, they'll show right up the following day. For example, running the GNU find command like this: $ find . -type f -printf "%T@ %u %s %p\n" > /yourserverroot/files.txt produces a file where each line contains the last modified time, username, size and path for one file. Dead easy to parse with Python, and you'll only have to set up the cronjob _once_ on the Unix server. (If the file becomes too big, grep can be additionally used to split the file e.g. per each user.) br, S -- firstname.lastname at iki.fi-spam From wp at tekran.spammenziemichnichtdankeschon.com Thu Apr 7 10:27:25 2005 From: wp at tekran.spammenziemichnichtdankeschon.com (Warren Postma) Date: Thu, 07 Apr 2005 10:27:25 -0400 Subject: Testing threading In-Reply-To: <1112723255.126565.290450@o13g2000cwo.googlegroups.com> References: <1112723255.126565.290450@o13g2000cwo.googlegroups.com> Message-ID: George Sakkis wrote: > How one goes on testing a threaded program, apart from doing a few > successful runs and crossing his fingers that it at least follows the > 'correct 99.9999% of the time' rule ? If you haven't been in there and stepped through all the code, looked for a reasonable set of test cases, and tried those test cases, then you haven't tested! :-) You test a threaded program the same way you test a non-threaded program. Thoroughly. Test cases. YOu don't *have* to write unit tests, but it sure helps. Code running a few times isn't tested. If you prefer to test manually, really want to be thorough you have to find ways to make sure you've done coverage of a reasonable set of test cases. How do I get myself a set of test cases? Personally I like to walk through my code in a debugger and ask myself "how could this go wrong?". "What if I pass a huge amount of data in here? How unresponsive can I find ways to make this thread get?" "If this is a network communications thread, let's try all the various error conditions that can happen on a real network.". ... When I think of an idea on how things could go wrong ("What happens if the data isn't here or is invalid?"/"Where should I be catching exceptions and how should I be handling them?") Regards, Warren From donn at drizzle.com Mon Apr 25 11:26:00 2005 From: donn at drizzle.com (Donn Cave) Date: Mon, 25 Apr 2005 15:26:00 -0000 Subject: Variables References: None Message-ID: <1114442759.889745@yasure> Quoth Richard Blackwood : ... | Would you agree that the concept of variables differs in very important | ways between the domains of math and programming? No, if "math" means the elementary notions that I have been exposed to and "very important" means "important to implementors". Cf. my prior post on this. Variables are semantically the same, "=" is different but can be modeled in equational terms with a fairly simple transformation. Donn Cave, donn at drizzle.com From thomas at eforms.co.nz Fri Apr 29 00:00:59 2005 From: thomas at eforms.co.nz (Thomas) Date: Fri, 29 Apr 2005 16:00:59 +1200 Subject: uploading large file 100mb Message-ID: <20050429035906.68BCA37025@mail.tintz.co.nz> Hi I am getting the following error when uploading large files. Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> ## working on region in file c:/DOCUME~1/ADMINI~1/LOCALS~1/Temp/python-1156QtG.py... Traceback (most recent call last): File "", line 1, in ? File "c:/DOCUME~1/ADMINI~1/LOCALS~1/Temp/python-1156QtG.py", line 79, in ? post_multipart("192.168.100.233","/UploaderHttp/",[('test','valTest')],[('FI LE1','TM_A5_Bulk.pdf',data)]); File "c:/DOCUME~1/ADMINI~1/LOCALS~1/Temp/python-1156QtG.py", line 17, in post_multipart h.send(body) File "C:\Python23\lib\httplib.py", line 576, in send self.sock.sendall(str) File "", line 1, in sendall socket.error: (10055, 'No buffer space available') >>> Thanks Thomas The code that I am using ---------------------------------------------------------------------- import httplib, mimetypes def post_multipart(host, selector, fields, files): """ Post fields and files to an http host as multipart/form-data. fields is a sequence of (name, value) elements for regular form fields. files is a sequence of (name, filename, value) elements for data to be uploaded as files Return the server's response page. """ content_type, body = encode_multipart_formdata(fields, files) h = httplib.HTTP(host) h.putrequest('POST', selector) h.putheader('content-type', content_type) h.putheader('content-length', str(len(body))) h.endheaders() #print body; h.send(body) errcode, errmsg, headers = h.getreply() return h.file.read() def encode_multipart_formdata(fields, files): """ fields is a sequence of (name, value) elements for regular form fields. files is a sequence of (name, filename, value) elements for data to be uploaded as files Return (content_type, body) ready for httplib.HTTP instance """ BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$' CRLF = '\r\n' L = [] for (key, value) in fields: L.append('--' + BOUNDARY) L.append('Content-Disposition: form-data; name="%s"' % key) L.append('') L.append(value) for (key, filename, value) in files: L.append('--' + BOUNDARY) L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename)) L.append('Content-Type: %s' % get_content_type(filename)) L.append('') L.append(value) L.append('--' + BOUNDARY + '--') L.append('') body = CRLF.join(L) content_type = 'multipart/form-data; boundary=%s' % BOUNDARY return content_type, body def get_content_type(filename): return mimetypes.guess_type(filename)[0] or 'application/octet-stream' FILE= 'c:/Documents and Settings/Administrator/Desktop/TM_A5_Bulk.pdf'; f = file(FILE, "rb") data = f.read() f.close() post_multipart("192.168.100.233","/UploaderHttp/",[('test','valTest')],[('FI LE1','TM_A5_Bulk.pdf',data)]); -------------- next part -------------- An HTML attachment was scrubbed... URL: From ritterhaus at yahoo.com Wed Apr 6 15:14:37 2005 From: ritterhaus at yahoo.com (ritterhaus at yahoo.com) Date: 6 Apr 2005 12:14:37 -0700 Subject: Python sleep doesn't work right in a loop? Message-ID: <1112814877.560518.229530@z14g2000cwz.googlegroups.com> Just a simple bit of code to toggle between two state at intervals... import time for i in range(4): print 'On' time.sleep(1) print 'Off' time.sleep(1) ... SHOULD toggle On and Off four times with one-second pauses. When I run this, the loop pauses the full eight seconds then prints the Ons and Offs all at once. What's up with that? From fredrik at pythonware.com Sat Apr 23 13:11:19 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 23 Apr 2005 19:11:19 +0200 Subject: Python or PHP? References: <1114254894.512656.297040@l41g2000cwc.googlegroups.com> <426A76A5.2050906@mage.hu> Message-ID: "Mage" wrote: > I don't think so. Bad programmers are able to write bad programs in any > language. in PHP, good programmers are able to write bad programs without even noticing. (every successful server attack I've seen closely the last few years have been through PHP. it's totally without competition in this area) > However one of the worst cases is the sql injection attack. And sql > injections must be handled neither by php nor by python but by the > programmer. sql injection? what's your excuse for not using data binding? From tjreedy at udel.edu Fri Apr 1 13:39:47 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 1 Apr 2005 13:39:47 -0500 Subject: that is it is not it (logic in Python) References: <424d0be1$0$2882$626a14ce@news.free.fr> Message-ID: "F. Petitjean" wrote in message news:424d0be1$0$2882$626a14ce at news.free.fr... >I want to know if iter(iterator) returns always its argument (when > argument is an iterator) By the strict definition of iterator (versus iterable) that requires that as a condition to be an iterator, then yes. If you use a looser definition of iterator, then perhaps not. >>>> iterable = range(10) >>>> it = iter(iterable) >>>> that = iter(it) >>>> that is it > True # Good! >>>> that is it is not it This is equivalent to '(that is it) and (it is not it)' which is clearly false. > False # What ? Reread the ref manual on chained comparison operators. Terry J. Reedy From electric.sunrise at gmail.com Wed Apr 6 23:17:21 2005 From: electric.sunrise at gmail.com (Matt@revera) Date: 6 Apr 2005 20:17:21 -0700 Subject: Overwrite just one line? Am I a n00b or is this impossible? Both? :D In-Reply-To: References: <1112821286.411004.225400@f14g2000cwb.googlegroups.com> Message-ID: <1112843841.813518.172350@l41g2000cwc.googlegroups.com> Erik Max Francis wrote: > Matt at revera wrote: > > > I'd like to overwrite just one line of a binary file, based on a > > position set by seek(). Is there no way to do this? As far as I can > > tell I need to read the whole file, change the line, and write it all > > back out. Not exactly easy on the memory, but I see no other solution. > > You need to find what "just one line" means in a binary format. If the > chunk you're replacing and the chunk you want to replace it with are of > different sizes, then you need to use a temporary file (or read the > remainder of the file in memory). > > Otherwise, open the file in read-write binary mode ("r+b") and seek and > write appropriately. In the general case, you need to write to a > temporary file to get the job done. > > Memory usage is not a factor, here; read and write the temporary files > in chunks. That way you can manage the memory usage to whatever upper > bound you wish. > > -- > Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ > San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis > Be able to be alone. Lose not the advantage of solitude. > -- Sir Thomas Browne Ok makes sense, I was using a+b. Would r+b be a better choice? I was under the impression that it was only for reading. I am writing something of the same length in fact, but the python reference says that on some versions of unix (I'm on mac OS X) append will ignore the seek() position and dump it at the bottom of the file - which is exactly what it's doing. Am I stuck? Thanks for all your help! From jjl at pobox.com Wed Apr 6 14:39:17 2005 From: jjl at pobox.com (John J. Lee) Date: 06 Apr 2005 19:39:17 +0100 Subject: Best editor? References: <1112725379.514651.66540@l41g2000cwc.googlegroups.com> <20050406010456.GA31984@alcyon.progiciels-bpi.ca> Message-ID: Fran?ois Pinard writes: [...] > Overall, Vim is also cleaner than Emacs, and this pleases me. [...] Is this still true when comparing XEmacs vs. vim? (rather than GNU Emacs vs. vim) I've always used GNU Emacs, but I have got the impression that XEmacs is (was?) cleaner in some ways. John From tjreedy at udel.edu Fri Apr 1 18:27:48 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 1 Apr 2005 18:27:48 -0500 Subject: Ternary Operator in Python References: <20050401072442.73412.qmail@web8408.mail.in.yahoo.com> <1112391650.018826.274970@l41g2000cwc.googlegroups.com> Message-ID: "Carl Banks" wrote in message news:1112391650.018826.274970 at l41g2000cwc.googlegroups.com... >> A unary operator has one operand; a binary operator has two operands; >> ternary operator has three operands. Python has none built-in, > > Not so fast, my friend. What about the expression "0.0 < a < 1.0"? Gee, what about 0.0 < a < 1.0 < b < 2.0? I see both as synthesized multinary operators, but your are right in that this combination does act differently than a+b+c. Terry J. Reedy From cfriedl at bigpond.net.au Wed Apr 27 21:51:23 2005 From: cfriedl at bigpond.net.au (bwaha) Date: 27 Apr 2005 18:51:23 -0700 Subject: suggestions on how to do this In-Reply-To: <1114648489.758666.224590@o13g2000cwo.googlegroups.com> References: <1114648489.758666.224590@o13g2000cwo.googlegroups.com> Message-ID: <1114653083.150763.269970@l41g2000cwc.googlegroups.com> Hi bgs Many thanks. This generates the correct coefficients. I am studying your implementation now. I've not used a dictionary of dictionaries before so there's a bit of a learning curve going on right now. However I can see that b[k] holds the relevant info (coefficients and powers) so I can easily modify it to collect terms with like powers. As for speed, its not a concern. Thanks again. bwaha Chris From mwm at mired.org Wed Apr 20 03:15:28 2005 From: mwm at mired.org (Mike Meyer) Date: Wed, 20 Apr 2005 02:15:28 -0500 Subject: pre-PEP: Simple Thunks References: <3jl2615c5pckknicc32ccv2cktue3nh603@4ax.com> <7og3615g159tgksejbo15oo8jcit3ugec2@4ax.com> <3r2661ltasoktjlgtvp3v03osb372b15j2@4ax.com> Message-ID: <86u0m1udf3.fsf@guru.mired.org> Ron_Adam writes: > Here's yet another way to do it, but it has some limitations as well. > > import pickle > def pickle_it(filename, obj, commands): > try: > f = open(filename, 'r') > obj = pickle.load(f) > f.close() > except IOError: > pass > for i in commands: > i[0](i[1]) > f = open(filename, 'w') > pickle.dump(obj, f) > f.close() > > file = 'filename' > L = [] > > opps = [ (L.append,'more data'), > (L.append,'even more data') ] > pickle_it(file, L, opps) Um - it doesn't look like this will work. You pass L in as the "obj" paremeter, and then it gets changed to the results of a pickle.load. However, you call L.append in the for loop, so the data will be appended to L, not obj. You'll lose an list elements that were in the pickle. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From fredrik at pythonware.com Wed Apr 27 06:57:39 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 27 Apr 2005 12:57:39 +0200 Subject: how to connect my sql with Python References: <20050427104754.45719.qmail@web8407.mail.in.yahoo.com> Message-ID: "praba kar" wrote: > I am doing Python-cgi Project in my company. > To connect My sql database(Mysql 4.1.11.) into > Python(2.3.3) cgi. I have installed > MySQL-python-1.2.0. After installation of > MySQL-Python-1.2.0 I try import > MySQLdb module. It raised the following error > >>>import MySQLdb > > Traceback (most recent call last): > File "", line 1, in ? > File > "/System/Links/Libraries/python2.4/site-packages/MySQLdb/__init__.py", > line 27, in ? > import _mysql > ImportError: libmysqlclient.so.14: cannot open shared > object file: No such file or directory > > so kindly give me guidance to connect Mysql and Python have you installed the required "libmysqlclient" library? if you have, have you installed in a location where the runtime linker can find it? From jarrod.roberson at gmail.com Fri Apr 15 16:28:03 2005 From: jarrod.roberson at gmail.com (fuzzylollipop) Date: 15 Apr 2005 13:28:03 -0700 Subject: How to fix this error in the example in 6.1.4 Files and Directories In-Reply-To: References: <1113583932.703797.118610@o13g2000cwo.googlegroups.com> Message-ID: <1113596883.573243.197250@f14g2000cwb.googlegroups.com> can't see the forest for the trees, that seems to be the problem, thanks for pointing out the obvious ( that I couldn't see ) :-( From john at castleamber.com Mon Apr 25 15:25:34 2005 From: john at castleamber.com (John Bokma) Date: 25 Apr 2005 19:25:34 GMT Subject: Python or PHP? References: <1114254894.512656.297040@l41g2000cwc.googlegroups.com> <87hdhxwj6s.fsf@debian.kirkjobsluder.is-a-geek.net> <1114274632.128667.281820@l41g2000cwc.googlegroups.com> <86br85rvfw.fsf@guru.mired.org> <863bthrmtg.fsf@guru.mired.org> <86y8b8rgg5.fsf@guru.mired.org> <86d5skr2l3.fsf@guru.mired.org> <86y8b7pydc.fsf@guru.mired.org> <86u0lvph0n.fsf@guru.mired.org> Message-ID: Mike Meyer wrote: > John Bokma writes: >> Mike Meyer wrote: [ snip ] >> do you really think that for / foreach and things like if / unless >> bloat a language processor? I think you take your "pure programming >> lanuage" way to far, and really don't understand your choice of >> Python in your crusade. > > I don't think I take it to far. All my experience dealing with > languages that took the opposite tack (i.e. - Perl and Common LISP) > demonstrate that such things are a bad idea. Funny, quite a lot of Perl programmers consider using unless instead of if ! a good idea. And if a programmer is not able to grasp the meaning of unless if he sees it the first time, he should be able to look it up. And if a programmer says that it burdens his mental processes, or slows him down, I hope I never have to work with him/her and/or maintain his/her code. >>> and increases the semantic load on >>> the programmer. The best the programmer can do, as you imply, is to >>> ignore the extraneous methods. >> I am curious of a list of extraneous methods in Perl (more about the >> size by the way) > > Methods isn't a very good word choice on my part, as it has to many > meanings. But saying "extraneous ways to do it" is a bit wordy. I > already gave you one such list, covering just the syntactic elements > of the language. I must have missed it, since I didn't see it. >> A poorly skilled programmer has to puzzle about a lot of more things. >> Or you think list comprehension (sp?) and all the tricks with it are >> clear? or the and or trick? I just had a glance on Python, but what >> probably to you is one clear path isn't clear to me yet. And I doubt >> that can all be blamed on unpure new Python. > > Correct - newbies have to puzzle about a lot of things. A good > language design won't add to that set of things without a good > reason. Adding features because you can is adding things to puzzle > about without a good reason. I doubt that features have been added to Perl just because. Even ones that look like it, unless for example, have an excellent use, it makes the code more readable. >>> No, one I blew. One you still got wrong. >> Which one? > > Faling to put in the parens that would have distinguished the argument > lists from the list of operators. *sigh* you gave a list of problems, I replied by putting all answers on one line, with () around them, and commas between them. I was not constructing a tuple, or a list in Perl > Actually, it's not clear the grep was right either. The return value > of grep (and map) isn't always the right thing. If you want to have a list of results and you assign it to a scalar, you are doing the wrong thing. But the bottom line is: I gave you answers to all, except one, of your problems, you think my set of answers is a kind of Perl list, you thought the grep was plainly wrong, and I guess you are not comfortable with split. And this gives me the feeling that you either haven't been using Perl for over 4 years, or was never got beyond the absolute beginner level. In the latter case I can imagine that you are overwhelmed by Perl. As would one by any language. >>>> If I could have a peek at the Perl code you maintained I could tell >>>> you (often by just seeing 3-5 lines) the status of the programmer >>>> who wrote it :-) >>> So you'd either say you were wrong, or that my second contention was >>> right. Either one would be a bad side effect of TMTOWTDI. >> I am right, and you are wrong ;-) > > In which case, I'm right in claiming that having more than one way to > do things fragments the community - which is *still* a bad thing for > the people writing the language. It fragments it in a way every programming community is fragmented: absoluut beginner, beginner, junior, senior, guru. >> ARM assembly, told you ;-) > > That's not a coverage. Unless ARM assembly includes garbage > collection, dictionaries and similar things. In a pure language such things are in the library. >> Easier, sure. But does it turn beginners in rock solid programmers? > > It means they never make errors like using free'd memory, or failing > to free allocated memory. So in that since, yes, they are rock solid. LOL, but they will make other mistakes. Otherwise, I am really curious, can you show a publication that shows that the number of bugs / application is much smaller when a garbage collection language is used, and one that does bounds checking? >> So they looked close at one aspect of the language. But you think >> that 10k lines of, say Java, has less bugs then 10k lines of C? > > Nah. Then again, counting lines of code is a silly thing to do. You > think 10K lines of C does as much as 10K lines of Java? Depends of course, but rephrase: we take 10 programs of C, 10 of Java, each which are equal (except in the number of bugs). You think Java has less? > The crucial > question isn't how many bugs you get per line of code, it's how many > bugs you get to achieve a given functionality. You can improve this > number by cutting down the number of bugs per line of code, or by > cutting down the number of lines of code needed to acheive a given > functionality. Modern programming environments clearly improve the > latter. But are there now less bugs compared to a few years ago? Are, say, Java programs in general more bug free? >> And I am sure that you fixed enough bugs in the same *real* programs >> that were in no way related to this. I have fixed enough bugs in >> Perl, Java, etc, to know that "life will find a way", so to speak. > > We both agree you're always going to have bugs. I think that > programming languages designed to eliminate whole classes of bugs are > good thing, because bugs are a bad thing. You seem to argue that > because we can't elimnate all bugs, we shouldn't eliminate any. That's > simply silly. Nope, I got the impression from you that Python restricts programmers, so they make less mistakes. They can't make mistakes of "whole classes", but that doesn't mean they are suddenly good programmers. If I considered garbage collection bad, I would say so. But like airbags doesn't improve the driving skills of someone, so doesn't all kind of restrictions turn bad programmers suddenly in good programmers. Moreover, good programmers rarely need to be restricted. But I don't see garbage collection as an anti-memory-leak restriction (which it can't be in all cases) but as a time saver. >> What makes you think there are isolated communities? > > Let's see. LISP - some of the communities were MacLISP, InterLISP, > Zeta LISP, and Standard LISP. There are certainly others I > forgot. Perl - they don't have names, they just show up in the code I > have to maintain. But is that because there are separate communities, or because there are different skill levels? Moreover, I hope that "have to maintain" was "had to maintain (some time ago)", because your Perl skills are more than lacking. >> How long haven't you been in touch with Perl? > > Oh, are you claiming that PERL ships with HTML and XML parsers, SMTP > clients and web servers in the standard library? Which Perl? ActiveState Perl does indeed come with HTML, and XML parsers, SMTP, etc, clients. Web server(s), I have no idea, haven't needed a Perl webserver, I doubt it comes with AS Perl. > That's odd - all the > packages I see seem to want to install those things from CPAN. Is there such a centralized place for libraries for Python? >> I use either for or while. > > You never use the Perl foreach loop? That doesn't sound like a skilled > Perl programmer to me. I already stated you have little Perl experience. Now I have to change that to *extremely* little Perl experience. So it seems I am right: the overwhelming effect of "many ways" is mainly seen by absolute beginners, who are able to make up many ways, even if there is just one or two :-D. >> How did you measure this? And which distribution of Perl are you >> talking about? > > By looking at the functionality installed programs used from third > parties (i.e. - CPAN in recent version) vs. what they used from the > standard library. And in Perl 4 and 5. Perl 4? Even Perl 5 is almost 11 years old. Which version of Perl 5 are you talking about? >>> Right - Perl makes writing ugly, >> Nope, the programmer does that. > > No, the programme writes the ugly code. Perl makes it easy. So, and who is to blame? Would you trust a programmer who can only write code in a certain way because he is restricted by the langauge to do so? And do you really think his/her code would be better compared to a skilled programmer? >> And I think that there is the main problem in your whole story. You >> think this is a quest for superiority. It isn't. > > What? You're not trying to find the superior tool for the application > domain? Then what *are* you doing? Programming, in a skilled way. There is no ultimate superior tool. Why do you think I am learning Python? Because I found the holy grail? Or that I just want another way to do things? >> But if this all bothers you *this* much, I am afraid that the problem >> is really behind the keyboard :-) > > No, what bothers me *this* much is that every time I have to maintain > a Perl program, I have to learn somebody else's subset/idioms/etc of > the language. "All this" is the cause of that. No. If this was crossposted in a Perl group, by now quite a lot of people would have pointed you out, probably in a less nice way, that your Perl skills are of a person who hasn't even gone beyond the first few chapters of "Learning Perl". >> Yup, to pick a tool out of a organized toolbox. Which is fine if >> that's the only job involved. Programming, or as I see it, is not >> about picking tools out of a box, but combining them. > > Right. A good language will have an obvious tool for each part of the > combination, so you don't spend time worrying about picking the right > tools - the right choices are obvious. A bad language will have more > than one tool for many parts of the combination, so you wind up > wasting time on which of n interchangable tools is the right one > instead of actually solving the problem at hand. And a bad programmer will go at great length explaining how bad the tools are, because he has to learn them :-D -- John MexIT: http://johnbokma.com/mexit/ personal page: http://johnbokma.com/ Experienced programmer available: http://castleamber.com/ Happy Customers: http://castleamber.com/testimonials.html From sabbey at u.washington.edu Fri Apr 15 19:44:58 2005 From: sabbey at u.washington.edu (Brian Sabbey) Date: Fri, 15 Apr 2005 16:44:58 -0700 Subject: pre-PEP: Simple Thunks Message-ID: Here is a first draft of a PEP for thunks. Please let me know what you think. If there is a positive response, I will create a real PEP. I made a patch that implements thunks as described here. It is available at: http://staff.washington.edu/sabbey/py_do Good background on thunks can be found in ref. [1]. Simple Thunks ------------- Thunks are, as far as this PEP is concerned, anonymous functions that blend into their environment. They can be used in ways similar to code blocks in Ruby or Smalltalk. One specific use of thunks is as a way to abstract acquire/release code. Another use is as a complement to generators. A Set of Examples ================= Thunk statements contain a new keyword, 'do', as in the example below. The body of the thunk is the suite in the 'do' statement; it gets passed to the function appearing next to 'do'. The thunk gets inserted as the first argument to the function, reminiscent of the way 'self' is inserted as the first argument to methods. def f(thunk): before() thunk() after() do f(): stuff() The above code has the same effect as: before() stuff() after() Other arguments to 'f' get placed after the thunk: def f(thunk, a, b): # a == 27, b == 28 before() thunk() after() do f(27, 28): stuff() Thunks can also accept arguments: def f(thunk): thunk(6,7) do x,y in f(): # x==6, y==7 stuff(x,y) The return value can be captured def f(thunk): thunk() return 8 do t=f(): # t not bound yet stuff() print t ==> 8 Thunks blend into their environment def f(thunk): thunk(6,7) a = 20 do x,y in f(): a = 54 print a,x,y ==> 54,6,7 Thunks can return values. Since using 'return' would leave it unclear whether it is the thunk or the surrounding function that is returning, a different keyword should be used. By analogy with 'for' and 'while' loops, the 'continue' keyword is used for this purpose: def f(thunk): before() t = thunk() # t == 11 after() do f(): continue 11 Exceptions raised in the thunk pass through the thunk's caller's frame before returning to the frame in which the thunk is defined: def catch_everything(thunk): try: thunk() except: pass # SomeException gets caught here try: do catch_everything(): raise SomeException except: pass # SomeException doesn't get caught here because it was already caught Because thunks blend into their environment, a thunk cannot be used after its surrounding 'do' statement has finished: thunk_saver = None def f(thunk): global thunk_saver thunk_saver = thunk do f(): pass thunk_saver() # exception, thunk has expired 'break' and 'return' should probably not be allowed in thunks. One could use exceptions to simulate these, but it would be surprising to have exceptions occur in what would otherwise be a non-exceptional situation. One would have to use try/finally blocks in all code that calls thunks just to deal with normal situations. For example, using code like def f(thunk): thunk() prevent_core_meltdown() with code like do f(): p = 1 return p would have a different effect than using it with do f(): return 1 This behavior is potentially a cause of bugs since these two examples might seem identical at first glance. The thunk evaluates in the same frame as the function in which it was defined. This frame is accessible: def f(thunk): frame = thunk.tk_frame do f(): pass Motivation ========== Thunks can be used to solve most of the problems addressed by PEP 310 [2] and PEP 288 [3]. PEP 310 deals with the abstraction of acquire/release code. Such code is needed when one needs to acquire a resource before its use and release it after. This often requires boilerplate, it is easy to get wrong, and there is no visual indication that the before and after parts of the code are related. Thunks solve these problems by allowing the acquire/release code to be written in a single, re-usable function. def acquire_release(thunk): f = acquire() try: thunk(f) finally: f.release() do t in acquire_release(): print t More generally, thunks can be used whenever there is a repeated need for the same code to appear before and after other code. For example, do WaitCursor(): compute_for_a_long_time() is more organized, easier to read and less bug-prone than the code DoWaitCursor(1) compute_for_a_long_time() DoWaitCursor(-1) PEP 288 tries to overcome some of the limitations of generators. One limitation is that a 'yield' is not allowed in the 'try' block of a 'try'/'finally' statement. def get_items(): f = acquire() try: for i in f: yield i # syntax error finally: f.release() for i in get_items(): print i This code is not allowed because execution might never return after the 'yield' statement and therefore there is no way to ensure that the 'finally' block is executed. A prohibition on such yields lessens the suitability of generators as a way to produce items from a resource that needs to be closed. Of course, the generator could be wrapped in a class that closes the resource, but this is a complication one would like to avoid, and does not ensure that the resource will be released in a timely manner. Thunks do not have this limitation because the thunk-accepting function is in control-- execution cannot break out of the 'do' statement without first passing through the thunk-accepting function. def get_items(thunk): # <-- "thunk-accepting function" f = acquire() try: for i in f: thunk(i) # A-OK finally: f.release() do i in get_items(): print i Even though thunks can be used in some ways that generators cannot, they are not nearly a replacement for generators. Importantly, one has no analogue of the 'next' method of generators when using thunks: def f(): yield 89 yield 91 g = f() g.next() # == 89 g.next() # == 91 [1] see the "Extended Function syntax" thread, http://mail.python.org/pipermail/python-dev/2003-February/ [2] http://www.python.org/peps/pep-0310.html [3] http://www.python.org/peps/pep-0288.html From robin at SPAMREMOVEjessikat.fsnet.co.uk Thu Apr 28 16:33:04 2005 From: robin at SPAMREMOVEjessikat.fsnet.co.uk (Robin Becker) Date: Thu, 28 Apr 2005 20:33:04 +0000 Subject: regex over files In-Reply-To: References: <426D0659.7080307@chamonix.reportlab.co.uk> <426D08BC.1040703@klix.ch> <426E021E.8000809@jessikat.fsnet.co.uk> <17006.31984.182979.430076@montanaro.dyndns.org> <426E893D.2070905@chamonix.reportlab.co.uk> <426EAA9D.2050904@jessikat.fsnet.co.uk> <426F5B62.3010801@chamonix.reportlab.co.uk> Message-ID: <42714880.4080205@jessikat.fsnet.co.uk> Skip Montanaro wrote: >... > > I'm not sure why the mmap() solution is so much slower for you. Perhaps on > some systems files opened for reading are mmap'd under the covers. I'm sure > it's highly platform-dependent. (My results on MacOSX - see below - are > somewhat better.) > > Let me return to your original problem though, doing regex operations on > files. I modified your two scripts slightly: > I'm sure my results are dependent on something other than the coding style I suspect file/disk cache and paging operates here. Note that we now agree on total match length and split count. However, when the windows VM goes into paging mode the mmap thing falls off the world as I would expect for a thrashing system. eg small memory (relatively) C:\code\reportlab\demos\gadflypaper>\tmp\sscan0.py xxx_100mb.dat fn=xxx_100mb.dat n=1898737 l=90506416 time=3.55 C:\code\reportlab\demos\gadflypaper>\tmp\sscan1.py xxx_100mb.dat fn=xxx_100mb.dat n=1898737 l=90506416 time=8.25 C:\code\reportlab\demos\gadflypaper>\tmp\sscan1.py xxx_100mb.dat fn=xxx_100mb.dat n=1898737 l=90506416 time=9.77 C:\code\reportlab\demos\gadflypaper>\tmp\sscan0.py xxx_100mb.dat fn=xxx_100mb.dat n=1898737 l=90506416 time=5.09 C:\code\reportlab\demos\gadflypaper>\tmp\sscan1.py xxx_100mb.dat fn=xxx_100mb.dat n=1898737 l=90506416 time=6.17 C:\code\reportlab\demos\gadflypaper>\tmp\sscan0.py xxx_100mb.dat fn=xxx_100mb.dat n=1898737 l=90506416 time=4.64 and large memory C:\code\reportlab\demos\gadflypaper>\tmp\sscan0.py xxx_200mb.dat fn=xxx_200mb.dat n=3797470 l=181012689 time=20.16 C:\code\reportlab\demos\gadflypaper>\tmp\sscan1.py xxx_200mb.dat fn=xxx_200mb.dat n=3797470 l=181012689 time=136.42 At the end of this run I had to wait quite a long time for other things to become responsive (ie things were entirely paged out). as another data point with sscan0/1.py (slight mods of your code) I get this with a 200mb file on freeBSD 4.9 /usr/RL_HOME/users/robin/sstest: $ python sscan0.py xxx_200mb.dat fn=xxx_200mb.dat n=3797470 l=181012689 time=7.37 /usr/RL_HOME/users/robin/sstest: $ python sscan1.py xxx_200mb.dat fn=xxx_200mb.dat n=3797470 l=181012689 time=129.65 /usr/RL_HOME/users/robin/sstest: ie the freeBSD vm seems to thrash just as nastily as xp :( #################################################################### Here I've implemented slightly modified versions of the scanners that you put forward. eg #sscan0.py thanks to Bengt import sys, time, re fn = sys.argv[1] rxo = re.compile('XXXXX') def frxsplit(path, rxo, chunksize=4096): buffer = '' for chunk in iter((lambda f=open(path,'rb'): f.read(chunksize)),''): buffer += chunk pieces = rxo.split(buffer) for piece in pieces[:-1]: yield piece buffer = pieces[-1] yield buffer l=n=0 t0 = time.time() for mat in frxsplit(fn,rxo): n += 1 l += len(mat) t1 = time.time() print "fn=%s n=%d l=%d time=%.2f" % (fn, n, l, (t1-t0)) #sscan1.py thanks to Skip import sys, time, mmap, os, re fn = sys.argv[1] fh=os.open(fn,os.O_BINARY|os.O_RDONLY) s=mmap.mmap(fh,0,access=mmap.ACCESS_READ) l=n=0 t0 = time.time() for mat in re.split("XXXXX", s): n += 1 l += len(mat) t1 = time.time() print "fn=%s n=%d l=%d time=%.2f" % (fn, n, l, (t1 -- Robin Becker From martin at v.loewis.de Fri Apr 1 00:24:44 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 01 Apr 2005 07:24:44 +0200 Subject: Change between Python 2.3 and 2.4 under WinXP In-Reply-To: <1112308637.190093.70910@l41g2000cwc.googlegroups.com> References: <424c5c9b$0$13375$9b622d9e@news.freenet.de> <1112308637.190093.70910@l41g2000cwc.googlegroups.com> Message-ID: <424cdb1c$0$19434$9b622d9e@news.freenet.de> Cappy2112 wrote: > Do you really think this is a safe solution? Not sure which of the three solutions I mentioned you are referring to as "this". > How do you deal with features that are in new 2.4, but you invoke it > with the exe from 2.3? If you want to have the script run with both Python 2.3 and 2.4, you should avoid using features new in 2.4. Alternatively, you can check for the presence of the feature, and fall back gracefully if the feature is missing. > The imports have to be handled as well, and the dlls, and the libs too Yes. Using different interpreter binaries (i.e. \python23\python.exe vs. \python24\python.exe) will automatically take care of this. Each interpreter binary will safely have its own Python path, use its own dlls, and its own libs. Regards, Martin From rbt at athop1.ath.vt.edu Mon Apr 25 16:41:07 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Mon, 25 Apr 2005 16:41:07 -0400 Subject: Python, Perl & PDF files In-Reply-To: <2zcbe.312$461.60@newssvr11.news.prodigy.com> References: <2zcbe.312$461.60@newssvr11.news.prodigy.com> Message-ID: Philippe C. Martin wrote: > This is highly frustrating !! > > Did Athena come to help or not ? > > > > > > Christos TZOTZIOY Georgiou wrote: > > >>On Mon, 25 Apr 2005 10:32:11 -0400, rumours say that rbt >> might have written: >> >> >>>I do not seek to provoke. Sorry if my question comes across that way to >>>you. >> >>Thanks for giving attention to my post, no need for apologies. >> >>By the way, you didn't say in which way ReportLab and pdflib are not >>helpful to you (packages suggested directly by Mike Meyer and indirectly >>by me). > > NO. From mage at mage.hu Sun Apr 24 14:18:43 2005 From: mage at mage.hu (Mage) Date: Sun, 24 Apr 2005 20:18:43 +0200 Subject: when will the file be closed Message-ID: <426BE303.3040305@mage.hu> Hello, The question is above: when will these file be closed? for s in file('/etc/passwd'): print s file('/home/mage/test.txt','w').write('foo') Mage From paul at boddie.org.uk Thu Apr 7 10:44:05 2005 From: paul at boddie.org.uk (Paul Boddie) Date: 7 Apr 2005 07:44:05 -0700 Subject: Calling a Perl Module from Python ( future direction of Python) References: <351e8871050406092449d4585b@mail.gmail.com> <20050406184257.71587.qmail@web20707.mail.yahoo.com> Message-ID: <5339b60d.0504070644.2bf4153b@posting.google.com> Steve Holden wrote in message news:... > > You might also look at the work Richard Jones and others did on PyPI > during their PyCon sprint. Richard was confident that PyPI Hmmm. It would appear that this information wasn't "cleared" by the PSU. ;-) Paul From pete at osc.edu Tue Apr 19 10:04:15 2005 From: pete at osc.edu (Peter G Carswell) Date: Tue, 19 Apr 2005 10:04:15 -0400 Subject: New to Tkinter... In-Reply-To: References: Message-ID: Eric Brunel wrote: > On Tue, 19 Apr 2005 09:35:03 -0400, Peter G Carswell > wrote: > >> Good Morning. >> >> I am new to Tkinter. I have been testing the installation of Tkinter >> through the python web site. The first two test steps give no errors, >> 'import _tkinter' and 'import Tkinter'. However, the third step, >> 'Tkinter._test', gives the error: >> > > > This is not an error. It's just the value of the _test function in the > Tkinter module. You don't give the URL where you found the > installation/test instructions, but you probably want: > > Tkinter._test() > > which *calls* the function. Tkinter._test just returns its value > (functions are first class objects in Python...) > > HTH Thanks, I realized my beginners' error just after I emailed the newgroup. I am sure this won't be my last question. pete -- Peter G. Carswell The Ohio Supercomputer Center pete at osc.edu work: 614.292.1091 fax: 614.292.XXXX "DOC NOTE, I DISSENT. A FAST NEVER PREVENTS A FATNESS. I DIET ON COD." -Peter Hilton From eibrandr at gmail.com Wed Apr 20 09:30:12 2005 From: eibrandr at gmail.com (Richard Eibrand) Date: Wed, 20 Apr 2005 14:30:12 +0100 Subject: Python Debugger with source code tracking ability In-Reply-To: References: Message-ID: <1a8f96a00504200630654a24c9@mail.gmail.com> On 4/20/05, Jaime Wyant wrote: > I haven't tried the customizations listed at the site below. If it > works, let me know. > > http://page.sourceforge.net/tricks.html > > jw > > On 19 Apr 2005 19:45:05 -0700, Tran Tuan Anh wrote: > > Hi all, > > > > I am new to Python and desperated to look for a good Python debugger. > > I mean a debugger with source coding tracking. For C/C++, emacs and > > gud offers execellent development env. The source code tracking is > > extremely useful for recursive functions. You could take a look at Eclipse (http://eclipse.org/) in conjunction with pydev (http://pydev.sourceforge.net/). Or you could take a look at Komodo (http://www.activestate.com/Products/Komodo/) which is a commercial product with a trial version. Regards, R From __peter__ at web.de Wed Apr 20 02:58:55 2005 From: __peter__ at web.de (Peter Otten) Date: Wed, 20 Apr 2005 08:58:55 +0200 Subject: Array of Chars to String References: <42658990.7739398@news.oz.net> Message-ID: Michael Spencer wrote: > >>>?def?func_join(s,?letters): > ...?????return?"".join(letter?for?letter?in?s?if?letter?in?set(letters)) Make that def func_join(s, letters): letter_set = set(letters) return?"".join(letter?for?letter?in?s?if?letter?in?letter_set) for a fair timing of a set lookup as opposed to set creation. Peter From fredrik at pythonware.com Fri Apr 22 16:51:39 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 22 Apr 2005 22:51:39 +0200 Subject: XML parsing per record References: Message-ID: Willem Ligtenberg wrote: > Since there are more than one database references possible per record you > should get per record a list of database names, database strings and > databases ids. (where the strings and the id's are really the same thing...) > So per record you check for both alternatives but since there could be > more than one, you do findall and get a (unsorted) list back. findall returns matching elements in document order. > And now you don't know which ID belonged to which database... why not? by looking at each database separately, surely you must be able to figure out if the subelement holds an ID or a string? sure, if you do document.findall(".//Object-id_id"), you'll get all IDs in document order. but if you do record.findall(".//Dbtag"), you get a list of all Dbtag elements, and can then look inside them to see what they contain. > See my problem? I'm afraid not. the document seems to have a clear structure; for some reason, you don't seem to take that into account in your program. From eurleif at ecritters.biz Sat Apr 30 04:53:40 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Sat, 30 Apr 2005 08:53:40 GMT Subject: Python Challenge ahead [NEW] for riddle lovers In-Reply-To: References: Message-ID: pythonchallenge wrote: > For the riddles' lovers among you, you are most invited to take part > in the Python Challenge, the first python programming riddle on the net. > > You are invited to take part in it at: > http://www.pythonchallenge.com Very neat, I love things like this. Level 5 is maddening. Keep up the good work. From fraca7 at free.fr Thu Apr 21 06:11:16 2005 From: fraca7 at free.fr (Fraca7) Date: Thu, 21 Apr 2005 12:11:16 +0200 Subject: ANN: Python 2.3.2 for PalmOS available References: <1113608405.558884.235890@f14g2000cwb.googlegroups.com> <1113922995.033230.159220@f14g2000cwb.googlegroups.com> Message-ID: On Tue, 19 Apr 2005 08:03:15 -0700, Lucio Torre wrote: > Do you have any experience on PODS? The whole thing is based on > Codewarrior and Codewarrior for palm is dead. Nope. Actually, I'm kind of reluctant to use IDEs and it seems PODS is targeted towards Eclipse users; I'd rather use prc-tools since I'm used to the GNU development tools. From fredrik at pythonware.com Mon Apr 11 03:28:29 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 11 Apr 2005 09:28:29 +0200 Subject: Thoughts on some stdlib modules References: <1113121254.874488.111250@f14g2000cwb.googlegroups.com> <42595E3D.7080301@v.loewis.de> Message-ID: Martin v. L?wis wrote: >> if I were in charge > > Would you like to be? I can help build an infrastructure that makes it easier to create a more complete standard distribution, sure. (and since this isn't exactly a new idea, I'm 100% confident that I don't have to do all the work myself.) if this is needed is something for the PSF to decide, I suppose. From vahmad70 at yahoo.com Tue Apr 19 15:09:04 2005 From: vahmad70 at yahoo.com (waqar) Date: 19 Apr 2005 12:09:04 -0700 Subject: python Message-ID: <27b90ebf.0504191109.b4d8513@posting.google.com> I am new to python. I need some information on following specifically: - Background & Evolution of python - current application areas - future trend. Kindly any one provide me such information or tell websites for that purpose. From ivanlan at pauahtun.org Thu Apr 14 11:06:08 2005 From: ivanlan at pauahtun.org (Ivan Van Laningham) Date: Thu, 14 Apr 2005 09:06:08 -0600 Subject: A little request about spam References: <1113416856.914310.63930@l41g2000cwc.googlegroups.com> <740c3aec05041405157cb90625@mail.gmail.com> <7ee3dcd80504140551385ce25e@mail.gmail.com> <425E7CB8.85DD2BA4@pauahtun.org> <20050414143640.GA94191@isis.sigpipe.cz> Message-ID: <425E86E0.1F4207AE@pauahtun.org> Hi All-- Roman Neuhauser wrote: > > # ivanlan at pauahtun.org / 2005-04-14 08:22:48 -0600: > > The listowner could turn on the [PYTHON] headers. > > I hope they don't. > What's your reasoning? > > I'm not using spambayes yet, although I'm leaning toward it, but that > > step alone could save me some work when trying to decide based on > > subject line alone whether or not an email is spam. As it stands now, > > it's too easy to decide incorrectly that "Subject: Inelegant" is a > > spamdunk. > > Don't base your decisions (only) on subject then. Oh, and spam sent > through the list would have the [PYTHON] space eater too, so what > would it buy you? > Of course I wouldn't base decisions _only_ on whether or not [PYTHON] appears in the subject. But I ordinarily do base decisions on the whole subject line, and I think that's perfectly reasonable. There's nothing else to go on without opening the message, and for HTML-based mail there's no surer way to let spammers know they've found a live email addres than to open it. You know that. Metta, Ivan ---------------------------------------------- Ivan Van Laningham God N Locomotive Works http://www.andi-holmes.com/ http://www.foretec.com/python/workshops/1998-11/proceedings.html Army Signal Corps: Cu Chi, Class of '70 Author: Teach Yourself Python in 24 Hours From fuzzyman at gmail.com Tue Apr 12 10:20:28 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 12 Apr 2005 07:20:28 -0700 Subject: Northampton, UK Message-ID: <1113315628.224648.292490@f14g2000cwb.googlegroups.com> Just on the off chance.... I thought I'd ask if there were any Pythoneers out there local to Northampton UK ? Best Regards, Fuzzy http://www.voidspace.org.uk/python From tiissa at nonfree.fr Thu Apr 21 14:33:03 2005 From: tiissa at nonfree.fr (tiissa) Date: Thu, 21 Apr 2005 20:33:03 +0200 Subject: __del__ and reference count problem In-Reply-To: <1114107504.036833.109360@z14g2000cwz.googlegroups.com> References: <97O9e.70365$mL3.4834342@phobos.telenet-ops.be> <1114107504.036833.109360@z14g2000cwz.googlegroups.com> Message-ID: <4267f1e0$0$8871$636a15ce@news.free.fr> ajikoe at gmail.com wrote: > Your problem can be simplified : > > class A: > pop = 11 > def __del__(self): > print A.pop > > if __name__ == '__main__': > objA = A() > > I got the same error message, and I don't know why ? it looks like the > class variable can't be accessed from __del__? It's interesting to note that self.pop instead of A.pop works as expected. But I don't know why A.pop doesn't. From lothar at ultimathule.nul Tue Apr 5 12:24:05 2005 From: lothar at ultimathule.nul (lothar) Date: Tue, 5 Apr 2005 16:24:05 -0000 Subject: re module non-greedy matches broken References: <115040egk00tf9d@corp.supernews.com><11535p0mdgqde1@corp.supernews.com> Message-ID: <1155et6khhpqu8c@corp.supernews.com> a non-greedy match is implicitly defined in the documentation to be one such that there is no proper substring in the return which could also match the regex. the documentation implies the module will return a non-greedy match. the module does not return a non-greedy match. "Fredrik Lundh" wrote in message news:mailman.1392.1112714523.1799.python-list at python.org... > "lothar" wrote: > > > with respect to the documentation, the module is broken. > > nope. > > > the module does not necessarily deliver a "minimal length" match for a > > non-greedy pattern. > > it isn't supposed to: a regular expression describes a *set* of matching > strings, and the engine is free to return any string from that set. Python's > engine returns the *first* string it finds that belongs to the set. if you use > a non-greedy operator, the engine will return the first non-greedy match > it finds, not the overall shortest non-greedy match. > > if you don't want to understand how regular expressions work, don't use > them. > > > > > From limodou at gmail.com Fri Apr 22 22:55:44 2005 From: limodou at gmail.com (limodou) Date: Sat, 23 Apr 2005 10:55:44 +0800 Subject: Frog 1.4 (web log aka blogging server) In-Reply-To: <4269535a$0$145$e4fe514c@news.xs4all.nl> References: <4269535a$0$145$e4fe514c@news.xs4all.nl> Message-ID: <505f13c05042219551ff8ea55@mail.gmail.com> great! How about change the bbcode like editor to FCKeditor? I think FCKeditor is much better, or make it as an optional editor which the user could select it himself. 2005/4/23, Irmen de Jong : > I've released a new version of Frog, a web log > aka blogging server written in 100% python. > > Get version 1.4 from http://snakelets.sourceforge.net/frog/index.html > > (note: storage file format has been changed since v1.3) > > Some of the more interesting features are: > > - multi user > - no database needed (uses files for storage) > - no web server needed (it runs in Snakelets, > which has its own web server) > - splitted articles ("read more...") > - email notification when comment is added > - formatting similar to 'bbcode', supports images and other files > - anti-spam measures: puzzles, auto-updating link blacklist, > anti-indexing hyperlinks in comments (rel="nofollow") > - outputs lean xhtml+css pages > - fully unicode compatible > - web-based file manager, available as separate module > > Have fun :) > > --Irmen > > PS You can see Frog in action here: > http://www.razorvine.net/snake/frog/user/irmen/ > -- > http://mail.python.org/mailman/listinfo/python-announce-list > > Support the Python Software Foundation: > http://www.python.org/psf/donations.html > -- I like python! My Donews Blog: http://www.donews.net/limodou New Google Maillist: http://groups-beta.google.com/group/python-cn From roy at panix.com Thu Apr 7 22:11:48 2005 From: roy at panix.com (Roy Smith) Date: Thu, 07 Apr 2005 22:11:48 -0400 Subject: How to name Exceptions that aren't Errors References: <3blfl8F6gt80jU1@individual.net> Message-ID: Leo Breebaart wrote: > I've recently become rather fond of using Exceptions in Python to > signal special conditions that aren't errors, but which I feel > are better communicated up the call stack via the exception > mechanism than via e.g. return values. > > For instance, I'm thinking of methods such as: > > > def run(self): > """ Feed the input file to the simulator. """ > > for linenr, line in enumerate(self.infile): > try: > current_values = self.parse_line(linenr, line) > ==> except CommentLineException: > continue > results = self.do_one_simulation_step(current_values) > self.process_simulation_results(results) I know this isn't the question you asked, but I would have written a little generator function which hides the comment processing in a lower level: def nonCommentLines (file): for lineNumber, line in enumerate (file): if not line.startswith('#'): yield lineNumber, line for lineNumber, line in nonCommentLines (sys.stdin): current_values = self.parse_line(linenr, line) results = self.do_one_simulation_step(current_values) self.process_simulation_results(results) This assumes you don't mind your line numbers starting from zero, but your version has the same behavior. > My question is twofold. First, I know that many programmers are > violently opposed to using exceptions in this fashion, i.e. for > anything other than, well, exceptional circumstances. But am I > correct in thinking that in Python this usage is actually > considered quite normal, and not frowned upon? Is my snippet > above indeed sufficiently Pythonic? I think my code is clearer, but I wouldn't go so far as to say I'm violently opposed to your code. I save violent opposition for really important matters like which text editor you use. I suspect if you showed your code to a C++ guy, he might be violently opposed. In C++, exceptions are perceived to be more heavyweight than they are in Python. Some of this is just perception (perhaps colored by historical issues with older C++ compilers not handling exceptions well), some of it is real. Just the other day, a colleague of mine was telling me about a bug in his code. It happened because he had failed to write a copy constructor for an exception class he wrote. The mind boggles how anybody can get anything useful done in a language like that. But I digress. In Python, exceptions seem to be the much more accepted way of doing things. You often see: try: value = dictionary[key] except KeyError: whatever instead of: if dictionary.has_key (key): value = dictionary[key] else: whatever While in C++, the "if" version would be far more common. > Second, purely as a question of aesthetics, I was wondering if > the folks here might have any opinions about actual naming > conventions for the exception classes used in this fashion. If you look at the list of standard exceptions (import exceptions and do a dir() on it), you'll see things like KeyboardInterrupt, StopIteration, and SystemExit. If the name fits, raise it. From superprad at gmail.com Sun Apr 24 12:00:10 2005 From: superprad at gmail.com (superprad at gmail.com) Date: 24 Apr 2005 09:00:10 -0700 Subject: Handling lists In-Reply-To: References: <1114285850.091749.188680@f14g2000cwb.googlegroups.com> Message-ID: <1114358410.431524.166110@z14g2000cwz.googlegroups.com> That helps.Thanks much. From jlenton at gmail.com Fri Apr 15 15:26:45 2005 From: jlenton at gmail.com (John Lenton) Date: 15 Apr 2005 12:26:45 -0700 Subject: module placeholder Message-ID: <1113593205.639128.197450@f14g2000cwb.googlegroups.com> Once again I'm working on code that has several 'providers' of different features, and I thought I'd ask the list what better solutions it has to this other than what I've come up with. Currently, the cleanest way I can find is to say import foo foo.config(bar='baz') # from this point on, foo.bar is provided by foo.bars.baz this could be widget sets, database connectors, persistance layers, RPC, you name it. This is very easy to do: # foo.py def config(bar_name=DEFAULT_BAR_NAME): global bar bar = __import__('foo.' + bar_name, globals(), locals(), bar_name) This would work fine if people wanted to use this (once its configured) as 'import foo; foo.bar.funkyFunction()', but no! they want to be able to do 'from foo.bar import funkyFunction', which is reasonable really because I'm just as lazy as they are. So what I've come up with is def config(bar_name=DEFAULT_BAR_NAME): global bar barModule = __import__('foo.' + bar_name, globals(), locals(), bar_name) bar.faultFrom(barModule) class proxyModule(new.module): def faultFrom(self, other): self.__other = other self.__name__ = other.__name__ self.__file__ = other.__file__ + ' [proxied]' def __getattr__(self, attr): return getattr(self.__other, attr) bar = proxyModule('bar proxy') and this is the bit that feels ugly: is there a better way to have an object that can be imported from a file and that behaves like a module, but that isn't filled in until some point down the road? From mal at egenix.com Mon Apr 4 09:59:26 2005 From: mal at egenix.com (M.-A. Lemburg) Date: Mon, 04 Apr 2005 15:59:26 +0200 Subject: Some notes about float approximations in mxNumber In-Reply-To: <1112382280.714450.170380@f14g2000cwb.googlegroups.com> References: <032720052340.23979.42474457000403FA00005DAB220699973508900A9C0E0C@comcast.net> <1112382280.714450.170380@f14g2000cwb.googlegroups.com> Message-ID: <4251483E.80608@egenix.com> Kay Schluehr wrote: > Hi Marc, > > I was a bit surprised to find the very slow Farey approximation by > means of the class in the mxNumber package. If the goal > was to reconstruct a rational from a float it is not a good choice and > should be replaced by a continued fractions approximation. The idea was to be able to create a Rational() from a float using a given upper bound on the denominator. The standard Rational() constructor already provides a way to construct a rational out of a Python or mxNumber float, but always uses maximum precision - which may not always be what the user wants (e.g. to work around rounding errors). Thanks for posting your faster version. I think it would be a good candidate for a Python Cookbook Entry and I'll see whether I can add something like this to one of the next mxNumber releases. > Some time > ago I implemented it by myself so it can be published here: > > > def cfrac(z,bound=10**-5,n=10): > ''' > creates a continued fraction from some number z. > @ bound - terminate cf if the rest is lower than the provided bound > @ n - terminate cf after n steps > ''' > l = [] > while 1: > a = int(z) > l.append(a) > y = z-a > if y<=bound or len(l)==n: > return l > z = 1./y > > > def fold(cf): > ''' > create u/v = cfrac(a0,a1,...,an) using following rules: > > 1. / u1 u0 \ / a1 1 \ / a0 1 \ > | | = | | * | | > \ v1 v0 / \ 1 0 / \ 1 0 / > > 2. The recursion rules > v(n+1) = v(n)*a(n+1)+v(n-1) > u(n+1) = u(n)*a(n+1)+u(n-1) > ''' > if len(cf)<2: > return Rational(0,1) > un = cf[0]*cf[1]+1 > vn = cf[1] > un_1 = cf[0] > vn_1 = 1 > for a in cf[2:]: > b = un > un = un*a+un_1 > un_1 = b > b = vn > vn = vn*a+vn_1 > vn_1 = b > return Rational(un,vn) > > > >>>>fold(cfrac(1./3)) > > 1/3 > >>>>fold(cfract(1525/42.)) > > 1525/42 > > import math > > >>>>fold(cfract(math.sqrt(2))) > > 3363/2378 > > > It is possible to provide this functionality in an even more efficient > manner because it is usefull to bound only the approximation error of > the rational, not the size of the continued fraction. > > def float2ratio(z, bound=10**-5): > ''' > convert a float into a Rational. > The approximation is bound by the error-limit 'bound'. > ''' > a = int(z) > y = z-a > z = 1./y > b = int(z) > un = a*b+1 > vn = b > un_1 = a > vn_1 = 1 > a = b > while 1: > y = z-a > if y return Rational(un,vn),k > z = 1./y > a = int(z) > x = un > un = un*a+un_1 > un_1 = x > x = vn > vn = vn*a+vn_1 > vn_1 = x > xn = float(un)/vn > yn = float(un_1)/vn_1 > if abs(xn-yn)<=bound: > return Rational(un,vn) > > >>>>math.sqrt(2) > > 1.4142135623730951 > > >>>>float2ratio(math.sqrt(2)) > > 1393/985 > >>>>1393./985 > > 1.4142131979695431 > ^ > > >>>>float2ratio(math.sqrt(2),10**-10) > > 275807/195025 > >>>>275807./195025 > > 1.4142135623637995 > ^ > > >>>>math.pi > > 3.1415926535897931 > > >>>>float2ratio(math.pi,10**-14) > > 245850922/78256779 > >>>>245850922./78256779 > > 3.1415926535897931 > > Note that the algorithm needed only 13 iteration steps to approximate > pi > in this accuracy. > > Regards, > Kay > -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Apr 04 2005) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ ::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,FreeBSD for free ! :::: From secun at yahoo.com Wed Apr 27 22:46:32 2005 From: secun at yahoo.com (ChrisH) Date: Thu, 28 Apr 2005 02:46:32 GMT Subject: pyqt and Eric 3 References: Message-ID: In article , secun at yahoo.com says... > Are there any Eric 3 users out there? > > I've been thinking about trying it. > > Also, if I write scripts for internal use only at my company, do I have > to purchase a Qt or pyqt license? > > Thanks for the info! > Chris > Oops.. I forgot to say I'm writing code for Windows. From raoul.daruwala at gmail.com Mon Apr 25 19:34:21 2005 From: raoul.daruwala at gmail.com (raoul) Date: 25 Apr 2005 16:34:21 -0700 Subject: Do I need a nested lambda to do this? Message-ID: <1114472061.732832.283540@l41g2000cwc.googlegroups.com> I can't figure this one out. Trying to be unnecessarily functional I suspect. I have the following lists. vals = [1.000,2.344,4.2342] tab = [((0,1),(0,3),(0,4)), ((2,2),(3,0),(3,9)), ((3,4),(6,3),(7,1))] I'm trying to create a one liner using map/reduce/lambda/zip(* etc to do replace the first element of each pair in each row by the the values in vals as follows: tab = [((1.000,1),(1.000,3),(1.000,4)), ((2.344,2),(2.344,0),(2.344,9)), ((4.2342,4),(4.2342,3),(4.2342,1))] I'm pretty sure there's a oneline way to do this. Naturally, one could loop mindlessly but this is my self-imposed programming challenge for the day and I'm not feeling much love from my python. From gnb at itga.com.au Mon Apr 11 21:57:50 2005 From: gnb at itga.com.au (Gregory Bond) Date: Tue, 12 Apr 2005 11:57:50 +1000 Subject: Threads and variable assignment Message-ID: I've had a solid hunt through the (2.3) documentation but it seems silent on this issue. I have an problem that would naturally run as 2 threads: One monitors a bunch of asyncrhonous external state and decides if things are "good" or "bad". The second thread processes data, and the processing depends on the "good" or "bad" state at the time the data is processed. Sort of like this: Thread 1: global isgood while 1: wait_for_state_change() if new_state_is_good(): isgood = 1 else: isgood = 0 Thread 2: s = socket(....) s.connect(...) f = s.makefile() while 1: l = f.readline() if isgood: print >> goodfile, l else: print >> badfile, l What guarantees (if any!) does Python make about the thread safety of this construct? Is it possible for thread 2 to get an undefined variable if it somehow catches the microsecond when isgood is being updated by thread 1? From gry at ll.mit.edu Fri Apr 29 14:02:59 2005 From: gry at ll.mit.edu (gry at ll.mit.edu) Date: 29 Apr 2005 11:02:59 -0700 Subject: module exports a property instead of a class -- Evil? Message-ID: <1114797779.371054.189950@g14g2000cwa.googlegroups.com> I often find myself wanting an instance attribute that can take on only a few fixed symbolic values. (This is less functionality than an enum, since there are no *numbers* associated with the values). I do want the thing to fiercely object to assignments or comparisons with inappropriate values. My implementation below gets me: .import mode .class C(object): . status = mode.Mode('started', 'done', 'on-hold') . .c=C() .c.status = 'started' .c.status = 'stated': #Exception raised .if c.status == 'done': something .if c.status == 'stated': #Exception raised .if c.status.done: something #simpler and clearer than string compare .if c.status < 'done': something # Mode arg strings define ordering I would appreciate comments on the overall scheme, as well as about the somewhat sneaky (I think) exporting of a property-factory instead of a class. My intent is to provide a simple clear interface to the client class ("C" above), but I don't want to do something *too* fragile or confusing... (I'd also welcome a better name than "Mode"...) -------------------------- mode.py ---------------------- class _Mode: #internal use only, not exported. def __init__(self, *vals): if [v for v in vals if not isinstance(v, str)]: raise ValueError, 'Mode values must be strings' else: self.values = list(vals) def set(self, val): if val not in self.values: raise ValueError, 'bad value for Mode: "%s"' % val else: self.state = val def __cmp__(self, other): if other in self.values: return cmp(self.values.index(self.state), self.values.index(other)) else: raise ValueError, 'bad value for Mode comparison' def __getattr__(self, name): if name in self.values: return self.state == name else: raise AttributeError, 'no such attribute: "%s"' % name def Mode(*vals): # *function* returning a *property*, not a class. m = _Mode(*vals) def _insert_mode_get(self): return m def _insert_mode_set(self, val): m.set(val) return property(_insert_mode_get, _insert_mode_set) ----------------------------------------------------------- Thanks, George From philippe at philippecmartin.com Mon Apr 25 15:43:07 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Mon, 25 Apr 2005 19:43:07 GMT Subject: what is the best way to determine system OS? References: <1114436211.942212.203790@f14g2000cwb.googlegroups.com> Message-ID: Well, At least I discovered os.uname :-) Thanks, Philippe Sion Arrowsmith wrote: > Philippe C. Martin wrote: >>How about popen of 'uname -r' ? > > os.uname()[2] is probably a better way (ie it doesn't spawning > another process) of getting this information. I don't think it > will help the original poster though (depending on *what* it is > about FC3 which is breaking things) since it only provides the > kernel version. > From bokr at oz.net Tue Apr 19 02:35:06 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 19 Apr 2005 06:35:06 GMT Subject: Enumerating formatting strings References: Message-ID: <42649c7f.321180923@news.oz.net> On Mon, 18 Apr 2005 16:24:39 -0400, Steve Holden wrote: >I was messing about with formatting and realized that the right kind of >object could quite easily tell me exactly what accesses are made to the >mapping in a string % mapping operation. This is a fairly well-known >technique, modified to tell me what keys would need to be present in any >mapping used with the format. > >I've been wondering whether it's possible to perform a similar analysis >on non-mapping-type format strings, so as to know how long a tuple to >provide, or whether I'd be forced to lexical analysis of the form string. > When I was playing with formatstring % mapping I thought it could be useful if you could get the full format specifier info an do your own complete formatting, even for invented format specifiers. This could be done without breaking backwards compatibility if str.__mod__ looked for a __format__ method on the other-wise-mapping-or-tuple-object. If found, it would call the method, which would expect def __format__(self, ix, # index from 0 counting every %... format name, # from %(name) or '' width, # from %width.prec prec, # ditto fc, # the format character F in %(x)F all # just a copy of whatever is between % and including F ): ... This would obviously let you handle non-mapping as you want, and more. The most popular use would probably be intercepting width in %(name)s and doing custom formatting (e.g. centering in available space) for the object and returning the right size string. Since ix is an integer and doesn't help find the right object without the normal tuple, you could give your formatting object's __init__ method keyword arguments to specify arguments for anonymous slots in the format string, conventionally naming them a0, a1, a2 etc. Then later when you get an ix with no name, you could write self.kw.get('%as'%ix) to get the value, as in use like '%(name)s %s' % Formatter(a1=thevalue) # Formatter as base class knows how to do name lookup Or is this just idearrhea? Regards, Bengt Richter From claird at lairds.us Wed Apr 20 14:08:03 2005 From: claird at lairds.us (Cameron Laird) Date: Wed, 20 Apr 2005 18:08:03 GMT Subject: goto statement References: <20050420092359.81900.qmail@web8409.mail.in.yahoo.com> <42664190.6010507@i.com.ua> Message-ID: <1rgij2-98r.ln1@lairds.us> In article , Maxim Kasimov wrote: . . . >>> if you need to comment a couple of code (and then uncomment ), what >>> are you doing then? >> >> >> Use comments? >> > >WOW, just greate! ... but i'd like to relax at some more interesting way >than to comment each of rows . . . Mr. Kasimov, here's another idiom you might want to consider: # Notice that we can make a code fragment into a string, # which is evaluated, then discarded. a = b c = d """e = f g = h i = j""" k = l From ville at spammers.com Sat Apr 23 11:04:25 2005 From: ville at spammers.com (Ville Vainio) Date: 23 Apr 2005 18:04:25 +0300 Subject: Caching compiled regexps across sessions (was Re: Regular Expressions - Python vs Perl) References: <1114092105.964664.211430@l41g2000cwc.googlegroups.com> Message-ID: >>>>> "Ilpo" == Ilpo Nyyss?nen writes: >> so you picked the wrong file format for the task, and the slowest Ilpo> What would you recommend instead? Ilpo> I have searched alternatives, but somehow I still find XML Ilpo> the best there is. It is a standard format with standard Ilpo> programming API. Ilpo> I don't want to lose my calendar data. XML as a standard Ilpo> format makes it easier to convert later to some other Ilpo> format. As a textual format it is also readable as raw also Ilpo> and this eases debugging. Use pickle, perhaps, for optimal speed and code non-ugliness. You can always use xml as import/export format, perhaps even dumping the db to xml at the end of each day. Ilpo> And my point is that the regular expression compilation can Ilpo> be a problem in python. The current regular expression Ilpo> engine is just unusable slow in short lived programs with a Ilpo> bit bigger amount of regexps. And fixing it should not be Ilpo> that hard: an easy improvement would be to add some kind of Ilpo> storing mechanism for the compiled regexps. Are there any Ilpo> reasons not to do this? It should start life as a third-party module (perhaps written by you, who knows :-). If it is deemed useful and clean enough, it could be integrated w/ python proper. This is clearly something that should not be in the python core, because the regexps themselves aren't there either. >> python has shipped with a fast XML parser since 2.1, or so. Ilpo> With what features? validation? I really want a validating Ilpo> parser with a DOM interface. (Or something better than DOM, Ilpo> must be object oriented.) Check out (coincidentally) Fredrik's elementtree: http://effbot.org/zone/element-index.htm Ilpo> I don't want to make my programs ugly (read: use some more Ilpo> low level interface) and error prone (read: no validation) Ilpo> to make them fast. Why don't you use external validation on the created xml? Validating it every time sounds like way too much like Javaic B&D to be fun anymore. Pickle should serve you well, and would probably remove about half of your code. "Do the simplest thing that could possibly work" and all that. -- Ville Vainio http://tinyurl.com/2prnb From mahs at telcopartners.com Sat Apr 9 05:37:26 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Sat, 09 Apr 2005 02:37:26 -0700 Subject: How to check whether a list have specific value exist or not? In-Reply-To: <20050409093226.96954.qmail@web8402.mail.in.yahoo.com> References: <20050409093226.96954.qmail@web8402.mail.in.yahoo.com> Message-ID: praba kar wrote: > Dear All > In Php we can find in_array() function > which function is mainly useful to check > whether a specific value is exist in the array > or not. > > But In python In cannot find any function > like that. I want to check a list have specific > value or not. So If any one know regarding this > mail me > > with regards > PRabahar > > > ________________________________________________________________________ > Yahoo! India Matrimony: Find your life partner online > Go to: http://yahoo.shaadi.com/india-matrimony No need to ask this list, ask the built-in one: >>> dir(list) ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__str__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] A minute of two experimenting, would then lead you to: >>> l = [1,2,3,4,5] >>> l.index(3) 2 >>> Note that all indexing in Python is 0-based Michael From radam2 at tampabay.rr.com Mon Apr 4 16:02:51 2005 From: radam2 at tampabay.rr.com (Ron_Adam) Date: Mon, 04 Apr 2005 20:02:51 GMT Subject: Decorator Base Class: Needs improvement. Message-ID: <0v4351l5v1f3i9h3fssvcfklifkdlhjv7o@4ax.com> Hi, Thanks again for all the helping me understand the details of decorators. I put together a class to create decorators that could make them a lot easier to use. It still has a few glitches in it that needs to be addressed. (1) The test for the 'function' object needs to not test for a string but an object type instead. (2) If the same decorator instance is stacked, it will get locked in a loop. But stacking different instances created from the same decorator object works fine. (3) It has trouble if a decorator has more than one argument. But I think all of these things can be fixed. Would this be something that could go in the builtins library? (After any issues are fixed first of course.) When these are stacked, they process all the prepossess's first, call the decorator, then process all the postprocess's. It just worked out that way, which was a nice surprise and makes this work a bit different than the standard decorators. Cheers, Ron #---start--- class Decorator(object): """ Decorator - A class to make decorators with. self.function - name of function decorated. self.arglist - arguments of decorator self.preprocess - over ride to preprocess function arguments. self.postprocess - over ride to postprocess function return value. Example use: class mydecorator(Decorate): def self.preprocess(self, args): # process args return args def self.postprocess(self, results): # process results return results deco = mydecorator() @deco def function(args): # function body return args """ function = None arglist = [] def __call__(self, arg): self.arglist.append(arg) def _wrapper( args): pre_args = self.preprocess(args) result = self.function(pre_args) return self.postprocess(result) if 'function' in str(arg): self.arglist = self.arglist[:-1] self.function = arg return _wrapper return self def preprocess(self, args): return args def postprocess(self, result): return result class mydecorator(Decorater): def preprocess(self, args): args = 2*args return args def postprocess(self, args): args = args.upper() args = args + str(self.arglist[0]) return args deco = mydecorator() @deco('xyz') def foo(text): return text print foo('abc') #---end--- From ckwiguno at gmail.com Tue Apr 19 20:32:03 2005 From: ckwiguno at gmail.com (Clara) Date: 19 Apr 2005 17:32:03 -0700 Subject: The value of the entry widget doesn't get updated References: <426563c7$0$20623$626a14ce@news.free.fr> Message-ID: <1113957123.607686.135670@o13g2000cwo.googlegroups.com> Yes that solves my problem all right...THanks a bunch to both of you From Scott.Daniels at Acm.Org Fri Apr 8 12:05:39 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 08 Apr 2005 09:05:39 -0700 Subject: curious problem with large numbers In-Reply-To: References: <723eb693050407124816431b6a@mail.gmail.com> <4255cd93$1@nntp0.pdx.net> Message-ID: <4256a676@nntp0.pdx.net> Steve Holden wrote: > Scott David Daniels wrote: > >> Terry Reedy wrote: >> >>> On my Windows machine with 2.2.1, I get exactly what you expected: >>> >>>>>> 1e10000 >>> >>> 1.#INF >>> ... >>> If you get wrong behavior on a later version, then a bug has been >>> introduced somewhere, even perhaps in VC 7, used for 2.4. >> >> Nope, it is also there for 2.3.4 (May 25 2004, 21:17:02).... > > A further Windows data point from Cygwin: > > Python 2.4 (#1, Dec 4 2004, 20:10:33) > [GCC 3.3.3 (cygwin special)] on cygwin > Type "help", "copyright", "credits" or "license" for more information. > >>> 1e10000 > Inf > >>> > > regards > Steve Aha! Same version (2.3.4): Idle: >>> 1e10000 1.0 >>> import struct; struct.pack('d', 1e10000) '\x00\x00\x00\x00\x00\x00\xf0?' (which is actually 1.0) python via command line (readline support): >>> 1e10000 1.#INF >>> import struct; struct.pack('d', 1e10000) '\x00\x00\x00\x00\x00\x00\xf0\x7f' Note the difference in the final byte. Same results (command line vs. Idle) for 2.4.1. --Scott David Daniels Scott.Daniels at Acm.Org From kirk at jobsluder.net Mon Apr 25 13:39:36 2005 From: kirk at jobsluder.net (Kirk Job Sluder) Date: Mon, 25 Apr 2005 17:39:36 GMT Subject: Changing a line in a text file References: <1114421951.029066.190120@g14g2000cwa.googlegroups.com> <1114423528.568195.12750@l41g2000cwc.googlegroups.com> Message-ID: <87y8b6ah61.fsf@debian.kirkjobsluder.is-a-geek.net> Steve Holden writes: > kah wrote: > However, you asked about replacing one line with another of a > different length: since this will mean changing the offsets of all > subsequent bytes you have no way to do this other than writing out the > whole content of the file following the modification. You would also > have to ensure that you truncated the file to the correct length. > > In general, although they don't make it obvious that they are doing so > most programs that "change" files (text editors and the like) are > really writing new copies. In addition, I would argue that editing a file in place using a non-interactive program is dangerous and bad practice in general. By the time you find a bug in your edit script, the original is lost. This is something I learned from bitter experience when I tried to be smart and make script-based edits over entire directories of html files. In unix shell scripting idiom, I would do something like: mv file file.bak sed -e 'g/oldline/c newline' < file.bak > file And yes, I know that some versions of sed have the --in-place option. Then, I would check for side effects: diff file file.bak All of this can be done in python, however I'm not overly familiar with difflib and it seems to require both versions of the file in memory. So an external diff might be better. import os os.rename(foo,foo.bak) infile = open(foo.bak,'r') outfile = open(foo,'w') for line infile: #test and substitution code block outfile.write(line) Using separate input and output files also has the advantage of being memory efficient. > > regards > Steve > -- > Steve Holden +1 703 861 4237 +1 800 494 3119 > Holden Web LLC http://www.holdenweb.com/ > Python Web Programming http://pydish.holdenweb.com/ > -- Kirk Job-Sluder "The square-jawed homunculi of Tommy Hilfinger ads make every day an existential holocaust." --Scary Go Round From steve at holdenweb.com Mon Apr 25 15:15:05 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 25 Apr 2005 15:15:05 -0400 Subject: Python documentation moronicities (continued) In-Reply-To: References: <1113301533.054410.203710@z14g2000cwz.googlegroups.com> <1114454884.549187.122440@o13g2000cwo.googlegroups.com> Message-ID: Robert Kern wrote: > Xah Lee wrote: > >> I have produced my doc. >> ( http://xahlee.org/perl-python/python_re-write/lib/module-re.html ) >> >> isn't there a hundred dollars due to me? > > > No. > > [Steve Holden] > >>> The condition for winning the prize is that at least five regular >>> posters to c.l.py have to mail me and saythey think your version is >>> better. > > ... and I haven't received a single email yet. I should also point out that you originally said >> paypal me a hundred dollars and i'll rewrite the whole re doc in a few >> hours. To which I replied > I will personally pay you a hundred dollars if you can find enough > time between now and this time next week - you should be able to find > "a few hours" in 168 without unduly conveniencing yourself. That offer was made on 4/12, and it's 4/25 today, so you're six days late. Since I don't want to be thought of as a welsher, however, the offer still stands despite the delay. I await five emails from regular c.l.py posters confirming that they think your version is better than the one in the documentation. Having read it I'm not sure *why* you believe your version is better, but I am nevertheless impressed that you did get around to it. regards Steve -- Steve Holden +1 703 861 4237 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ From tgagne at wide-open-west.com Tue Apr 5 23:34:25 2005 From: tgagne at wide-open-west.com (Thomas Gagne) Date: Tue, 05 Apr 2005 23:34:25 -0400 Subject: Does IronPython indicate MS interest in dynamic languages? In-Reply-To: References: <1111603770.909447.18070@z14g2000cwz.googlegroups.com> <1f7befae05040512422ef693d4@mail.gmail.com> Message-ID: Cameron Laird wrote: > > And now, for something completely different, I'll tender a > personal view: I think Mr. Gates and Python are actually > destined to get along uncharacteristically well. Roughly, I > suspect the habits and motivations of the two are so skew, > that the usual "embrace and extend" simply won't obtain. I > soberly expect IronPython to work out well for both Microsoft > and Python. The techweb.com article said something interesting. > "Python is an open-source dynamic language; dynamic languages enable developers to produce applications more efficiently by reducing the amount of complexity in the code they write," Jason Matusow, program manager of Microsoft's Shared Source Initiative, writes on his blog. "Microsoft's IronPython project demonstrates the benefits of putting the Python dynamic language on the .NET Common Language Runtime." Assuming (I don't know for certain) that MS's PR approves all messages that leave the building, I'm wondering if this foray into dynamic languages doesn't signal something greater on MS' part. While Sun and Java (and C# for the most part) have remained statically-typed, do you think IronPython might indicate a new direction for MS language development? From megahrtz at gte.net Tue Apr 12 12:50:38 2005 From: megahrtz at gte.net (Alex Nordhus) Date: Tue, 12 Apr 2005 11:50:38 -0500 Subject: "The C++ part of the .. Has been deleted, wsTaskBarIcon Message-ID: <000001c53f7f$c15951e0$6400a8c0@grondor> I need some help. I cant seem to get rid of this error. I can program a button that will exit the program and remove the icon in the taskbar, but I have to tie it to OnTaskBarClose. OnExit and OnCloseWindow do nothing and leave the icon in the taskbar, I think I have tried every option, when you double click the icon it gives you the error. Traceback (most recent call last): File "D:/Python24/simple.py", line 43, in OnTaskBarActivate self.Show(true) File "D:\Python24\Lib\site-packages\wx-2.5.4-msw-unicode\wx\_core.py", line 11263, in __getattr__ raise PyDeadObjectError(self.attrStr % self._name) wx._core.PyDeadObjectError: The C++ part of the MyFrame object has been deleted, attribute access no longer allowed. When the program runs, you can right click on the icon in the taskbar and close and it works. I hardcoded the file > Exit button to do the same thing and that works too. However if you click the top right X to just close the window, or on close that's when the error happens. How do I get the close to work properly from the default window? I have been on this same thing for days. Any help would be greatly appreciated. Heres the code, also attaching it. from wxPython.wx import * import sys import os ID_ABOUT = 101 ID_EXIT = 102 class MyFrame(wxFrame): def __init__(self, NULL, ID, title): wxFrame.__init__(self, NULL, ID, title, wxDefaultPosition, wxSize(200, 150)) self.CreateStatusBar() self.SetStatusText("This is the statusbar") menu = wxMenu() menu.Append(ID_ABOUT, "&About", "More information about this program") menu.AppendSeparator() menu.Append(ID_EXIT, "E&xit", "Terminate the program") menuBar = wxMenuBar() menuBar.Append(menu, "&File"); self.SetMenuBar(menuBar) EVT_MENU(self, ID_ABOUT, self.OnAbout) EVT_MENU(self, ID_EXIT, self.OnTaskBarClose) # make the TaskBar icon self.tbIcon = wxTaskBarIcon() # FIX ME WITH your Icon icon = wxIcon('small.ico', wxBITMAP_TYPE_ICO) self.tbIcon.SetIcon(icon, "It Doesnt work!") EVT_TASKBAR_LEFT_DCLICK(self.tbIcon, self.OnTaskBarActivate) EVT_TASKBAR_RIGHT_UP(self.tbIcon, self.OnTaskBarMenu) EVT_MENU(self.tbIcon, self.TBMENU_CLOSE, self.OnTaskBarClose) EVT_ICONIZE(self, self.OnIconify) def OnIconify(self, evt): self.Hide() def OnTaskBarActivate(self, event): self.Show(true) TBMENU_CLOSE = 1001 def OnTaskBarMenu(self, event): menu = wxMenu() menu.Append(self.TBMENU_CLOSE, "Close") self.tbIcon.PopupMenu(menu) menu.Destroy() def OnOK(self, event): self.Show(false) def OnExit(self, event): del self.tbIcon sys.exit() def OnCloseWindow(self, event): del self.tbIcon sys.exit() def OnTaskBarClose(self, event): del self.tbIcon sys.exit() def OnAbout(self, event): dlg = wxMessageDialog(self, "This sample program shows off\n" "frames, menus, statusbars, and this\n" "message dialog.", "About Me", wxOK | wxICON_INFORMATION) dlg.ShowModal() dlg.Destroy() def TimeToQuit(self, event): self.Destroy() class MyApp(wxApp): def OnInit(self): frame = MyFrame(NULL, -1, "Hello from wxPython") frame.Show(true) self.SetTopWindow(frame) return true app = MyApp(0) app.MainLoop() -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: systraynew.py URL: From martin.witte at gmail.com Tue Apr 5 15:26:42 2005 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 5 Apr 2005 12:26:42 -0700 Subject: os.path query functions behavior incorrect? In-Reply-To: References: Message-ID: <1112729202.724140.319860@z14g2000cwz.googlegroups.com> It works fine under linux martin at ubuntu:~ $ python Python 2.3.4 (#2, Feb 2 2005, 11:10:56) [GCC 3.3.4 (Debian 1:3.3.4-9ubuntu5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import os.path >>> os.path.exists('/blah') False >>> os.path.isdir('/blah') False >>> os.path.isdir('/home/martin') True >>> os.path.exists('/home/martin') True >>> From codecraig at gmail.com Thu Apr 21 09:48:44 2005 From: codecraig at gmail.com (codecraig) Date: 21 Apr 2005 06:48:44 -0700 Subject: python classes/file structure Message-ID: <1114091324.679130.294190@g14g2000cwa.googlegroups.com> What is the best/common way to structure ur python code for an application? For example...if I create some custom GUI widgets I have this C:\stuff --> gui --: MyCustomWidget.py --: TestWidgets.py so MyCustomWidget.py has one class, class MyCustomWidget: ... so from TestWidgets.py i have to do this from gui import * widget = gui.MyCustomWidget.MyCustomWidge() ...seems weird, how should I structure this? Is it not common to have one class in a .py? thanks From nemesis at nowhere.invalid Tue Apr 12 16:11:44 2005 From: nemesis at nowhere.invalid (Nemesis) Date: Tue, 12 Apr 2005 20:11:44 GMT Subject: Python 2.4 killing commercial Windows Python development ? References: <425a9869$0$38039$bed64819@news.gradwell.net> <20050411194907.1769.17472.XPN@orion.homeinvalid> <425AF2FD.2080006@v.loewis.de> Message-ID: <20050412191956.1706.59231.XPN@orion.homeinvalid> Mentre io pensavo ad una intro simpatica "Martin v. L?wis" scriveva: >> What happens if I try to install Python2.4 on a system wich doesn't have >> the dll? > It will just work. Python installs the DLL if it is missing, and leaves > it alone (just incrementing the refcount) if it is present on the target > system. OK, so the python installer _does_ ship this dll. So also the win installer has the redistribution problem, or does they pay for redistributing msvcr71.dll? -- Computers follow your orders, not your intentions. |\ | |HomePage : http://nem01.altervista.org | \|emesis |XPN (my nr): http://xpn.altervista.org From kasimov at i.com.ua Wed Apr 20 07:00:57 2005 From: kasimov at i.com.ua (Maxim Kasimov) Date: Wed, 20 Apr 2005 14:00:57 +0300 Subject: goto statement In-Reply-To: References: <20050420092359.81900.qmail@web8409.mail.in.yahoo.com> Message-ID: Mage wrote: > praba kar wrote: > > >>Dear All, >> >> In Python what is equivalent to goto statement >> >> >> > > You shouldn't use goto in high-level languages. it would be quite useful for debuging porposes -- Best regards, Maxim Kasimov mailto: kasimov at i.com.ua From gsakkis at rutgers.edu Sat Apr 9 00:52:50 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 8 Apr 2005 21:52:50 -0700 Subject: Python Equivalent to Java Interfaces? References: Message-ID: <1113022370.851748.51160@f14g2000cwb.googlegroups.com> "Brian Kazian" wrote: > I want to insure that all subclasses implement a certain method, but could > not find anything that would do this for me. Is there anyway in Python to > implement this check? Thanks! Check out PyProtocols (http://peak.telecommunity.com/PyProtocols.html). Protocols in a way extend (no pun intended) typical interfaces by giving more flexibility to independent components to talk to each other. George From ksenia.marasanova at gmail.com Sun Apr 10 11:55:06 2005 From: ksenia.marasanova at gmail.com (Ksenia Marasanova) Date: Sun, 10 Apr 2005 17:55:06 +0200 Subject: templating system Message-ID: <130df19305041008552621549c@mail.gmail.com> Hi, I am looking for fast, simple templating system that will allow me to do the following: - embed Python code (or some templating code) in the template - generate text output (not only XML/HTML) I don't need a framework (already have it), but just simple templating. The syntax I had in mind is something like that: # in Python module def some_view(): # some code goes here... records = get_some_data() req = get_request_class() return template('some_template.tmpl', **locals()).render() # in some_template.tmpl: >From what I saw Cheetah seems to be the only one that can do it. I was hoping there might be alternatives that I've missed :) Thanks! -- Ksenia From peter at engcorp.com Fri Apr 1 12:43:20 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 01 Apr 2005 12:43:20 -0500 Subject: Pseudocode in the wikipedia In-Reply-To: <1112362451.848227.208120@z14g2000cwz.googlegroups.com> References: <1112362451.848227.208120@z14g2000cwz.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > (Further, Python has the baggage that there are no block-terminators: > i.e., no "}" or "end"s or "fi"s or "repeat"s. By adding such > terminators, we can make it a lot less ambiguous to all readers.) In > otherwords, we're basically right on track: removing the quirks of > Python, and making it higher-level. Heh heh... good joke for April 1. Clearly, calling the absence of something "baggage" is intended to be humorous... -Peter From dcrespo at gmail.com Mon Apr 25 11:56:23 2005 From: dcrespo at gmail.com (dcrespo) Date: 25 Apr 2005 08:56:23 -0700 Subject: PyGTK vs. wxPython Message-ID: <1114444582.909431.245450@f14g2000cwb.googlegroups.com> Hi all... I think wxPython is much better than PyGTK. First of all, PyGTK needs the GTK runtime installed, whereas wxPython is entirely Python's modules, so It facilitates the apps' distribution. Also, PyGTK uses specific controls or widgets of GTK, while wxPython uses native controls of the platform where the app is running. I'm learning both, but at a slow step, so I want to know all the comments about this subject in this group. I heard about Glade to make the graphic layout of the app and then export it as XML. Then, it connects to PyGTK. The problem I see is that What if you want to refer to a state of a specific radiobutton of a radobutton's group? It seems to be very troublesome. Please, post any comments about the pros and cons of each library, and the proper way to construct the graphic layout (generating XML through Glade, or by hand-code). Thanks. Daniel From aisaac0 at verizon.net Wed Apr 27 18:56:12 2005 From: aisaac0 at verizon.net (David Isaac) Date: Wed, 27 Apr 2005 22:56:12 GMT Subject: mbx repair script Message-ID: I'm looking for a Python script to repair the mbx header for a mail file where only the header is corrupted. Thanks, Alan Isaac From eucci.group at gmail.com Thu Apr 21 15:26:50 2005 From: eucci.group at gmail.com (Jeff Shell) Date: 21 Apr 2005 12:26:50 -0700 Subject: Persistent python object and the Web In-Reply-To: <1114107302.827987.230560@l41g2000cwc.googlegroups.com> References: <1114107302.827987.230560@l41g2000cwc.googlegroups.com> Message-ID: <1114111609.946834.253480@o13g2000cwo.googlegroups.com> The ZODB (Zope's object database, which can be downloaded and installed separately from Zope) and Durus (part of the Quixote family, I believe) are both high quality persistent Python object stores that are used heavily for web sites. I've never used the ZODB outside of Zope, and haven't used Durus yet. But there may be some examples written up about how to use them with mod_python. You *might* even be served by the built-in 'shelve' module. http://docs.python.org/lib/module-shelve.html From cam.ac.uk at mh391.invalid Mon Apr 25 13:54:51 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Mon, 25 Apr 2005 18:54:51 +0100 Subject: Python, Perl & PDF files In-Reply-To: References: Message-ID: Christos TZOTZIOY Georgiou wrote: > [0] there's an ancient myth about a peasant's cart getting stuck in the > mud, so the peasant starts calling out for help from goddess Athena. > Another peasant passing by tells him: "Syn Athena kai kheira kinei", > which means, more or less, "keep on calling Athena, but start also using > your hands." > I don't know any related myth of anglo-saxon origin to quote. A man prays to God, very hard for a winning lottery ticket. He tells God that he will use most of the money to do good works. Some he will use to make life better for his family. He keeps praying and praying. He never wins the lottery. One day he is so angry, he goes to church and rants and raves to God about not winning the lottery. Finally God comes and says to him "You have to buy a ticket my son, for me to help you." -- Michael Hoffman From Barron.Snyder at wholefoods.com Tue Apr 19 11:52:47 2005 From: Barron.Snyder at wholefoods.com (Barron Snyder (MW MWC)) Date: Tue, 19 Apr 2005 10:52:47 -0500 Subject: ANN: Python 2.3.2 for PalmOS available Message-ID: Isn't ** used for exponents? >>>4**2 -----Original Message----- Sent: Tuesday, April 19, 2005 10:39 AM By: RM To: python-list at python.org Subject: Re: ANN: Python 2.3.2 for PalmOS available I get odd results when trying to use exponents. For example: >>>4^2 6 -- http://mail.python.org/mailman/listinfo/python-list From peufeu at free.fr Tue Apr 12 15:10:36 2005 From: peufeu at free.fr (=?iso-8859-15?Q?Pierre-Fr=E9d=E9ric_Caillaud?=) Date: Tue, 12 Apr 2005 21:10:36 +0200 Subject: ATTN : Georges ( gry@ll.mit.edu) References: Message-ID: > My code so far: > # -*- coding: iso-8859-1 -*- > import sys > import os > from progadn import * > > ab1seq = raw_input("Entrez le r?pertoire o? sont les fichiers ? > analyser: ") or None Ce serait mieux d'utiliser sys.argv pour sp?cifier le r?pertoire dans la ligne de commande du programme : import sys help(sys.argv) > if ab1seq == None : > print "Erreur: Pas de r?pertoire! \n" \ > "\nAu revoir \n" > sys.exit() je propose : import os, os.path, sys def usage(): print "documentation..." sys.exit(-1) args = sys.argv[1:] if not args: usage() files = [] for path in args: if os.path.isfile( path ): files.append( path ) elif os.path.isdir( path ): files.extend( [os.path.join( path, fname ) for fname in os.listdir( path )] ) else: print "%s n'est ni un fichier ni un r?pertoire..." % path usage() files = [ fname for fname in files if fname.endswith( ".Seq" ) ] 88 if not files: print "Aucun fichier a traiter." usage() print "Fichier ? traiter :" print ", ".join( files ) for path in files: print path checkDNA( open( path ).read() ) > def checkDNA(seq): > """Retourne une liste des caract?res non conformes ? l'IUPAC.""" > > junk=[] > for c in range (len(seq)): > if seq[c] not in iupac: > junk.append([seq[c],c]) > #print junk > print "ATTN: Il y a le caract?re %s en position %s " % > (seq[c],c) > if junk == []: > indinv=range(len(seq)) > indinv.reverse() > resultat="" > for i in indinv: > resultat +=comp[seq[i]] > return resultat Je r??cris un peu votre fonction d'une mani?re plus "python", ? placer dans le programme avant son appel bien s?r ! def checkDNA( seq ): seq = seq.strip() if not seq: print "Fichier vide." return resultat = [] for i,c in enumerate(seq): try: resultat.append( comp[c] ) except KeyError: print "Catact?re <%s> en position <%d> invalide" % (c,i) resultat.reverse() return ''.join( resultat ) > > seq=checkDNA(seq) > > ------------------------------------------------------------------------------------------------------------------------- > > Path: > news3!feeder.news-service.com!news.glorb.com!postnews.google.com!o13g2000cwo.googlegroups.com!not-for-mail > From: gry at ll.mit.edu > Newsgroups: comp.lang.python > Subject: Re: problem with the logic of read files > Date: 12 Apr 2005 10:47:17 -0700 > Organization: http://groups.google.com > Lines: 104 2> Message-ID: <1113328037.070319.136110 at o13g2000cwo.googlegroups.com> > References: <68da8$425bf954$43461874$29054 at nf1.news-service.com> > NNTP-Posting-Host: 129.55.200.20 > Mime-Version: 1.0 > Content-Type: text/plain; charset="iso-8859-1" > Content-Transfer-Encoding: quoted-printable > X-Trace: posting.google.com 1113328069 32347 127.0.0.1 (12 Apr 2005 > 17:47:49 GMT) > X-Complaints-To: groups-abuse at google.com > NNTP-Posting-Date: Tue, 12 Apr 2005 17:47:49 +0000 (UTC) > In-Reply-To: <68da8$425bf954$43461874$29054 at nf1.news-service.com> > User-Agent: G2/0.2 > Complaints-To: groups-abuse at google.com > Injection-Info: o13g2000cwo.googlegroups.com; posting-host=129.55.200.20; > posting-account=tzIXbQwAAACT3z3X4eITVLtksgiDRxhx > Xref: news-x2.support.nl comp.lang.python:438583 > > > wrote: >> I am new to python and I am not in computer science. In fact I am a > biologist and I ma trying to learn python. So if someone can help me, I > will appreciate it. >> Thanks >> >> >> #!/cbi/prg/python/current/bin/python >> # -*- coding: iso-8859-1 -*- >> import sys >> import os >> from progadn import * >> >> ab1seq =3D raw_input("Entrez le r=E9pertoire o=F9 sont les fichiers =E0 > analyser: ") or None >> if ab1seq =3D=3D None : >> print "Erreur: Pas de r=E9pertoire! \n" >> "\nAu revoir \n" >> sys.exit() >> >> listrep =3D os.listdir(ab1seq) >> #print listrep >> >> extseq=3D[] >> >> for f in listrep: > ###### Minor -- this is better said as: if f.endswith(".Seq"): >> if f[-4:]=3D=3D".Seq": >> extseq.append(f) >> # print extseq >> >> for x in extseq: >> f =3D open(x, "r") > ###### seq=3D... discards previous data and refers only to that just > read. > ###### It would be simplest to process each file as it is read: > @@@@@@ seq=3Df.read() > @@@@@@ checkDNA(seq) >> seq=3Df.read() >> f.close() >> s=3Dseq >> >> def checkDNA(seq): >> """Retourne une liste des caract=E8res non conformes =E0 > l'IUPAC.""" >> >> junk=3D[] >> for c in range (len(seq)): >> if seq[c] not in iupac: >> junk.append([seq[c],c]) >> #print junk >> print "ATTN: Il y a le caract=E8re %s en position %s " % > (seq[c],c) >> if junk =3D=3D []: >> indinv=3Drange(len(seq)) >> indinv.reverse() >> resultat=3D"" >> for i in indinv: >> resultat +=3Dcomp[seq[i]] >> return resultat >> >> seq=3DcheckDNA(seq) >> print seq > > ##### The program segment you posted did not define "comp" or "iupac", > ##### so it's a little hard to guess how it's supposed to work. It > would > ##### be helpful if you gave a concise description of what you want the > > ##### program to do, as well as brief sample of input data. > ##### I hope this helps! -- George >> >> #I got the following ( as you see only one file is proceed by the > function even if more files is in extseq >> >> ['B1-11_win3F_B04_04.ab1.Seq'] >> ['B1-11_win3F_B04_04.ab1.Seq', 'B1-11_win3R_C04_06.ab1.Seq'] >> ['B1-11_win3F_B04_04.ab1.Seq', 'B1-11_win3R_C04_06.ab1.Seq', > 'B1-18_win3F_D04_08.ab1.Seq'] >> ['B1-11_win3F_B04_04.ab1.Seq', 'B1-11_win3R_C04_06.ab1.Seq', > 'B1-18_win3F_D04_08.ab1.Seq', 'B1-18_win3R_E04_10.ab1.Seq'] >> ['B1-11_win3F_B04_04.ab1.Seq', 'B1-11_win3R_C04_06.ab1.Seq', > 'B1-18_win3F_D04_08.ab1.Seq', 'B1-18_win3R_E04_10.ab1.Seq', > 'B1-19_win3F_F04_12.ab1.Seq'] >> .. >> ['B1-11_win3F_B04_04.ab1.Seq', 'B1-11_win3R_C04_06.ab1.Seq', > 'B1-18_win3F_D04_08.ab1.Seq', 'B1-18_win3R_E04_10.ab1.Seq', > 'B1-19_win3F_F04_12.ab1.Seq', 'B1-19_win3R_G04_14.ab1.Seq', > 'B90_win3F_H04_16.ab1.Seq', 'B90_win3R_A05_01.ab1.Seq', > 'DL2-11_win3F_H03_15.ab1.Seq', 'DL2-11_win3R_A04_02.ab1.Seq', > 'DL2-12_win3F_F03_11.ab1.Seq', 'DL2-12_win3R_G03_13.ab1.Seq', > 'M7757_win3F_B05_03.ab1.Seq', 'M7757_win3R_C05_05.ab1.Seq', > 'M7759_win3F_D05_07.ab1.Seq', 'M7759_win3R_E05_09.ab1.Seq', > 'TCR700-114_win3F_H05_15.ab1.Seq', 'TCR700-114_win3R_A06_02.ab1.Seq', > 'TRC666-100_win3F_F05_11.ab1.Seq', 'TRC666-100_win3R_G05_13.ab1.Seq'] >> >> after this listing my programs proceed only the last element of this > listing (TRC666-100_win3R_G05_13.ab1.Seq) >> >> > NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNTCCCGAAGTGTCCCAGAGCAAATAAATGGACCAAAACGTTTTTAG= > NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNTCCCGAAGTGTCCCAGAGCAAATAAATGGACCAAAACGTTTTTAG= > AATACTTGAACGTGTAATCTCATTTTAA > > > > **********End Of Post************* > > > > From rbt at athop1.ath.vt.edu Tue Apr 19 16:50:24 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Tue, 19 Apr 2005 16:50:24 -0400 Subject: Array of Chars to String In-Reply-To: References: Message-ID: James Stroud wrote: > Hello, > > I am looking for a nice way to take only those charachters from a string that > are in another string and make a new string: > > >>>>astr = "Bob Carol Ted Alice" >>>>letters = "adB" >>>>some_func(astr,letters) > > "Bad" astr = "Bob Carol Ted Alice" letters = "adB" both = [x for x in astr if x in letters] print both >>> ['B', 'a', 'd'] >>> From vegeta.z at gmail.com Tue Apr 5 11:03:17 2005 From: vegeta.z at gmail.com (vegetax) Date: Tue, 05 Apr 2005 11:03:17 -0400 Subject: Python Google Server References: <1112696434.623557.97000@g14g2000cwa.googlegroups.com> <1112706994.922193.5610@z14g2000cwz.googlegroups.com> Message-ID: Fuzzyman wrote: > Add the follwoing two lines to the start of the code : > > import urllib2 > txheaders = { 'User-agent' : 'Mozilla/4.0 (compatible; MSIE 6.0; > Windows NT 5.1; SV1; .NET CLR 1.1.4322)' } > > Then change the start of the send_head method to this : > > def send_head(self): > """Only GET implemented for this. > This sends the response code and MIME headers. > Return value is a file object, or None. > """ > print 'Request :', self.path # traceback to sys.stdout > url_tuple = urlparse.urlparse(self.path) > url = url_tuple[2] > domain = url_tuple[1] > if domain.find('.google.') != -1: # bypass the cache for > google domains > req = urllib2.Request(self.path, None, txheaders) > return urllib2.urlopen(req) Doesnt work,the browsers keeps asking me to save the page. this one works =) >> def send_head(self): print 'Request :', self.path #| traceback| to| sys.stdout url_tuple = urlparse.urlparse(self.path) url = url_tuple[2] domain = url_tuple[1] if domain.find('.google.') != -1: # bypass the cache for google domains req = urllib2.Request(self.path, None, txheaders) self.send_response(200) self.send_header("Content-type", 'text/html') self.end_headers() return urllib2.urlopen(req) >> dotloc = url.rfind('.') + 1 From leo at lspace.org Thu Apr 7 17:20:19 2005 From: leo at lspace.org (Leo Breebaart) Date: 7 Apr 2005 21:20:19 GMT Subject: How to name Exceptions that aren't Errors References: <3blfl8F6gt80jU1@individual.net> <_8-dnTyvubKUBMjfRVn-3Q@is.co.za> Message-ID: <3blmgjF6gh1egU1@individual.net> Max writes: > LOOK EVERYONE, it's Leo Breebart. You are the same Leo > Breebart, right? Breeb*aa*rt. But otherwise, yeah -- I do frequent more than just one newsgroup. :-) > This guys famous in the alternative universe of > alt.fan.pratchett. I doubt anybody here cares! Who was it that said: "On the Internet, everyone's famous to fifteen other people"...? Anyways, regardless of any feeble claims to notoriety I may have in alternate universes, here in Python country I am but a humble grasshopper wot has only been programming in Python for slightly over a year now. *Dutch* grasshopper, though. Does that help any? -- Leo Breebaart From wp at tekran.spammenziemichnichtdankeschon.com Tue Apr 5 09:29:02 2005 From: wp at tekran.spammenziemichnichtdankeschon.com (Warren Postma) Date: Tue, 05 Apr 2005 09:29:02 -0400 Subject: boring the reader to death (wasRe: Lambda: the Ultimate DesignFlaw In-Reply-To: <1112456559.835048@yasure> References: <424e8d1d$1@nntp0.pdx.net> <1112456559.835048@yasure> Message-ID: Donn Cave wrote: > > That's an odd thing to say. Poetry is verbose, florid? > Python is Dutch. Ha. I'm vaguely dutch, whatever that means. I would say if there is a sister word for "Programming" in the english language, it isn't Poetry and it surely isn't Prose. It's Dialectic. I appreciate the idea of "Code Poetry", and I find more than a few coders out there with more than a rudimentary appreciation of Poetry as well, but I don't like the analogy. No slight to Poetry is intended. Rather, I intend it as a compliment. Code has an almost entirely practical purpose, Malbol et al excluded. Poetry, except in cases of extraordinarily bad poetry, may have little "practical" purpose. Now dialectic. I like that word. And I think the art of programming is somewhere in the Late-Medeival period right now. From Merriam Webster, meanings 1,5,6 seem rather sympathetic to texts used in the creation of software: Dialectic 1. LOGIC 5. Any systematic reasoning, exposition, or argument that juxtaposes opposed or contradictory ideas and usually seeks to resolve their conflict/an intellectual exchange of ideas 6 : the dialectical tension or opposition between two interacting forces or elements One way to look at Code is as a textual abstraction of a design. Having been flattened from brain-space into a two dimension matrix of latin glyphs, certain semantic/meta-data is typically omitted. Thus a classical programming problem in many languages: The "Write-only-code" syndrom. You wrote it, it runs, but you're afraid even to touch it yourself. Python is stronger than other languages I have used. When I go back to Python code I've written long enough ago to have forgotten everything about, I am more able to pick it up and work with it than I am with other less agile languages. I'm not merely talking about pedantic details of literal code-readability, I'm talking about the ability to intuit design from implementation, and the orthogonality of the design of the system to the to the faculty of human reason. (In not so many words: Python fits my brain.) Warren From cam.ac.uk at mh391.invalid Thu Apr 28 20:44:30 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Fri, 29 Apr 2005 01:44:30 +0100 Subject: Best way to parse file into db-type layout? In-Reply-To: References: Message-ID: Peter A. Schott wrote: > I've got a file that seems to come across more like a dictionary from what I can > tell. Something like the following format: > > ###,1,val_1,2,val_2,3,val_3,5,val_5,10,val_10 > ###,1,val_1,2,val_2,3,val_3,5,val_5,11,val_11,25,val_25,967,val_967 Peter, I'm not sure exactly what you want. Perhaps a dictionary for each row in the file? Where the first row would result in: {"letter_type": "###", 1: "val_1", 2: "val_2", 3: "val_3", 5: "val_5", 10: "val_10"} Something like this: import csv import fileinput row_dicts = [] for row in csv.reader(fileinput.input()): row_dict = dict(letter_type=row[0]) for col_index in xrange(1, len(row), 2): row_dict[int(row[col_index])] = row[col_index+1] row_dicts.append(row_dict) Someone else might come up with something more elegant. -- Michael Hoffman From bokr at oz.net Mon Apr 11 01:44:11 2005 From: bokr at oz.net (Bengt Richter) Date: Mon, 11 Apr 2005 05:44:11 GMT Subject: Doubt regarding sorting functions References: Message-ID: <425a0c44.78988539@news.oz.net> On Mon, 11 Apr 2005 05:50:11 +0100 (BST), praba kar wrote: >Dear All, > > I am new to Python. I am in need of >some sorting functions (eg) numerical sorting >functions and alphapetical sorting functions. >I have searched through net But I cannot >find any regarding this so If anyone know >regarding this. Kindly mail me as early as possible > >with regards >PRabahr Frankly, your claim to has "searched through the net" is not believable, unless you are not using a search engine such as google, in which case go to google.com (assuming you know how to do that) and type in something like sorting site:python.org and press enter. The "site:python.org" will limit the search to what is available on the python.org site, which has a high concentration of Python-relevant information. Perhaps this will help someone avoid a seemingly helpless or lazy post like yours. BTW, a request to "mail me as early as possible" is more likely to get favorable consideration if you explain why you can't monitor the newsgroup postings for a reply. Regards, Bengt Richter From mahs at telcopartners.com Sun Apr 24 19:35:08 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Sun, 24 Apr 2005 16:35:08 -0700 Subject: How to "generalize" a function? In-Reply-To: <851x8zyhtl.fsf@ishmael.pequod.dyndns.org> References: <851x8zyhtl.fsf@ishmael.pequod.dyndns.org> Message-ID: Thomas K?llmann wrote: > Hi, everybody! > > I'm teaching myself Python, and I have no experience in programming > apart from some years of shell scripting. So, please bear with me. > > These two funktions are part of an administrative script I've set > myself as a first lesson, and, as you will see, they're practically the same, > except for one variable. So I'd like to weld them together -- but I > can't find out how to. > > def writeIP(ip): > """ IP schreiben """ > regex = re.compile('(.*)address(.*)') This is the only difference between the functions, isn't it? So, instead of hardwiring 'address' or 'netmask' into the regexp template, you should insert it based on an argument passed to the function. String interpolation works well here: e.g., >>> '(.*)%s(.*)' % 'netmask' '(.*)netmask(.*)' >>> > confFile = open(networkConf, 'r') > conf = confFile.readlines() > confFile.close Note, here you presumably mean confFile.close() i.e., you must supply the parens to call the function. [snip] > > I feel it should be possible to use something like > > def writeFile(ip,keyword): > ... > Indeed. Use keyword as the argument to the string interpolation >>> regex = re.compile('(.*)%s(.*)' % keyword) > but how would I construct expressions like > > netmaskLineNum = conf.index(netmaskLine) > I think these should work unchanged. But it would be easier to read if you changed these names to be neutral to the application e.g., instead of netmaskLine, foundLine HTH Michael From claird at lairds.us Tue Apr 26 20:08:03 2005 From: claird at lairds.us (Cameron Laird) Date: Wed, 27 Apr 2005 00:08:03 GMT Subject: Python, Perl & PDF files References: Message-ID: In article , rbt wrote: . . . >Read and search them for strings. If I could do that on windows, linux >and mac with the *same* bit of Python code, I'd be very happy ;) Textual content, right? Without regard to font funniness, or whether the string is in or out of a table, and so on? 'Might be a few days before I answer; I'm crashing into end-of- the-month deadlines. From martin at v.loewis.de Fri Apr 1 00:34:09 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 01 Apr 2005 07:34:09 +0200 Subject: Problem with national characters In-Reply-To: References: Message-ID: <424cdd51$0$21909$9b622d9e@news.freenet.de> Leif B. Kristensen wrote: > Is there a way around this problem? My character set in Linux is > ISO-8859-1. In Windows 2000 it should be the equivavent Latin-1, though > I'm not sure about which character set the command shell is using. You need to do locale.setlocale(locale.LC_ALL, "") to get locale-specific upper-casing. Notice that things are more difficult in the Windows terminal window, as this uses an encoding different from the one that the system's locale functions expect. Regards, Martin From bogus@does.not.exist.com Mon Apr 4 11:45:01 2005 From: bogus@does.not.exist.com () Date: Mon, 04 Apr 2005 15:45:01 -0000 Subject: (no subject) Message-ID: #! rnews 2776 Newsgroups: comp.lang.python Path: news.xs4all.nl!newsspool.news.xs4all.nl!transit.news.xs4all.nl!news-spur1.maxwell.syr.edu!news.maxwell.syr.edu!central.cox.net!east.cox.net!filt02.cox.net!peer01.cox.net!cox.net!attga1!attga2!attws2!ip.att.net!NetNews1!xyzzy!nntp From: Harry George Subject: Re: unittest vs py.test? X-Nntp-Posting-Host: cola2.ca.boeing.com Content-Type: text/plain; charset=us-ascii Message-ID: User-Agent: Gnus/5.09 (Gnus v5.9.0) Emacs/21.3 Lines: 49 Sender: hgg9140 at cola2.ca.boeing.com Organization: The Boeing Company References: <6I-dnbpiIZJNJNPfRVn-hA at powergate.ca> <6oQ3e.10378$db.6219 at trndny07> Mime-Version: 1.0 Date: Mon, 4 Apr 2005 15:30:36 GMT Xref: news.xs4all.nl comp.lang.python:370744 roy at panix.com (Roy Smith) writes: > Peter Hansen wrote: > >It seems possible to me that I might have helped him > >solely by pointing out that unittest might not be so > >"heavy" as some people claimed. I got the impression > >that he might be swayed by some unfounded claims not > >even to look further at unittest, which I felt would > >be a bad thing. > > I'm the "him" referred to above. I've been using unittest ever since > it was first added to the standard library (actually, now that I think > about it, I believe I may have been using it even before then). > > And yes, I think unittest brings along a certain amount of baggage. > There is something attractive about having the same basic framework > work in many languages (PyUnit, JUnit, C++Unit, etc), but on the other > hand, it does add ballast. I use it, I certainly don't hate it, but > on the other hand, there are enough things annoying about it that it's > worth investing the effort to explore alternatives. > > From the few days I've been playing with py.test, I think I like what > I see, but it's got other issues. The "optimization elides assert" > issue we've been talking about is one. > > It's also neat that I can write unittest-style test classes or go the > simplier route of just writing static test functions, but there's a > certain amount of TIMTOWTDI (did I spell that right?) smell to that. > > I'm also finding the very terse default output from unittest (basicly > a bunch of dots followed by "all N tests passed") highly preferable to > py.test's verbosity. > > In short, I haven't made up my mind yet, but I do appreciate the input > I've gotten. > > I haven't used pytest, so no comparisons to offer. But for unittest, I've found a lot of the "baggage" can be automated. My mkpythonproj (http://www.seanet.com/~hgg9140/comp/index.html#L006) does that. When you generate a project, you get a unittest suite with a default test ready to run, and the mechanisms needed to add more. -- harry.g.george at boeing.com 6-6M21 BCA CompArch Design Engineering Phone: (425) 294-4718 From ishpeck at gmail.com Wed Apr 27 10:05:36 2005 From: ishpeck at gmail.com (Ishpeck) Date: 27 Apr 2005 07:05:36 -0700 Subject: Which IDE is recommended? In-Reply-To: <426f90ac$1_2@rain.i-cable.com> References: <426f90ac$1_2@rain.i-cable.com> Message-ID: <1114608598.571508.6570@z14g2000cwz.googlegroups.com> monkey wrote: > Read through python site for programming tool, really plenty of choices :-) > (For c++, I just can't breath with very very limited choices) > > Tried Spe, it come with wxGlade built-in very nice(is Spe still actively > develop?). But seem that Boa Constructor and PyDev(the plug-in for Eclipse) > also worth looking. Actually which one are you guys using? and why? I think > it is also valuable for those who are new to python as me. From ndbecker2 at verizon.net Fri Apr 8 12:52:40 2005 From: ndbecker2 at verizon.net (Neal Becker) Date: Fri, 8 Apr 2005 16:52:40 +0000 (UTC) Subject: redirect stdout Message-ID: I'd like to build a module that would redirect stdout to send it to a logging module. I want to be able to use a python module that expects to print results using "print" or "sys.stdout.write()" and without modifying that module, be able to redirect it's stdout to a logger which will send the messages via datagrams to a server. Any ideas? From deetsNOSPAM at web.de Sun Apr 24 10:20:16 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Sun, 24 Apr 2005 16:20:16 +0200 Subject: Question on metaclasses References: <1114341959.796996.120840@l41g2000cwc.googlegroups.com> Message-ID: Steffen Gl?ckselig wrote: > Hello, > > I've been experimenting with metaclasses a bit (even though I am quite > a newbie to python) and stumpled over the following problem in my code: > > class Meta(type): > def __init__(cls, name, bases, dct): > for attr, value in dct.items(): > if callable(value): > dct[attr] = wrapper(value) > > wrapper adds debugging-information to methods of the class (at least > that is my plan). > > Using dct[attr] = wrapper(value) does not result in wrapped methods, > though. Using setattr(cls, attr, wrapper(value)) creates the desired > effect, though. > > Why are the changes to dct not visible in the instantiated class? Is > dct not the namespace of the class currently instantiated? You don't use metaclasses correctly I believe. Usage should look like this: class Foo(type): def __new__(cls, name, bases, dict): for k,v in [(k, v) for k,v in dict.items() if callable(v)]: cls.wrap(k,v,cls.get_directives(v), dict) return super(Foo, self).__new__(self, name, bases, dict) Notice the __new__ instead of __init__, and the call to (actually, through super) type.__new__ -- Regards, Diez B. Roggisch From ahaas at airmail.net Thu Apr 28 09:52:05 2005 From: ahaas at airmail.net (Art Haas) Date: Thu, 28 Apr 2005 08:52:05 -0500 Subject: [ANNOUNCE] Twenty-fourth release of PythonCAD now available Message-ID: <20050428135205.GS11497@artsapartment.org> I'm pleased to announce the twenty-fourth development release of PythonCAD, a CAD package for open-source software users. As the name implies, PythonCAD is written entirely in Python. The goal of this project is to create a fully scriptable drafting program that will match and eventually exceed features found in commercial CAD software. PythonCAD is released under the GNU Public License (GPL). PythonCAD requires Python 2.2 or newer. The interface is GTK 2.0 based, and uses the PyGTK module for interfacing to GTK. The design of PythonCAD is built around the idea of separating the interface from the back end as much as possible. By doing this, it is hoped that both GNOME and KDE interfaces can be added to PythonCAD through usage of the appropriate Python module. Addition of other PythonCAD interfaces will depend on the availability of a Python module for that particular interface and developer interest and action. The twenty-fourth release contains numerous improvements to the code used for constructing the user interface and the entity drawing routines. This release utilizes the GTK Action and ActionGroup classes for building and controlling the menubar and menus. Using these classes greatly simplifies and enhances the ability to manipulate the menu items, and these features are used extensively in this release. Many menu choices are now activated when the functionality they provide can be used, and deactivated when their use is not possible. More enhancements of this nature will be appearing in future releases. Another significant improvement is the refactoring of the entity drawing routines. These routines are now provided as methods for each entity class, making their usage much clearer and simpler. Changing the drawing routines has allowed significant simplification of the code responsible for drawing as well as fixing several drawing bugs. Future releases of PythonCAD will build on this change to enhance and improve the graphical behavior of the program even further. A number of PyGTK deprecation warnings that slipped by in the previous release have been removed, and a good number of bug fixes and code enhancements are present in this release as well. A mailing list for the development and use of PythonCAD is available. Visit the following page for information about subscribing and viewing the mailing list archive: http://mail.python.org/mailman/listinfo/pythoncad Visit the PythonCAD web site for more information about what PythonCAD does and aims to be: http://www.pythoncad.org/ Come and join me in developing PythonCAD into a world class drafting program! Art Haas -- Man once surrendering his reason, has no remaining guard against absurdities the most monstrous, and like a ship without rudder, is the sport of every wind. -Thomas Jefferson to James Smith, 1822 From monocalibro at yahoo.com Thu Apr 14 03:16:03 2005 From: monocalibro at yahoo.com (monocalibro) Date: Thu, 14 Apr 2005 12:16:03 +0500 Subject: need help in PySparse Message-ID: <4260bcfe@x-privat.org> Hello all! I need ready-for-use installable version of PySparse (for FiPy), because I can't compile it with MingW. Or, may be, somebody knows step-by-step instruction to complie this package under Win32 using Mingw? Best regards From steve at holdenweb.com Sat Apr 30 09:31:47 2005 From: steve at holdenweb.com (Steve Holden) Date: Sat, 30 Apr 2005 09:31:47 -0400 Subject: Can .py be complied? In-Reply-To: References: <426ec8f7_2@rain.i-cable.com> <1114696910.862093.100690@z14g2000cwz.googlegroups.com> Message-ID: John J. Lee wrote: > Steve Holden writes: > [...] > >>There's nothing wrong with open source projects catering to a market, >>and there's nothing wrong with running open source software on a >>proprietary operating system. To behave otherwise might reduce the >>growth opportunities for Python and its community. >> >>no-zealotry-please-ly y'rs - steve > > [...] > > I'm hesitant to label everybody who disagrees with you (and me) on > that a zealot. Though I tend to take the same side you do, I'm not > entirely sure it's not just laziness on my part that I think that way. > > Seems to me that holding opinions such as "it's a bad thing to support > open source software on closed source systems, and you should not do > it, for the common good" is far from crazy, even though I don't > currently happen to hold that view. > Well, we appear to agree. Please note I wasn't labelling anyone a zealot, simply implying that I didn't want the discussion to descend to blind repetitions of principle with no supporting arguments. I have no problem with others taking a different view from mine on this issue, though I reserve the right to disagree with them. My own view is that open source (Python included) wouldn't be anywhere near as advanced and popular as it is if it hadn't been ported to the majority platform, and that this actually positions it better for eventual world domination :-). There's a reason Microsoft are fighting Linux with FUD. Let's also not forget that at PyCon, (I am told) when Jim Hugunin asked for a show of hands as to who principally developed for Windows platforms, *Guido* raised his hand. regards Steve -- Steve Holden +1 703 861 4237 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ From fumanchu at amor.org Tue Apr 12 13:11:39 2005 From: fumanchu at amor.org (Robert Brewer) Date: Tue, 12 Apr 2005 10:11:39 -0700 Subject: [perl-python] Python documentation moronicities (continued) Message-ID: <3A81C87DC164034AA4E2DDFE11D258E339876F@exchange.hqamor.amorhq.net> His vitriol should at least warrant a temporary ban. No money need change hands. Top-posting-because-it-wasn't-worth-quoting, Robert Brewer MIS Amor Ministries fumanchu at amor.org > -----Original Message----- > From: python-list-bounces+fumanchu=amor.org at python.org > [mailto:python-list-bounces+fumanchu=amor.org at python.org] On > Behalf Of Richie Hindle > Sent: Tuesday, April 12, 2005 4:10 AM > To: python-list at python.org > Subject: Re: [perl-python] Python documentation moronicities > (continued) > > > > [Xah] > > motherfucking ... fucking ... fucking ... fucking ... fuck > ... fucking > > fucking ... fucking ... mother fucking ... fucking ... > piece of shit ... > > motherfucking ... fucking ... fucking ... big asshole ... > masturbation ... > > Fucking morons ... fucking stupid ... fuckhead coders ... > fuckheads ... > > you fucking asses. > > > paypal me a hundred dollars and i'll rewrite the whole re > doc in a few > > hours. > > Can we paypal you a hundred dollars to leave us alone? I'll > pledge $10. > Are there another nine people here who'll do the same? > > -- > Richie Hindle > richie at entrian.com > > -- > http://mail.python.org/mailman/listinfo/python-list > From steve at holdenweb.com Wed Apr 13 18:21:05 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 13 Apr 2005 18:21:05 -0400 Subject: smtplib does not send to all recipients In-Reply-To: <1113421803.445281.3660@l41g2000cwc.googlegroups.com> References: <1113244721.415164.81290@f14g2000cwb.googlegroups.com> <1113246181.843652.158520@o13g2000cwo.googlegroups.com> <1113421803.445281.3660@l41g2000cwc.googlegroups.com> Message-ID: <425D9B51.5080804@holdenweb.com> dccarson at gmail.com wrote: > That seems reasonable. However, using the 'mail' utility I can deliver > the same mail successfully. I assume mail is using sendmail under the > covers, which is doing the same negotiation with the same SMTP server? > The facts would appear to suggest that both sources are accepted by the local SMTP server - as long as you are positive both chains are indeed contacting the same server. Ethereal could show you this. A possible scenario would be that the downstream SMTP chain is somehow discriminating against the Python-originated messages. Logs should give evidence here. So, unless it's a simple typo and you are using different (email or SMTP server) addresses that you think are the same, see my original response, which included > and you need to take the matter up with whoever runs the SMTP server. Are you sure the address is actually valid? Evidence for and against? These things are a pain, but with patience you can usually track them down. You could try explaining to a stuffed toy, or a sock on your hand, exactly why there can't be anything wrong with your code. My wife's bears are very forbearing [n.p.i.]. Whatever it takes to break the perceptual barrier. We now return you to your regular episode of scheduled tasks ... regards Steve -- Steve Holden +1 703 861 4237 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ From rtw at freenet.co.uk Sat Apr 2 05:10:43 2005 From: rtw at freenet.co.uk (Rob Williscroft) Date: Sat, 02 Apr 2005 04:10:43 -0600 Subject: Simple thread-safe counter? References: <7x3bu9ss22.fsf_-_@ruckus.brouhaha.com> Message-ID: Tim Peters wrote in news:mailman.1223.1112417955.1799.python- list at python.org in comp.lang.python: > [Paul Rubin] >> I'd like to have a function (or other callable object) that returns >> 0, 1, 2, etc. on repeated calls. That is: >> >> print f() # prints 0 >> print f() # prints 1 >> print f() # prints 2 >> # etc. >> >> There should never be any possibility of any number getting returned >> twice, or getting skipped over, even if f is being called from >> multiple threads. >> >> What's the simplest and most natural way to do this? I can think of a >> few but am not sure that they work. And I can think of some ways that >> are sure to work, but are messier than I'd like. > > The GIL is your friend here: > Yes but IIUC the GIL is only CPython, will this work with Jython, IornPython etc ? (*) > import itertools > f = itertools.count().next > *) I'm either being rhetorical or stupid, not sure which :). Rob. -- http://www.victim-prime.dsl.pipex.com/ From nw_moriarty at yahoo.com Mon Apr 18 18:32:56 2005 From: nw_moriarty at yahoo.com (nw_moriarty at yahoo.com) Date: 18 Apr 2005 15:32:56 -0700 Subject: strange error in socket.py Message-ID: <1113863576.931976.222330@l41g2000cwc.googlegroups.com> Folks I'm getting a very strange error when I'm using the SocketServer. Has anybody got any ideas? Nigel File "/scratch1/nigel/c6/phenix-1.08a/build/intel-linux/python/lib/python2.4/SocketServer.py", line 468, in process_request_thread File "/scratch1/nigel/c6/phenix-1.08a/build/intel-linux/python/lib/python2.4/SocketServer.py", line 378, in close_request File "/scratch1/nigel/c6/phenix-1.08a/build/intel-linux/python/lib/python2.4/socket.py", line 164, in close exceptions.AttributeError: 'NoneType' object has no attribute 'write' Unhandled exception in thread started by Error in sys.excepthook: Original exception was: From davidf at sjsoft.com Wed Apr 6 14:59:11 2005 From: davidf at sjsoft.com (David Fraser) Date: Wed, 06 Apr 2005 20:59:11 +0200 Subject: Installing Python 2.4 on Linux In-Reply-To: References: Message-ID: Edward Diener wrote: > I can install Python 2.4 on the Fedora 3 Linux system, but after I do a > number of Linux utilities and commands, like yum, stop working because > they were dependent on the Python 2.3 installation. What happens is that > Python 2.4 replaces the /usr/bin/python module with the Python 2.4 > version. If I replace /usr/bin/python with the Python 2.3 version > executable, which is still on my system, that all the aforesaid modules > depend on, they start working again, but I can no longer execute > modules, like IDLE, which was part of my Python 2.4 distribution. > > What is the solution to this ? The operating system was installed with > Python 2.3 and the development libraries but no tools, doc, or > otherwise. I have installed Python 2.4 with all the RPMs and copied down > the Python 2.4 documentation to my machine ( since python24-docs.rpm > gives one very little ). I would naturally like to use Python 2.4 > without killing all the commands that depend on Python 2.3. No doubt > these commands have their modules in the site libraries for Python 2.3. > Of course I would love to update these dependencies to use Python 2.4 > but newer RPMs for these commands do not exist. > > I do not know whether this is a Python problem or a Fedora 3 problem but > I thought I would ask here first and see if anybody else had the same > problem. I imagine the problem might exist on other Linux systems. Actually the Fedora RPMS supplied on the Python website are fine: http://www.python.org/2.4.1/rpms.html Quoting from that page: > # Q) Is it safe to install these RPMs on a Red Hat system? Will they over-write the system python and cause problems with other Red Hat applications that expect a different version of Python? > # A) The RPMs that start with "python2.4" are built to not interfere with the system Python. They install as "/usr/bin/python2.4" and will not conflict with the system Python unless you are running on a system that ships the a version of Python which has the same major/minor number. > > To invoke the interpreter with these packages, you will explicitly have to run "python2.4". Note that all Python RPMs provided by Python.org and Red Hat provide a "/usr/bin/python2.4" (or similar, with major/minor number), even if they also provide "/usr/bin/python". So, yes, it should be safe. > > Note that you may need to build and install a second copy of any packages which you need access to with the supplemental version of Python. You can build packages of these files for the Python 2.4 interpreters for packages which use Distutils, by using the command "python2.4 setup.py bdist_rpm". This is by far the preferred way to install a different version of Python to the default version provided with a distribution, as you don't then conflict with packages that require the default version. Also, it is better to do it like this using real packages than to rename files manually. I have used the above successfully on Fedora Core 3 (and other similar versions on other distro versions), if it doesn't work for you there is a source RPM available to rebuild from Hope that helps David From __peter__ at web.de Fri Apr 22 11:30:21 2005 From: __peter__ at web.de (Peter Otten) Date: Fri, 22 Apr 2005 17:30:21 +0200 Subject: Problem deriving a class from the built-in file object References: Message-ID: Pierre Rouleau wrote: > I'm trying to extend the functionality of the file object by creating a > class that derives from file.??MyFile?class?re-implements?__init__(), > write(), writelines() and close() to augment the capabilities of file. > > All works fine, except for one thing:??'print?>>?myfile'??does?not > execute Myfile.write(), it executes the file.write().???If?I?execute > myfile.write() explicitly, then Myfile.write() is called as expected. As a workaround, you can use delegation instead of inheritance: >>> class File(object): ... def __init__(self, *args): ... self.file = file(*args) ... def __getattr__(self, name): ... return getattr(self.file, name) ... def write(self, s): ... print "writing", s ... self.file.write(s) ... >>> f = File("tmp.txt", "w") >>> for s in ["alpha", "beta", "gamma"]: ... print >> f, s ... writing alpha writing writing beta writing writing gamma writing >>> f.close() >>> File("tmp.txt").read() 'alpha\nbeta\ngamma\n' > I was not expecting that behaviour.??I?though?that?'print?>>?afileobject > ' would execute the afileobject.write() as you can easily obtain by > defining a simple file-like class that implements write() and writeline(). > > I am running Python 2.3.4.??Can't?move?to?2.4?yet. Nothing has changed with 2.4 in that respect. > Is it the expected behavior? I certainly didn't expect it either when I saw it for the first time. Peter From gsakkis at rutgers.edu Sat Apr 9 06:49:19 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 9 Apr 2005 03:49:19 -0700 Subject: Puzzling OO design problem References: <1113003772.020556.69550@l41g2000cwc.googlegroups.com> <1113010854.638038.173460@g14g2000cwa.googlegroups.com> <1113018015.535852.53250@z14g2000cwz.googlegroups.com> Message-ID: <1113043759.765568.9920@o13g2000cwo.googlegroups.com> "Michael Spencer" wrote: > > George, > > since you explicit allowed metaprogramming hacks :-), how about something like > this (not tested beyond what you see): > > [snipped] > Nice try, but ideally all boilerplate classes would rather be avoided (at least being written explicitly). Also, it is not obvious in your solution why and which placeholder classes have to be written (like World2.Movable) and which do not. By the way, my current working solution involves copying and pasting verbatim these classes :-) Below is an abstracted example; note that the 'declaration string' of each original class is exactly the same across all different versions after the first (e.g. "class B(PreviousNamespace.B, A)"). #====================================================== # version_1.py class Namespace: class A(object): def foo(self): return "version_1.foo()" class B(A): def bar(self): return "version_1.bar()" class C(B): def zen(self): return "version_1.zen()" #====================================================== # version_2.py from version_1 import Namespace as PreviousNamespace class Namespace(PreviousNamespace): class A(PreviousNamespace.A): def foo(self): return "version_2.foo()" class B(PreviousNamespace.B, A): pass class C(PreviousNamespace.C, B): pass #====================================================== # version_3.py from version_2 import Namespace as PreviousNamespace class Namespace(PreviousNamespace): class A(PreviousNamespace.A): pass class B(PreviousNamespace.B, A): def bar(self): return "version_3.bar()" class C(PreviousNamespace.C, B): pass #====================================================== # test.py # command: python test.py <#version> def NamespaceFactory(version): return __import__("version_%d" % version).Namespace print NamespaceFactory(2).B().foo() # "version_2.foo()" print NamespaceFactory(3).C().bar() # "version_3.bar()" import sys, inspect namespace = NamespaceFactory(int(sys.argv[1])) # print the __mro__ of each 'inner' class for name,cls in inspect.getmembers(namespace, inspect.isclass): print cls for ancestor in cls.__mro__: print "\t", ancestor #====================================================== George From gh at ghaering.de Thu Apr 21 19:36:41 2005 From: gh at ghaering.de (Gerhard Haering) Date: Fri, 22 Apr 2005 01:36:41 +0200 Subject: [ANN] pysqlite 2.0.alpha3 In-Reply-To: <20050421233432.GA15825@mylene.ghaering.de> References: <20050421233432.GA15825@mylene.ghaering.de> Message-ID: <20050421233641.GA15865@mylene.ghaering.de> On Fri, Apr 22, 2005 at 01:34:32AM +0200, Gerhard Haering wrote: > =================== > pysqlite 2.0.alpha3 > =================== > > I'm glad to announce pysqlite 2.0.alpha3, which will be the last alpha > release. Documentation and more testing will be what I'm concentrating > on in the beta test phase, so here's the explanation of the new features > within the change log. > > Download it from Sourceforge: > http://sourceforge.net/project/showfiles.php?group_id=54058 > [...] Forgot the pysqlite homepage: http://pysqlite.org/ with Wiki, BugTracker and Subversion repository. -- Gerhard -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From quasara at earthlink.net Fri Apr 29 08:20:53 2005 From: quasara at earthlink.net (sheltech) Date: Fri, 29 Apr 2005 12:20:53 GMT Subject: Ron Grossi: God is not a man References: <1114098221.580669.86300@g14g2000cwa.googlegroups.com> <1114127633.859113.292290@l41g2000cwc.googlegroups.com> <#2tJ0r3RFHA.3664@TK2MSFTNGP15.phx.gbl> <1114328806.147822.64660@z14g2000cwz.googlegroups.com> <1114329202.229148.82550@o13g2000cwo.googlegroups.com> <1114654290.690332.155200@f14g2000cwb.googlegroups.com> <3dc8hjF6s5i2uU1@individual.net> Message-ID: "MC05" wrote in message news:3dc8hjF6s5i2uU1 at individual.net... > > "Donald L McDaniel" wrote in message > news:ueXTQC8SFHA.3184 at TK2MSFTNGP15.phx.gbl... > > > > 4) I doubt seriously whether God plays a guitar, since guitars are made by > > men, for men. His Son could theoretically play a guitar. Perhaps He > > does. Perhaps He doesn't. Only the Father and His Holy Angels know. > > So then Lucifer was a wicked bass player whose sex and drugs and rock n roll > alientated the rest of the band and was fired? > > > "Fired" .... good one From __peter__ at web.de Thu Apr 28 03:05:06 2005 From: __peter__ at web.de (Peter Otten) Date: Thu, 28 Apr 2005 09:05:06 +0200 Subject: List comprehension and FieldStorage References: <1114552736.288675.248070@g14g2000cwa.googlegroups.com> <1114624635.234561.96390@o13g2000cwo.googlegroups.com> Message-ID: Derek Basch wrote: > print [(key, value) for key, value in form.keys() and form[key].value] and > bump The tutorial is always willing to make time for you :-) >>> import cgi >>> fs = cgi.FieldStorage(environ=dict(QUERY_STRING="alpha=1&beta=2")) >>> [(key, fs[key].value) for key in fs.keys()] [('alpha', '1'), ('beta', '2')] So you might have come up yourself with the above in the mean time. However, it breaks if there are multiple occurrences of the same key: >>> fs = cgi.FieldStorage(environ=dict(QUERY_STRING="alpha=1&beta=2&alpha=3")) >>> [(key, fs[key].value) for key in fs.keys()] Traceback (most recent call last): File "", line 1, in ? AttributeError: 'list' object has no attribute 'value' A quick glance in the source suggests that >>> [(mfs.name, mfs.value) for mfs in fs.list] [('alpha', '1'), ('beta', '2'), ('alpha', '3')] is a bit more robust. But perhaps you can get hold of the original unparsed query string and avoid the detour via FieldStorage altogether? Peter From codecraig at gmail.com Fri Apr 22 08:19:12 2005 From: codecraig at gmail.com (codecraig) Date: 22 Apr 2005 05:19:12 -0700 Subject: __init__.py question Message-ID: <1114172352.208471.158410@o13g2000cwo.googlegroups.com> Ok, I have the following directory structure C:\pycode --> blah.py --> mynewdir --> __init__.py --> abc.py [[ C:\pycode\mynewdir\abc.py ]] def doFoo(): print "hi" def doBar(): print "bye" [[ C:\pycode\mynewdir\__init__.py ]] from mynewdir import * [[ C:\pycode\blah.py ]] ???? what do i import in blah.py so that I can accesss, abc.doFoo() ? thanks From http Wed Apr 13 17:54:48 2005 From: http (Paul Rubin) Date: 13 Apr 2005 14:54:48 -0700 Subject: Newbie Tkinter Question References: <425d9284$0$572$ed2e19e4@ptn-nntp-reader04.plus.net> Message-ID: <7xfyxu8hqv.fsf@ruckus.brouhaha.com> "Pseud O'Nym" writes: > class App: > def __init__(self, master): > frame = Frame(master) > frame.pack(side=LEFT, fill=Y) > image1 = PhotoImage(file='button_a.gif') > self.button = Button(frame, image=image1) > self.button.pack(side=TOP) > > Can anyone enlighten me? You do have this inside a frame whose main loop is running, I hope? From jerf at jerf.org Mon Apr 4 19:26:29 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Mon, 04 Apr 2005 18:26:29 -0500 Subject: unittest vs py.test? References: <114pqf31isr8k4d@news.supernews.com> <1112372685.034751.99410@o13g2000cwo.googlegroups.com> <1I2dnUmAu5ZPSdDfRVn-rA@powergate.ca> <%Fl3e.1804$7b.990@trndny01> <_4-dnaRR8dv8dNDfRVn-tg@powergate.ca> <6I-dnbpiIZJNJNPfRVn-hA@powergate.ca> <6oQ3e.10378$db.6219@trndny07> <878y3y6ts4.fsf@pobox.com> Message-ID: On Mon, 04 Apr 2005 22:50:35 +0000, John J. Lee wrote: > What I don't understand about py.test (and trying it out seems > unlikely to answer this) is why it uses the assert statement. > unittest used to do that, too, but then it was pointed out that that > breaks when python -O is used, so unittest switched to self.assert_ > &c. Does py.test have some way around that? "Don't use -O because it doesn't do anything significant?" Is this an issue in practice? (Honest question.) If -O did something interesting I might use it, but I don't think it does. From garz at tmft.net Fri Apr 22 20:13:47 2005 From: garz at tmft.net (Markus Wintermann) Date: Sat, 23 Apr 2005 02:13:47 +0200 Subject: c-extension crashes unexpected In-Reply-To: References: Message-ID: <3cti95F6nmi80U1@news.dfncis.de> John Machin schrieb: > ... > > Some suggestions: > > 1. Try Pyrex. You get to write in a higher-level language and it does > all the boring ugly error-prone stuff for you -- this includes > reference counting as well! Look at the C code that Pyrex generates, > to see what Pyrex is saving you from. > 2. If you still insist on DIY, look at some of the Python source code > in the Modules and Objects directories to see how it is done. > 3. Examine carefully the book or whatever you have been learning from. > If it doesn't cover topics like always checking for errors, throw it > in the garbage bin (and tell the world via this newsgroup). If it does > cover such topics but you've been ignoring it, well then, it's up to > you what you do next :-) > > HTH, > John many thanks. it works now, but i?ll try to do the whole thing with pyrex. because i?m not so familiar with error handling. i tried to write this with some tutorials and there is always written something like: "i know it?s no nice style to have no errorhandling but for excercise purpose that?s not necessary." and i never know what to add. luckily now the good pyrex will do this for me, if i get it to work. From zarnovican at pobox.sk Wed Apr 6 08:39:36 2005 From: zarnovican at pobox.sk (Brano Zarnovican) Date: 6 Apr 2005 05:39:36 -0700 Subject: ignoring keywords on func. call References: <1112787673.095411.266170@o13g2000cwo.googlegroups.com> Message-ID: <1112791176.258876.200160@o13g2000cwo.googlegroups.com> > > Q: Can you call 'f' with keywords that will be > > ignored, without changing 'f's definition ? > > no. OK. Thank you for an answer. > what's the use case? I have extended the dict class, so that my __getitem__ accepts an optional parameter class MyTree(dict): def __getitem__(self, key, **k): .. def lookup(self, seq): node = self for k in seq: node = node.__getitem__(k, someoption=True) lookup takes a sequence of keys to lookup in hierarchy of Tree nodes. But I would like lookup to work also on objects that are not subclasses of Tree. It has to work on any dict-like class. If a user defines a custom class, he will intuitively define __getitem__ like this: def MyNode(??): def __getitem__(self, key): .. I could check in 'lookup' if isinstance(node, Tree): node = node.__getitem__(k, someoption=True) else: node = node.__getitem__(k) But it still doesn't guarantee that __getitem__ accepts keywords. (What if somebody will extend the Tree class and overlook the definition of __getitem__ and define a "classic" one) BranoZ From fredrik at pythonware.com Thu Apr 14 07:49:22 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 14 Apr 2005 13:49:22 +0200 Subject: Supercomputer and encryption and compression @ rate of 96% References: <1113470846.970773.4780@g14g2000cwa.googlegroups.com> <425e47a9$0$26352$db0fefd9@news.zen.co.uk> Message-ID: Will McGugan wrote: > Please implement this as a Python module. I would like to compress my mp3 collection to single > bits. here's the magic algorithm (somewhat simplified): def algorithm(data): m = 102021 # magic constant d = [int(c) for c in str(1*2*3*4*5*m+5+4+2+1)] x = [ord(c) for c in hex(1+2+4+5+m*5*4*3*2*1)] x[d[0]*d[1]*d[2]] = x[d[-1]] + sum(d) - d[d[-d[-1]-1]] + d[0] x = __import__("".join(chr(c) for c in x[d[0]*d[1]:])).encodestring return "".join(x(data).split("\n")).rstrip("="), sum(d)-sum(reversed(d)) and here's a driver for your MP3 collection: import glob def compress(filename): data = open(filename, "rb").read() keycode, bit = algorithm(data) file = open(keycode + ".out", "wb") file.write(chr(bit)) file.close() print "compressed", filename, print len(data), "=>", 1, round(100.0/len(data), 3), "%" for file in glob.glob("*.mp3"): compress(file) From peufeu at free.fr Tue Apr 12 17:54:22 2005 From: peufeu at free.fr (=?iso-8859-15?Q?Pierre-Fr=E9d=E9ric_Caillaud?=) Date: Tue, 12 Apr 2005 23:54:22 +0200 Subject: database in python ? References: <1113197530.990898.46130@z14g2000cwz.googlegroups.com> <1113216765.784331.156820@f14g2000cwb.googlegroups.com> <1113333625.215786.198580@l41g2000cwc.googlegroups.com> <1113339252.851450.184620@z14g2000cwz.googlegroups.com> Message-ID: > It's not a bug if you didn't RTFM. I did read it in much detail ! In fact I spent a lot of time trying to make understand how it could do a simple 4-table join to display also purchased products on an online store. The damn query took 0.5 seconds to execute no matter how I twisted it in and out ! Postgres did it in 0.5 milliseconds. I had to split the query in two in the application ! Speaking of the manual, the mysql manual is quite... well... i don't quite find the word, but it has many sentences which sound like PR stuff. Like, we don't do this like you or anyone would expect, but there is a reason ! Embrace our school of thought, stop worrying about integrity ! Peace, my friend, etc. And the non-working examples posted in the user comments are nice to look at, too. The organization of the manual is a mess, too, it's often quite difficult to find what I seek. The postgres manual is just wonderful. I know I'm feeding the flamewar, but I can't resist, once I came up on a post on the mysql website from a guy basically saying "wow, the fulltext is so powerful, I can search this document set in only half a second !" and then the same day, on the postgres mailinglist, there was a message from a guy who was really upset because his full text search on something like 1000 times bigger would take more than one tenth a second, and that wan't really acceptable for him, and then several competent people responded and helped him make it work. That's also why I want to use postgres. From beliavsky at aol.com Wed Apr 20 09:33:17 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 20 Apr 2005 06:33:17 -0700 Subject: Why Python does *SLICING* the way it does?? References: <1113976729.450677.261130@o13g2000cwo.googlegroups.com> <_Lm9e.23143$Xm3.17864@trndny01> Message-ID: <1114003997.778676.144950@z14g2000cwz.googlegroups.com> Terry Hancock wrote: > So I like Python's slicing because it "bites *less*" than intervals in C or Fortran. I disagree. Programming languages should not needlessly surprise people, and a newbie to Python probably expects that x[1:3] = [x[1],x[2],x[3]] . Array-oriented languages, such as Fortran 90/95, Matlab/Octave/Scilab, and S-Plus/R do not follow the Python convention, and I don't know of Fortran or R programmers who complain (don't follow Matlab enough to say). There are Python programmers, such as the OP and me, who don't like the Python convention. What languages besides Python use the Python slicing convention? Along the same lines, I think the REQUIREMENT that x[0] rather than x[1] be the first element of list x is a mistake. At least the programmer should have a choice, as in Fortran or VBA. In C starting at 0 may be justified because of the connection between array subscripting and pointer arithmetic, but Python is a higher-level language where such considerations are less relevant. From tundra at tundraware.com Thu Apr 21 05:17:28 2005 From: tundra at tundraware.com (Tim Daneliuk) Date: 21 Apr 2005 05:17:28 EDT Subject: goto statement In-Reply-To: <3cmtgvF6q13cvU1@individual.net> References: <20050420092359.81900.qmail@web8409.mail.in.yahoo.com> <3cmtgvF6q13cvU1@individual.net> Message-ID: Reinhold Birkenfeld wrote: > John Bokma wrote: > >>Mage wrote: >> >> >>>praba kar wrote: >>> >>> >>>>Dear All, >>>> >>>> In Python what is equivalent to goto statement >>>> >>>> >>>> >>> >>>You shouldn't use goto in high-level languages. >> >>Nonsense +1 > > > Thank you! > > Above all your claim is well justified. These brilliant arguments > you have put forth really explain in a magnificent way why goto is a > sane addition to any HLL. > > Reinhold OK - Here's some reasoning that may illuminate it. We could, in theory, reduce any language to the minimal Boehm & Jacopini control structures (iirc there were only four). In effect, anything beyond these is syntactic sugar. IOW, feel free to use a minimalist Turing Machine to implement your next 100,000 line program. I, on the other hand, have a really hard time finding infinite tapes (in both directions) and a suitably fast tape reader to implement such ideas. (I also seem to recall that any digital circuit can be implemented with nothing more than AND and NOT gates, but I'd rather not, thanks - I don't have enough probes on my oscilloscope to debug that kind of hardware.) Control structures/directives evolve to solve real problems. 'goto', properly used, can actually clarify code, especially when dealing with exceptions and the like. Oh, we may rename it and call it 'break' or 'try/except' or whatever suits the language author's fancy, but the concept is similar, if not identical. 'goto' certainly could be synthesized in Python with the appropriate try/except hierarchy and custom exceptions, but in many cases this would *really* be overkill - a simple 'goto' would be considerably simpler *and* probably easier to understand. Note that I am not arguing for 'goto' in Python, merely trying to respond to your point about why it is does not inherently appropriate for HLLs. Some HLLs almost have to have it by definition. I cut my teeth as programmer writing for embedded realtime systems in a HLL (PL/M). While you could, in theory, completely avoid 'goto' in a realtime environment, it would make all manner of practical programming problems kind of ugly to implement. BTW, all modern systems come complete with 'goto' implemented in *hardware* - they're called "interrupts". More to the point, I have seen some really tortured code written in the name of maintaining religious purity of some kind ("Structure", "Object Orientation",...). While language constructs can promote better- or worse code structuring, at the end of the day, programming is still the expression of human thought. Some people think clearly, some don't, and this has little to do with just what language structures are in use. Python is elegant at almost every level, and I am certainly not arguing for 'goto' in the language. But to reflexively assume that it has *no* place in a modern HLL is, I think, a bit overstated. I must now 'goto' sleep ... and I cannot think of a better way to express this... -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From http Fri Apr 22 11:48:32 2005 From: http (Paul Rubin) Date: 22 Apr 2005 08:48:32 -0700 Subject: How to run Python in Windows w/o popping a DOS box? References: <7xekd66ra3.fsf@ruckus.brouhaha.com> <4265d7b4.27743873@news.oz.net> <7xk6mvh5cn.fsf@ruckus.brouhaha.com> <42690932.237021939@news.oz.net> Message-ID: <7xk6mun773.fsf@ruckus.brouhaha.com> Wow, thanks for that very complete answer. I'll try some of those things. From lucio.torre at gmail.com Mon Apr 18 09:22:13 2005 From: lucio.torre at gmail.com (Lucio Torre) Date: 18 Apr 2005 06:22:13 -0700 Subject: ANN: Python 2.3.2 for PalmOS available References: <1113608405.558884.235890@f14g2000cwb.googlegroups.com> <1113682846.004698.182180@l41g2000cwc.googlegroups.com> Message-ID: <1113830533.234327.105980@f14g2000cwb.googlegroups.com> Most likely you run out of stack. The amount of memory this beast required for initialization was too much for most old Palms. Ive tried it on PalmOS simulator mainly, and on some version of OS5 hardware. Lucio. From mauriceling at acm.org Tue Apr 26 21:54:50 2005 From: mauriceling at acm.org (Maurice LING) Date: Wed, 27 Apr 2005 11:54:50 +1000 Subject: bytecode non-backcompatibility References: <1114418065.581779.52480@l41g2000cwc.googlegroups.com> <86wtqqm27r.fsf@guru.mired.org> <86is29n9cg.fsf@guru.mired.org> Message-ID: > The same *can* be said for some decade-old .py files. Certainly, most > everything written for 2.0 onward still works. The same will also be true > for .pyc files as long as you run them with their corresponding binary and > as long as the binary stills run. > > However, .pyc files are private, temporary caches created by a CPython > interpreter for its own use and tied to its current implementation > technology. They are not intended to be a public distribution form and > indeed cannot be a means to run Python programs on other interpreters. > Guido has stated that he want the freedom to change or even replace parts > of the internal implementation as he sees fit. (2.5 will probably get a new > compiler, with the difference mostly transparent to users.) > > One of the principles of OOP is separation of interface from > implementation. User of a class should only use the public interface and > not depend on private implementation. One reason is so implementation can > be changed even radically as long as interface is kept constant. The > Python language is interface. CPython bytecodes are implementation. > From a technical perspective, I can accept that .pyc files are private and temporary. To a certain extend, it does helps development cycle. Every time I amend my source codes, I just run it without having to consider or needing to re-compile the source files. The idea of having to release the program or library as source files does ring alarms in many executives in corporate world. Less freezing the modules (which renders it platform dependent) or using Jython (which is not possible when C extensions are involved), there is no middle grounds in CPython for distribution without source codes. Every now and then, there will be new threads in this list about people asking the means and possibilities of releasing a module/program without having to release the source code (there's another new thread on it today, "Can .py be compiled?")... > >>What I do have resources (time and energy) for is to work with the >>maintainers of PyPI to implement the package maintenance system I've >>described...... > > > Good. I agree that we need more along that line. > I've posted my idea on catelog-sig mailing list. Hope it get picked up... Cheers Maurice From sabbey at u.washington.edu Sat Apr 16 21:46:28 2005 From: sabbey at u.washington.edu (Brian Sabbey) Date: Sat, 16 Apr 2005 18:46:28 -0700 Subject: pre-PEP: Simple Thunks In-Reply-To: <4260bc72.67216001@news.oz.net> References: <4260bc72.67216001@news.oz.net> Message-ID: Bengt Richter wrote: >> Good background on thunks can be found in ref. [1]. > > UIAM most of that pre-dates decorators. What is the relation of thunks > to decorators and/or how might they interact? Hmm, I think you answered this below better than I could ;). >> def f(thunk): >> before() >> thunk() >> after() >> >> do f(): >> stuff() >> >> The above code has the same effect as: >> >> before() >> stuff() >> after() > Meaning "do" forces the body of f to be exec'd in do's local space? What if there > are assignments in f? I don't think you mean that would get executed in do's local space, > that's what the thunk call is presumably supposed to do... Yes, I see now that there is an ambiguity in this example that I did not resolve. I meant that the suite of the 'do' statement gets wrapped up as an anonymous function. This function gets passed to 'f' and can be used by 'f' in the same way as any other function. Bindings created in 'f' are not visible from the 'do' statement's suite, and vice-versa. That would be quite trickier than I intended. >> Other arguments to 'f' get placed after the thunk: >> >> def f(thunk, a, b): >> # a == 27, b == 28 >> before() >> thunk() >> after() >> >> do f(27, 28): >> stuff() > I'm not sure how you intend this to work. Above you implied (ISTM ;-) > that the entire body of f would effectively be executed locally. But is that > true? What if after after() in f, there were a last statment hi='from last statement of f' > Would hi be bound at this point in the flow (i.e., after d f(27, 28): stuff() )? I didn't mean to imply that. The body of 'f' isn't executed any differently if it were called as one normally calls a function. All of its bindings are separate from the bindings in the 'do' statement's scope. > I'm thinking you didn't really mean that. IOW, by magic at the time of calling thunk from the > ordinary function f, thunk would be discovered to be what I call an executable suite, whose > body is the suite of your do statement. yes > In that case, f iself should not be a callable suite, since its body is _not_ supposed to be called locally, > and other than the fact that before and after got called, it was not quite exact to say it was _equivalent_ to > > before() > stuff() # the do suite > after() yes, I said "same effect as" instead of "equivalent" so that too much wouldn't be read from that example. I see now that I should have been more clear. > In that case, my version would just not have a do, instead defining the do suite > as a temp executable suite, e.g., if instead > > > we make an asignment in the suite, to make it clear it's not just a calling thing, e.g., > > do f(27, 28): > x = stuff() > > then my version with explict name callable suite would be > > def f(thunk, a, b): > # a == 27, b == 28 > before() > thunk() > after() > > set_x(): > x = stuff() # to make it plain it's not just a calling thing > > f(set_x, 27, 28) > # x is now visible here as local binding > > but a suitable decorator and an anonymous callable suite (thunk defined my way ;-) would make this > > @f(27, 28) > (): x = stuff() > Hmm, but this would require decorators to behave differently than they do now. Currently, decorators do not automatically insert the decorated function into the argument list. They require you to define 'f' as: def f(a, b): def inner(thunk): before() thunk() after() return inner Having to write this type of code every time I want an thunk-accepting function that takes other arguments would be pretty annoying to me. >> >> Thunks can also accept arguments: >> >> def f(thunk): >> thunk(6,7) >> >> do x,y in f(): >> # x==6, y==7 >> stuff(x,y) > > IMO > @f > (x, y): stuff(x, y) # like def foo(x, y): stuff(x, y) > > is clearer, once you get used to the missing def foo format > OK. I prefer a new keyword because it seems confusing to me to re-use decorators for this purpose. But I see your point that decorators can be used this way if one allows anonymous functions as you describe, and if one allows decorators to handle the case in which the function being decorated is anonymous. >> >> The return value can be captured >> > This is just a fallout of f's being an ordinary function right? > IOW, f doesn't really know thunk is not an ordinary callable too? > I imagine that is for the CALL_FUNCTION byte code implementation to discover? yes > >> def f(thunk): >> thunk() >> return 8 >> >> do t=f(): >> # t not bound yet >> stuff() >> >> print t >> ==> 8 > That can't be done very well with a decorator, but you could pass an > explicit named callable suite, e.g., > > thunk(): stuff() > t = f(thunk) But not having to do it that way was most of the purpose of thunks. >> >> Thunks blend into their environment > ISTM this needs earlier emphasis ;-) > >> >> def f(thunk): >> thunk(6,7) >> >> a = 20 >> do x,y in f(): >> a = 54 >> print a,x,y >> >> ==> 54,6,7 > > IMO that's more readable as > > def f(thunk): > thunk(6, 7) > @f > (x, y): # think def foo(x, y): with "def foo" missing to make it a thunk > a = 54 > print a,x,y > > IMO we need some real use cases, or we'll never be able to decide what's really useful. >> >> Thunks can return values. Since using 'return' would leave it unclear >> whether it is the thunk or the surrounding function that is returning, a >> different keyword should be used. By analogy with 'for' and 'while' loops, >> the 'continue' keyword is used for this purpose: > Gak ;-/ >> >> def f(thunk): >> before() >> t = thunk() >> # t == 11 >> after() >> >> do f(): >> continue 11 > > I wouldn't think return would be a problem if the compiler generated a > RETURN_CS_VALUE instead of RETURN_VALUE when it saw the end of > the callable suite (hence _CS_) (or thunk ;-) > Then it's up to f what to do with the result. It might pass it to after() sometimes. It wouldn't be a problem to use 'return' instead of 'continue' if people so desired, but I find 'return' more confusing because a 'return' in 'for' suites returns from the function, not from the suite. That is, having 'return' mean different things in these two pieces of code would be confusing: for i in [1,2]: return 10 do i in each([1,2]): return 10 > >> >> Exceptions raised in the thunk pass through the thunk's caller's frame >> before returning to the frame in which the thunk is defined: > But it should be possible to have try/excepts within the thunk, IWT? yes, it is possible and they are allowed in the example implementation. >> >> def catch_everything(thunk): >> try: >> thunk() >> except: >> pass # SomeException gets caught here >> >> try: >> do catch_everything(): >> raise SomeException >> except: >> pass # SomeException doesn't get caught here because it was >> already caught >> >> Because thunks blend into their environment, a thunk cannot be used after >> its surrounding 'do' statement has finished: >> >> thunk_saver = None >> def f(thunk): >> global thunk_saver >> thunk_saver = thunk >> >> do f(): >> pass >> >> thunk_saver() # exception, thunk has expired > Why? IWT the above line would be equivalent to executing the suite (pass) in its place. The restriction on saving thunks for later is for performance reasons and because I believe it is hacky to use thunks in that way. > What happens if you defined > > def f(thunk): > def inner(it): > it() > inner(thunk) > > do f(): > x = 123 > > Of course, I'd spell it > @f > (): x = 123 > > Is there a rule against that (passing thunk on to inner)? No, that is fine, as long as execution has not yet left the 'do' statement. >> 'break' and 'return' should probably not be allowed in thunks. One could >> use exceptions to simulate these, but it would be surprising to have >> exceptions occur in what would otherwise be a non-exceptional situation. >> One would have to use try/finally blocks in all code that calls thunks >> just to deal with normal situations. For example, using code like >> >> def f(thunk): >> thunk() >> prevent_core_meltdown() >> >> with code like >> >> do f(): >> p = 1 >> return p >> >> would have a different effect than using it with >> >> do f(): >> return 1 >> >> This behavior is potentially a cause of bugs since these two examples >> might seem identical at first glance. > I think less so with decorator and anonymous callable suite format > > @f > (): return 1 # as in def foo(): return 1 -- mnemonically removing "def foo" > In your syntax, 'return' would return from the thunk. With the 'do' syntax, 'return' would return from the surrounding function. So the issue does not arise with your syntax. >> >> The thunk evaluates in the same frame as the function in which it was >> defined. This frame is accessible: >> >> def f(thunk): >> frame = thunk.tk_frame > # no connection with tkinter, right? Maybe thunk._frame would also say be careful ;-) > assert sys._getframe(1) is frame # ?? when does that fail, if it can? 'tk' is supposed to remind one of 'thunk'. I believe that follows a standard naming convention in python (e.g. see generators). I don't see how that assert can fail. I see what you're getting at with decorators and anonymous functions, but there are a couple of things that, to me, make it worth coming up with a whole new syntax. First, I don't like how one does not get the thunk inserted automatically into the argument list of the decorator, as I described above. Also, I don't like how the return value of the decorator cannot be captured (and is already used for another purpose). The fact that decorators require one more line of code is also a little bothersome. Decorators weren't intended to be used this way, so it seems somewhat hacky to do so. Why not a new syntax? -Brian From sunnan at handgranat.org Sat Apr 2 06:35:17 2005 From: sunnan at handgranat.org (Sunnan) Date: Sat, 02 Apr 2005 11:35:17 GMT Subject: boring the reader to death (wasRe: Lambda: the Ultimate Design Flaw In-Reply-To: References: Message-ID: Tim Peters wrote: > [Aahz] > >>>"The joy of coding Python should be in seeing short, concise, readable >>>classes that express a lot of action in a small amount of clear code -- >>>not in reams of trivial code that bores the reader to death." --GvR > > > [Sunnan] > >>Can anyone please point me to the text that quote was taken from? I >>tried to use a search engine but I only found quotations, not the source. > > > That's because it was originally in email to a company-internal > mailing list. If you're willing to move to Fredericksburg, VA and > work for Zope Corp, perhaps they'll let you in to the PythonLabs list > archives. Fair warning: I work for Zope Corp, and I'm not sure I can > get into those archives. So don't switch jobs _just_ for that. It's just that I'm having a hard time matching that quote to what I though python was about. I thought boring code was considered a virtue in python. ("Explicit is better than implicit", "sparse is better than dense".) Because what is "boring"? The opposite of dense, tense, intense. Utterly predictable; it's like the combination of all my prejudices. Even before I knew, I thought "Bet Python separates statements from expressions". Sunnan PS. (People easily offended can substitute "boring" for "readable" in the above text.) From llothar at web.de Mon Apr 18 21:52:46 2005 From: llothar at web.de (Lothar Scholz) Date: 18 Apr 2005 18:52:46 -0700 Subject: Can't compile with --enable-shared on MacOSX References: <6ee58e07.0504180620.4b157ebf@posting.google.com> <4263d20e$0$149$e4fe514c@news.xs4all.nl> Message-ID: <6ee58e07.0504181752.c83afcf@posting.google.com> Maarten Sneep wrote in message news:<4263d20e$0$149$e4fe514c at news.xs4all.nl>... > On Mac OS X the shared library functionality is obtained through > frameworks. It may detect this by default, but I'm not sure about Not good. I don't want frameworks. I must embedd python into my application. Setting up a framework and installing/maintaining it is much more work especially when i'm already doing my own maintainance for the Linux/Windows port. No ther way then stealing the dylib from the framework directory ? From jepler at unpythonic.net Fri Apr 1 08:07:01 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Fri, 1 Apr 2005 07:07:01 -0600 Subject: Spider - path conflict [../test.htm,www.nic.nl/index.html] In-Reply-To: <1112357294.881735.287370@o13g2000cwo.googlegroups.com> References: <1112357294.881735.287370@o13g2000cwo.googlegroups.com> Message-ID: <20050401130658.GA22184@unpythonic.net> I think you want urllib.basejoin(). >>> urllib.basejoin("http://www.example.com/test/page.html", "otherpage.html") 'http://www.example.com/test/otherpage.html' -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From kay.schluehr at gmx.net Tue Apr 19 03:16:32 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 19 Apr 2005 00:16:32 -0700 Subject: pre-PEP: Suite-Based Keywords - syntax proposal In-Reply-To: <42634e5c.235641494@news.oz.net> References: <1113720183.913168.184770@f14g2000cwb.googlegroups.com> <42621c83.157344138@news.oz.net> <1113755254.226237.138550@z14g2000cwz.googlegroups.com> <4262e25b.207992156@news.oz.net> <1113799727.299053.138010@f14g2000cwb.googlegroups.com> <42634e5c.235641494@news.oz.net> Message-ID: <1113894992.556496.73510@f14g2000cwb.googlegroups.com> Bengt Richter wrote: [...] > Um, I think that's too narrow for where. Consider > > foo = f1; bar=f2; x=k1; y=k2 > foo(x)*bar(y)[3].attr > > now should > > foo(x)*bar(y)[3].attr where: > foo = f1; bar=f2; x=k1; y=k2 I think we are diverging again. You are right with Your objection about my claim of generality but I'm completely against the latter statement not only because foo(x) where: foo = f1 is not much better than foo(x) where: def foo(): # do some stuff which should clearly raise an exception and be abandoned. After all I start backtracking: the purpose of defining suites is still prevention of namespaces pollution with helper-functions not a sake of it's own and not inventing of a suite-based programming style for everything. The examples You presented have become almost pathological examples of what should be prevented and where syntax cannot be rigid enough. So there are following requierements about we seem to agree: - define suites on a functions-call scope in order to define helper functions that would otherwise pollute external namespaces - mark the func-call-scope by some keyword either "with" or "where" because it has to be separated from the calling environment both for consistency and user friendlyness - Simple matching rules for both keyword-parameters and argument-tuples. Make explicit which kind of inference rule is selected. I think that my last proposal I finally distilled from our discussion would pretty much fullfill all three requirements whereas that of Andrey Tatarinov would be somewhat more restrictive and fullfills only the first two. Ciao, Kay From tiissa at nonfree.fr Sat Apr 23 06:20:39 2005 From: tiissa at nonfree.fr (tiissa) Date: Sat, 23 Apr 2005 12:20:39 +0200 Subject: a=[ lambda t: t**n for n in range(4) ] In-Reply-To: <1114215456.258241.194840@l41g2000cwc.googlegroups.com> References: <1114206105.666055.33720@g14g2000cwa.googlegroups.com> <1114215456.258241.194840@l41g2000cwc.googlegroups.com> Message-ID: <426a2177$0$19274$636a15ce@news.free.fr> mehmetmutigozel at gmail.com wrote: > i wonder if there is an automatic way to make that without calling a > function. You mean without _explicitely_ calling a function. May I inquire why you need to write f instead of f(x)? > an automatic way that depends on changing the value of x. as each time > x=something used the whole matrix changes automaticly. As pointed out by El Pitonero property can be your friend: >>> class A(object): ... def get_v(self): ... return [1,x] ... v=property(get_v) ... >>> a=A() >>> x=0 >>> a.v [1, 0] >>> x=2 >>> a.v [1, 2] >>> However, you will calculate your matrix each time you will access it (and I find it ugly to use a global variable this way). You can however build it the other way round: >>> class B(object): ... def __init__(self): ... self.v=[1,0] ... self.x=0 ... def calc_v(self): ... self.v[1]=self.__x ... def set_x(self,x): ... self.__x=x ... self.calc_v() ... def get_x(self): ... return self.__x ... x=property(get_x, set_x) ... >>> b=B() >>> b.v [1, 0] >>> b.x=2 >>> b.v [1, 2] >>> This time, calculations only occur when you change the value of x. From xnews2 at fredp.lautre.net Mon Apr 11 09:26:54 2005 From: xnews2 at fredp.lautre.net (Fred Pacquier) Date: 11 Apr 2005 13:26:54 GMT Subject: database in python ? References: <1113197530.990898.46130@z14g2000cwz.googlegroups.com> Message-ID: "ajikoe at gmail.com" said : > Hello I need to build table which need searching data which needs more > power then dictionary or list in python, can anyone help me what kind > of database suitable for python light and easy to learn. Is mySQL a > nice start with python ? There are a number of separate database engines with a python interface, as others in the thread have shown. However, if you mostly work with one table at a time, as you seem to imply, then you might have a look a Kirbybase : it's a single python module, and databases don't come any lighter or easier than that :) -- YAFAP : http://www.multimania.com/fredp/ From roy at panix.com Fri Apr 29 18:12:58 2005 From: roy at panix.com (Roy Smith) Date: Fri, 29 Apr 2005 18:12:58 -0400 Subject: Sorting an Edge List References: Message-ID: In article , "Anthony D'Agostino" wrote: > I need to sort this list: > [('A','Y'), ('J','A'), ('Y','J')] like this: > [('A','Y'), ('Y','J'), ('J','A')]. > > Note how the Ys and Js are together. All I need is for the second element of > one tuple to equal the first element of the next tuple. Another valid > solution is [('J','A'), ('A','Y'), ('Y','J')]. This is an interesting problem. Can you give us more details? I'm assuming the length of the list can be any arbitrary length. Will there always only be three letters? Can there ever be a pair with the same first and second elements, i.e. ('A', 'A')? Will there always be a valid solution? For example, it's trivial to show that [('A', 'Y'), ('A', 'J'), ('J', 'A')] cannot be sorted using your criteria (there's no pair starting with 'Y' to match the one that ends with 'Y') Is this a real-life problem, or are we doing your homework for you? :-) From mage at mage.hu Sat Apr 23 03:43:52 2005 From: mage at mage.hu (Mage) Date: Sat, 23 Apr 2005 09:43:52 +0200 Subject: a=[ lambda t: t**n for n in range(4) ] In-Reply-To: <42698692$1@nntp0.pdx.net> References: <1114206105.666055.33720@g14g2000cwa.googlegroups.com> <1114208333.622909.179640@l41g2000cwc.googlegroups.com> <42698692$1@nntp0.pdx.net> Message-ID: <4269FCB8.5010402@mage.hu> Scott David Daniels wrote: > > > See, the body of your anonymous function just looks for "the current > value of n" when it is _invoked_, not when it is _defined_. The "lambda functions" was an unclear part of the tutorial I read. Should I use them? Are they pythonic? As far I see they are good only for type less a bit. Mage From swaroopch at gmail.com Sat Apr 2 07:12:01 2005 From: swaroopch at gmail.com (Swaroop C H) Date: Sat, 2 Apr 2005 17:42:01 +0530 Subject: pagecrawling websites with Python In-Reply-To: <1112385491.601719.67420@o13g2000cwo.googlegroups.com> References: <1112385491.601719.67420@o13g2000cwo.googlegroups.com> Message-ID: <351e887105040204123ff58c0@mail.gmail.com> On 1 Apr 2005 11:58:11 -0800, writeson wrote: > We've got an application we wrote in Python called pagecrawler that > Does anyone have any insight if this is a reasonable approach to build web pages, > or if we should look at another design? I don't have an answer to your particular question, but maybe you can have a look at how the HarvestMan works: http://freshmeat.net/projects/harvestman Regards, -- Swaroop C H Blog: http://www.swaroopch.info Book: http://www.byteofpython.info From rkern at ucsd.edu Mon Apr 11 16:23:01 2005 From: rkern at ucsd.edu (Robert Kern) Date: Mon, 11 Apr 2005 13:23:01 -0700 Subject: Thoughts on some stdlib modules In-Reply-To: References: <4257BE8B.9080209@v.loewis.de><1113120099.217977.192190@g14g2000cwa.googlegroups.com> <4258e5e6$0$3407$9b622d9e@news.freenet.de> <425999BD.7050308@v.loewis.de> Message-ID: Fredrik Lundh wrote: > Robert Kern wrote: > > >>Agreed, which is why I think that proper package management and a CPyAN-type system is the way to >>go, not trying to stuff everything into a single distribution. > > > I think we're looking at this in two different ways: you're looking at it from the "sumo > python distribution" perspective, I'm trying to find a middle ground between a sumo > distribution and today's put-it-in-our-repository-or-else approach. Okay, then we may be advocating the same thing, and I'm misinterpreting your comments. Wouldn't be the first time. > (I have more comments to your comments, but they have to wait until later) I look forward to them. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From bj_666 at gmx.net Sat Apr 2 15:42:35 2005 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sat, 02 Apr 2005 22:42:35 +0200 Subject: Performance issue References: Message-ID: In , Tom Carrick wrote: > In my attempted learning of python, I've decided to recode an old > anagram solving program I made in C++. The C++ version runs in less > than a second, while the python takes 30 seconds. I'm not willing to > think it's just python being slow, so I was hoping someone could find > a faster way of doing this. Also, I was wondering if there was a more > builtin, or just nicer way of converting a string to a list (or using > the sort function on a list) than making a function for it. > > The words.txt here is just a copy of FreeBSD's /usr/share/dict/words Here's my attempt which builds an anagram dictionary ("sorted word" -> list of anagrams) for fast lookup of anagrams:: #!/usr/bin/env python2.4 from itertools import imap, ifilter WORDS = '/usr/share/dict/words' def make_anagram_map(words): anagram_map = dict() for word in imap(lambda w: w.strip().lower(), words): sorted_word = ''.join(sorted(list(word))) anagram_map.setdefault(sorted_word, list()).append(word) return dict(ifilter(lambda x: len(x[1]) > 1, anagram_map.iteritems())) def main(): words_file = open(WORDS, 'r') anagram_map = make_anagram_map(words_file) words_file.close() while True: word = raw_input('Find anagrams of word (just enter to end): ') if not word: break try: print anagram_map[''.join(sorted(list(word.strip().lower())))] except KeyError: print 'No anagrams found for %r' % word # # Print all anagrams sorted by number of anagrams. # print '\n'.join(map(str, sorted(anagram_map.values(), key=len))) # print len(anagram_map) if __name__ == '__main__': main() Ciao, Marc 'BlackJack' Rintsch From surrender_it at remove-yahoo.it Thu Apr 28 19:35:33 2005 From: surrender_it at remove-yahoo.it (gabriele renzi) Date: Thu, 28 Apr 2005 23:35:33 GMT Subject: anonymous function objects? In-Reply-To: References: <7x7jimlfnj.fsf@ruckus.brouhaha.com> Message-ID: <9rece.70309$IN.1217267@twister2.libero.it> Uwe Mayer ha scritto: > Friday 29 April 2005 00:06 am Paul Rubin wrote: > >>Closest you can come is: >> >> f = lambda: sys.stdout.write("hello world\n") > > > Ah. :)) > Why does the "print" statement return a syntax error here? > ^^^^^^^^^ > this is the reason :) You can't have statements into an expression From robin at reportlab.com Mon Apr 25 10:50:31 2005 From: robin at reportlab.com (Robin Becker) Date: Mon, 25 Apr 2005 15:50:31 +0100 Subject: Python, Perl & PDF files In-Reply-To: References: Message-ID: <426D03B7.1020400@chamonix.reportlab.co.uk> rbt wrote: ...... > > I just want to read PDF files in a portable way (windows, linux, mac) > from within Python. > ...... I suppose you mean extract PDF pages and do something with them. http://www.reportlab.com does have a tool that handles that in Python. It's not free though. There are indeed a number of perl modules which do that and other modules which allow you to overprint etc etc. You can always hand translate one of the extract perl modules. They don't seem that hard. Alternatively put a good case to andy at reportlab.com. -- Robin Becker From python at rcn.com Tue Apr 12 08:03:50 2005 From: python at rcn.com (Raymond Hettinger) Date: Tue, 12 Apr 2005 08:03:50 -0400 Subject: [Python-Dev] args attribute of Exception objects In-Reply-To: Message-ID: <000001c53f57$b0fe7d20$c2bd2c81@oemcomputer> [S?bastien de Menten] > 2) Could this be changed to .args more in line with: > a) first example: e.args = ('foo', "NameError: name 'foo' is not > defined") > b) second example: e.args = (4, 'foo', "'int' object has no attribute > 'foo'",) > the message of the string can even be retrieved with str(e) so it is > also > redundant. Something like this ought to be explored at some point. It would certainly improve the exception API to be able to get references to the objects without parsing strings. The balancing forces are backwards compatibility and a need to keep the exception mechanism as lightweight as possible. Please log a feature request on SF. Note that the idea is only for making builtin exceptions more informative. User defined exceptions can already attach arbitrary objects: >>> class Boom(Exception): pass >>> x = 10 >>> if x != 5: raise Boom("Value must be a five", x) Traceback (most recent call last): File "", line 2, in -toplevel- raise Boom("Value must be a five", x) Boom: ('Value must be a five', 10) Raymond Hettinger From littlejohn.75 at news.free.fr Fri Apr 1 18:06:35 2005 From: littlejohn.75 at news.free.fr (F. Petitjean) Date: 01 Apr 2005 23:06:35 GMT Subject: that is it is not it (logic in Python) References: <424d0be1$0$2882$626a14ce@news.free.fr> <424dc4b4$0$18707$636a15ce@news.free.fr> Message-ID: <424dd3fb$0$19147$636a15ce@news.free.fr> Le Fri, 01 Apr 2005 17:42:30 -0500, Jeremy Bowers a ?crit : > On Fri, 01 Apr 2005 22:01:25 +0000, F. Petitjean wrote: > >> Le Fri, 1 Apr 2005 13:39:47 -0500, Terry Reedy a ?crit : >>> This is equivalent to '(that is it) and (it is not it)' which is clearly >>> false. >>> >>>> False # What ? >>> >>> Reread the ref manual on chained comparison operators. >> >> And see the date of the post :-) >> that is it isn't it ? > > Nope, nothing to do with it. Read the ref manual on chained comparision > operators. > > http://www.python.org/doc/2.4/ref/comparisons.html#l2h-430 > > For proof, run the given code in the original post. It's not faked in the > slightest, and the manual holds the key to understanding. *I* wrote the original post. and am pretty sure it is not faked. And I run it before posting to be sure not to say anything wrong. it is a kind of relief to learn that computers in 2005 (even Python powered) are humor-impaired and follow the ? ref manual ? every time even on first April. >>> There = True >>> Python = map(bool, range(5)) >>> logic = True >>> There is logic in Python True # naturally From dbasch at yahoo.com Sun Apr 10 15:45:20 2005 From: dbasch at yahoo.com (Derek Basch) Date: 10 Apr 2005 12:45:20 -0700 Subject: Counting iterations In-Reply-To: References: <1112994185.983954.234650@l41g2000cwc.googlegroups.com> <4256f4c0$0$2603$da0feed9@news.zen.co.uk> <1112998861.316958.152060@g14g2000cwa.googlegroups.com> <1113064744.144787.315120@o13g2000cwo.googlegroups.com> Message-ID: <1113162320.578460.95300@g14g2000cwa.googlegroups.com> Interesting stuff Andrew. I do generally avoid string concantination for the reason listed in the Python Performance Tips but your analysis kinda puts that in question. Such a dense discussion for me just trying to find the enumerate() function :). I guess that is why the python list is so great. You guys always rip my code apart and correct my style. Even if it is just a stupid one off example. Thanks everyone, Derek Basch From mahs at telcopartners.com Sat Apr 23 19:43:21 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Sat, 23 Apr 2005 16:43:21 -0700 Subject: Handling lists In-Reply-To: <1114285850.091749.188680@f14g2000cwb.googlegroups.com> References: <1114285850.091749.188680@f14g2000cwb.googlegroups.com> Message-ID: superprad at gmail.com wrote: ... > list = [[10,11,12,13,14,78,79,80,81,300,301,308]] > how do I convert it so that I arrange them into bins . > so If i hvae a set of consecutive numbers i would like to represent > them as a range in the list with max and min val of the range alone. > I shd get something like > list = [[10,14],[78,81],[300,308]] > Mage: > Maybe: > > list = [10,11,12,13,14,78,79,80,81,300,301,308] > > new_list = [] > start = 0 > for i in range(1,len(list) + 1): > if i == len(list) or list[i] - list[i-1] <> 1: > new_list.append([list[start],list[i-1]]) > start = i > > print new_list superprad at gmail.com wrote: > yes that makes sense.But the problem I am facing is if list= > [300,301,303,305] I want to consider it as one cluster and include the > range as [300,305] so this is where I am missing the ranges. > so If the list has l = [300,301,302,308,401,402,403,408] i want to > include it as [[300,308],[401,408]]. Mage's solution meets the requirements that you initially stated of treating *consecutive* numbers as a group. Now you also want to consider [300,301,303,305] as a cluster. You need to specify your desired clustering rule, or alternatively specify ho many bins you want to create, but as an example, here is a naive approach, that could be adapted easily to other clustering rules and (a bit less easily) to target a certain number of bins def lstcluster(lst): # Separate neighbors that differ by more than the mean difference lst.sort() diffs = [(b-a, (a, b)) for a, b in zip(lst,lst[1:])] mean_diff = sum(diff[0] for diff in diffs)/len(diffs) breaks = [breaks for diff, breaks in diffs if diff > mean_diff] groups = [lst[0]] + [i for x in breaks for i in x] + [lst[-1]] igroups = iter(groups) # Pairing mechanism due to James Stroud return [[i, igroups.next()] for i in igroups] Note this is quite inefficient due to creating several intermediate lists. But it's not worth optimizing yet, since I'm only guessing at your actual requirement. lst0 = [10,11,12,13,14,78,79,80,81,300,301,308] lst1 = [10,12,16,24,26,27,54,55,80,100, 105] lst3 = [1,5,100,1000,1005,1009,10000, 10010,10019] >>> lst0 = [10,11,12,13,14,78,79,80,81,300,301,308] >>> lst1 = [10,12,16,24,26,27,54,55,80,100, 105] >>> lst2 = [1,5,100,1000,1005,1009,10000, 10010,10019] >>> lstcluster(lst0) [[10, 14], [78, 81], [300, 308]] >>> lstcluster(lst1) [[10, 27], [54, 55], [80, 80], [100, 105]] >>> lstcluster(lst2) [[1, 1009], [10000, 10019]] >>> Michael From peter at engcorp.com Fri Apr 22 18:21:00 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 22 Apr 2005 18:21:00 -0400 Subject: Python licence again In-Reply-To: <42697785$0$2594$da0feed9@news.zen.co.uk> References: <1114197761.019100.38890@o13g2000cwo.googlegroups.com> <87fyxilehj.fsf@pobox.com> <42697785$0$2594$da0feed9@news.zen.co.uk> Message-ID: Will McGugan wrote: > Peter Hansen wrote: >> How *do* you pronounce it? "Thurrow" seems to match >> how I say the word, along with everyone else I've >> ever met (until now?). > > I would pronounce it like 'thurra', since I'm Scottish. It always makes > me cringe when Americans pronounce 'Edinburgh' as 'edin-burrow' rather > then 'edin-burra'. And I would pronounce it as just "edin-burr"... I've heard the (as you call it) American pronunciation before, but never the, uh, real one, which you use. :-) > I love how this newsgroup can digress so quickly.. ;) It does do that, doesn't it? And all on its own, too! ;-) -Peter From duncan.booth at invalid.invalid Fri Apr 15 10:55:27 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 15 Apr 2005 14:55:27 GMT Subject: sort of a beginner question about globals References: <1113354531.380490.81190@z14g2000cwz.googlegroups.com> <3aOdnX8D67t5PcHfRVn-qQ@comcast.com> <1113403451.556360.116630@f14g2000cwb.googlegroups.com> <1113405724.301516.232000@f14g2000cwb.googlegroups.com> <6v-dnV7CJ7WZocDfRVn-oA@comcast.com> <1113422470.180010.172970@z14g2000cwz.googlegroups.com> <1113434483.437663.206030@f14g2000cwb.googlegroups.com> <1113481607.615479.72920@g14g2000cwa.googlegroups.com> <1113573592.248241.38550@z14g2000cwz.googlegroups.com> Message-ID: fred.dixon wrote: >:) unit test is something on my to-learn list. seems involved and i > haven't seen any straight forward tutorials yet. as yet i still > consider myself a hobbyist at best. > Hmm, I believe you are right. I can't see any straight-forward tutorials which use Python. I found a tutorial at onlamp.com, but it doesn't seem to me to explain TDD at all clearly. Kent Beck's book is pretty good except that the main tutorial is in Java rather than Python, and the Python section tells you how to write a new unit test harness (using TDD). So it won't tell you how to use the unittest module, but if you use the Python documentation for that (library reference, chapter 5.3) you should be able to follow the Java tutorial converting it into Python as you go. (Likewise, I've worked through the Python chapter converting that into another language when there wasn't a suitable xUnit harness available). It is one of those things that, once you get the hang of it, really grows on you: for me the turning point was the first time I added some code and a completely unrelated test which had been working fine up until that point, and which could not possibly be affected by the latest change, suddenly broke. At that point I realised I had just saved myself considerable debugging time as without the tests I wouldn't have realised I had introduced a problem until much later. From radam2_ at _tampabay.rr.com Sun Apr 10 13:32:20 2005 From: radam2_ at _tampabay.rr.com (Ron_Adam) Date: Sun, 10 Apr 2005 17:32:20 GMT Subject: Thoughts on some stdlib modules References: <1113121254.874488.111250@f14g2000cwb.googlegroups.com> Message-ID: On Sun, 10 Apr 2005 13:18:01 +0200, "Fredrik Lundh" wrote: >Kay Schluehr wrote: > >> I fear that Python 3.0 becomes some kind of vaporware in the Python >> community that paralyzes all redesign efforts on the std-lib. Even if Python 3.0 never materializes, The documented PEP may still have an impact on further development of Python. So it might also be referred to as PEP __future__ . Has there been any suggestion of a time line? If there is a new release every 18 months, v2.4 to v3.0 would be, 108 months?, Or would there be a jump from v2.5 or 2.6, to v3.0? >that, combined with the old observation that CPython developers, >when given a choice, prefer to write C code over Python code, is >making the standard library a lot less useful than it could be. > >(if you look at recent releases, most standard lib additions are things >that are fun for language tinkerers and people looking for many ways >to write simple algorithms, but very little stuff that's useful for >scripters >and application builders. a C implementation of _bisect. hello?) "Fun" things and demos could be put in an "extras". That might do a lot to clean up the library so that the rest of it can be put in better perspective. Also looking at my python24 directory there is a 'tools' dir that probably could be put in the extra package as well. >if I were in charge, I'd separate 90% of the standard library from the >core distribution, made sure it ran on multiple implementions (at least >the two latest CPython implementations, plus what's needed to make >as much as possible available on the latest Jython and IronPython >releases), bundled a number of carefully selected external libraries >(without forcing developers to give up rights and loose control over >maintenance), refactor the test suite so it could be used both to test >the library and to see what parts worked properly on your platform, >and make new releases (for testers and early adopters) available >regularily. > > Larger utility packages could be moved from the "stdlib" but still be included as separate packages that can optionally be installed from the python installer. Idle, distutils, tcl/tk, .. ? Probably a clearer definition of purpose for the different parts is needed. I haven't seen anything documented on that specifically. Has it been upto recently, 'more is better' as long as it doesn't break anything? With the emphasis on growing the language? What would definitions of 'purpose' be for? '__builtin__' '__builtins__' packages: 'stdlib' ... 'stdlib23', 'stdlib24' # Versions? 'extras' # examples, demos, and fun stuff other packages included in the install packages available at 'pythonpacks.com' (possible?) seperately installed applications ? Is it possible to get some sort of overview on extending python? Does one already exist? Cheers, Ron From yhdanid at yahoo.com Sat Apr 30 16:35:59 2005 From: yhdanid at yahoo.com (Obaid R.) Date: 30 Apr 2005 13:35:59 -0700 Subject: Ron Grossi: God is not a man References: <1114098221.580669.86300@g14g2000cwa.googlegroups.com> <1114127633.859113.292290@l41g2000cwc.googlegroups.com> <4-CdnYtONKWR3fTfRVn-sA@comcast.com> Message-ID: <1114893359.535040.261000@o13g2000cwo.googlegroups.com> Larry Bates, I truly appreciate the dignified tone of your response. Kindly allow me to respond. IN SPITE OF THE BIBLE, NOT BECAUSE OF IT? ========================================= First I do apologize for the earlier long discourse; I am afraid this might be just as long. There is much to discuss and I try to be through. Having said that, and to respond to your point, please be informed that I did not take any scripture out of context so as to reach a conclusion of my own. If you'd be kind enough to point out one incident I will promptly apologize and will take it back. With that said, I hope you are fair enough to agree that if someone makes a claim that then the same person should back that claim up with proof. That out of context claim you make, brother, is made without proof. Please tell us how Christ the "man" (Acts 2: 22), and "the son of man" (Luke 9: 58) are not part of the Christian textual sources or how they were taken out of context. How is that when it is proclaimed in the Law attributed to Almighty God that "God is not a man ... neither the son of man" (Numbers 23: 19) that this part of the Law (given Acts 2:22, and Luke 9: 58) is not applicable to Christ PBBUH or any other man and son of man from the beginning of time until the end of time. You see, Larry, if someone were to write an essay and post satellite images in support of the fact that earth is spherical, anyone defending the false notion that the earth is flat can simply counter: "you are taking things out of context." But these words will not do, as any fair person can confirm. Without proof, a claim is what it is: just a claim. The burden of proof is on the one who makes the point to prove it, not on the other party to refute what was not proven. In my case, proof was offered in defence of my assertions from what Christian authorities themselves regard as Christian textual sources of divine origin. Does that not carry enough weight for you so as to be convinced? If people will read in their textual sources that "God is not a man ... neither the son of man" and *yet* go on to believe in- and even argue the exact opposite of that- just because they have an opinion, then what is the Bible for then? If people are going to believe that Christ the "man" (Acts 2:22), and the "son of man" (Luke 9: 58) is Almighty God Himself in spite of Numbers (among others), then what is the point of these people having textual sources for their beliefs? Wouldn't it be better if these people got together, sat down, and wrote a novel and made a religion out of it? This is what the Church of Scientology did. Perhaps then that novel would agree with their man-made beliefs, namely that "God is a man and is the son of man" in spite of (Numbers 23: 19)? That "God will dwell on the earth" in spite of (1 Kings 8: 27)? That "there are other 'Gods' with God" and that "there is now someone like unto God" in spite of (Isaiah 46:9)? And so on and so forth? After all, let's face it, Larry, the novel is there inside your (plural) head, and it is from which you are all reading to us that Christ PBBUH the "man" and "the son of man" is actually God; but whether you realize it or not, you are doing so in spite of the word of God as found in the Bible, not because of it. I truly don't know how to make a mention of this and not appear like I wish to offend you, which is truly not my intention, but I must inform you anyway: does the word "anti" ring any bells? PLURAL GOD? =========== Do you believe that God is one or not? Was it not Christ PBBUH himself who said that the "Lord our God is one Lord" (as opposed to a "tri-une" Lord) or was he not? Is there a single explicit mention of the word "Trinity" in the entire encyclopaedia of books called the Bible? Just one? There is none, can you believe it? THE DONKEY RIDE --------------- Please read from the New Testament: "... and they sat him thereon." (The Donkey) (Matthew 21:7) "... and he sat upon him." (The Donkey) (Mark 11:7) "... and they set Jesus thereon." (The Donkey) (Luke 19:35) "... Jesus ... sat thereon:" (The Donkey) (John 12:14) In "Is The Bible God's Word"[1], Ahmed Deedat writes: "Could God Almighty have been the author of this incongruous situation - going out of His Way to see that all the Gospel writers did not miss their footing recording of His "son's" donkey-ride into the Holy City - and yet "inspiring" them to blackout the news about His "son's" heavenly flight on the wings of angels?" I note the exact same amazing situation here. Why is it so important to have all the Gospels mention the donkey incident but not have one single explicit remark anywhere about what effectively will decide the eternal fate (repeat: eternal fate) of many: the alleged "trinity"? Astonishing, no? WHY NOT A PENTINITY? -------------------- Yes "as humans we will never fully understand the Trinity in this lifetime," but so would be the case, I put it to you, concerning "dualnity," (as in two) "quadrupinity", "pentinity", etc., if there is actually such words. You see the issue is not merely that our minds are unable to deal with these impossible concepts, but also (and equally importantly) that we must remember that these concepts were never explicitly mentioned in the word of God. And so the question that faces us is this: why a "trinity," and not a "pentinity"? Any person can make up things in any aggregate along the lines of your crude (yet unproven theory) of what makes God like a man, even when it is the Bible that states not only that "God is not a man ... neither the son of man" (Numbers 23: 19), but also that "God is a Spirit" (John 4:24). Nevertheless, one can add charisma, and the subconscious mind to your physical, spiritual, and emotional "aspects" and get that imaginary "penta-une" false god to be also like man, so as to make a man into Almighty God, may He be glorified above all of this. No, Larry. God is one, period. This is all human invention and has nothing to do with divine revelations. Moreover, do you not see that by saying "Tri" that you are automatically arguing for plurality in God? One does not equal three, Larry, not logically, and not linguistically. All the universally agreed norms of language and reason and even algebra are lined up in defence of God against such illogical notions. Not that Almighty God needs any defence. READ ==== I have read for C. S. Lewis and if I am not mistaken, seen Josh McDowell lecture on TBN. But the matter is different here, Larry. I don't know about McDowell, but I know that C. S. Lewis was questioning the existence of God, not whether or not if he believed in a "trinity" and in Christ PBBUH the "man" and "son of man" as God that he would then be doing so in spite of the word of God as reported in the Bible, not because of it. And since you made that offer, then allow me to suggest you read the Qur'an. There is truly no excuse for anyone not to read it, especially that it is even available online for free download.[2] By the way, did you know that the first verse revealed on prophet Muhammad PBBUH was "Read!" upon which the prophet replied to angel Gabriel PBBUH: "I am not learned." And this, we hold, is a direct fulfillment of Isaiah 29:12: "And the book is delivered to him that is not learned, saying, Read this, I pray thee: and he saith, I am not learned." (Isaiah 29: 12) Here is the first revealed verses of the Qur'an: "Read: In the name of thy Lord Who createth, Createth man from a clot. Read: And thy Lord is the Most Bounteous, Who teacheth by the pen, Teacheth man that which he knew not." (Translation, Qur'an, 96: 1) OPINION VS. DIVINE REVELATIONS ============================== You and I are entitled to our opinions, as is the case for all the people of this earth. These might even matter to someone. When it comes to the issues of the unseen, however, then our opinions (including mine I assure you!) are just worthless. It is not within us to have our minds dwell in the unseen. This is the job of divine revelations. This is their sole purpose: to reveal to us from the world of the unseen that which we cannot grasp or know on our own. If you and I and everyone else are going to make our opinions matter more than divine revelations then not only would we be deceiving ourselves that our inconsequential opinion is now divine truth (which it is not), but we would also be very likely at odds with Almighty God's truth. HOW DO WE INHERIT ETERNAL LIFE? =============================== Your point that there is only one way to God is a valid one. The issue is not that, but whether you and I are following that only way; or to keep to the topic of this thread, whether Grossi's post accurately describes that way. You say that Christ PBBUH is the only way, but did you know that Christ PBBUH is not even your designated prophet? Believe it or not Muhammad PBBUH is. And I know this might come as a shock, but they both peace and blessings of Almighty God be upon them PBBUT, preached the same religion: the worship of one God, we inherit heaven by keeping the law and the commandments, i.e. surrendering one's will to Almighty God, which is Islam in a nutshell. They even prayed the same! In Matthew 26:39 we are told that Christ PBBUH "fell on his face, and prayed!" Must I remind you who else falls on their faces to pray? Moreover, and on at least two occasions in the Bible, Christ PBBUH is explicitly proclaiming that he was sent only to the lost sheep of the house of Israel, not to anyone else of the Gentiles. "But he answered and said, I am not sent but unto the lost sheep of the house of Israel." (Matthew 15: 24) (see also Matthew 10:6). And so even when he was the way, Christ PBBUH was so to his people of the house of Israel only (and this not according to my convenient opinion, but according to the reported first person words attributed to Christ PBBUH), and only in the span of time that he lived on earth, and hence this excludes people of times past and future, especially of the Gentiles. With that said, it is indeed true that people will struggle to come to terms that Islam (of all religions) is God's divine Truth, which it is. That is, I have come to believe, is mankind's present test. Will they contemplate that they might be utterly misguided, that Islam of all religions is the God's Truth, that its Arab prophet PBBUH of the third world is actually the seal of the Almighty God's prophets, the comforter that Christ PBBUH foretold? Will they follow their pride or will they let their minds decide? To have Christianity as the Truth temptation of mankind makes no sense. The Christian West boasts to have the power, the money, the science-- they boast they have everything. Earthly that is. So they must be right in worshiping a "trinity"? Right? But that is an easy test, Larry. If Islam was the Truth and a Muslim failed the test and worshiped a "trinity" in stead of his one true God, he might think that he will gain something in this world. But a Christian who gives up the "trinity" and his earthly wealth, power, and pride that comes with the magic of the West actually seems to many that he will lose according to the earthly ways. No? which is the tougher test, Larry, you tell me. A tougher test would be to have you choose between that alleged earthly power and wealth and Almighty God's truth, even if hidden in the weakest and most poor of places. Or was Christ PBBUH wealthy and powerful compared to the scribes and Pharisees or the Romans? David PBBUH to Saul? Moses PBBUH to Pharaoh? Don't you see the pattern here? If Christ PBBUH was really "son of God" in the literal sense or "God" as per the scripture and word of God, we would be the first to worship, Larry. "Say: "If (Allah) Most Gracious had a son, I would be the first to worship." Glory to the Lord of the heavens and the earth, the Lord of the Throne (of Authority)! (He is free) from the things they attribute (to him)!" (Translation, Qur'an 43: 81-82) But he is not so. And this according to your own scriptures. People are making Christ "God," and believing him to have been crucified and later resurrected in spite of "the word of God" as found in the Bible, not because of it. The only way you can make your beliefs agree with your sources is if either you replace them with something that matches your claims, or that you expunge those parts from the present scripture that testify that Christ is "a man" and "son of man" and that "God is not a man ... neither the son of man" and that the resurrected are spirits equal unto the angels having spiritual bodies. For while these things are still in your Bible then you have a serious problem. Here is an ex-practicing American Christian sharing his thoughts on a topic related to our discussion: "I remember thinking a few years ago, when I was studying about Christianity and Islam, that it sure would be nice to have Jesus around today so that I could go up and ask him two questions: 1) Is it more important to believe that God is "One" or "Tri-une"? and 2) What do I need to do in order to get into Heaven? However, once I thought about it a bit more, I realized that I already had answers to these questions! The New Testament shows how Jesus EXPLICITLY and CLEARLY answered both of these questions - not to mention the Qur'an! How could a prophet doing the work of Almighty God do otherwise? If something such as the "Doctrine of the Trinity" or having Jesus as one's "Lord and Personal Savior" is so important, it would be unjust - if not criminal - for it not to be an explicit teaching. It should be kept in mind that Jesus' audience was made up mostly of Jews, so when he mentioned "One God", they certainly understood it in an absolute and non-Trinitarian way. "Those of you who don't already know Jesus', peace be upon him, clear answers to these direct questions, please see Mark 12:28-34; Matthew 22:35-40; Matthew 19:16-17; Mark 10:17-19 and Luke 18:18-20. "On top of all this, the New Testament says that Jesus, peace be upon him, went around preaching "the gospel". (See Matthew 4:23, 9:35, 11:5; Mark 1:15, 8:35; Luke 4:18, 7:22, 9:6 and 20:1). Based on this fact, Christians should be able to COMPLETELY derive their doctrines and "Gospel message" from the words of Jesus as reported in the New Testament. However, everyone who has taken a look at the evidence should be able to conclude that Christians certainly cannot do this - they have to appeal to the epistles of Paul and to an innovated Trinitarian vocabulary. So what was this "gospel" that Jesus was preaching? Was it CLEARLY the Divine Incarnation, the Atonement and the Trinity? I certainly feel that the longest and most eloquent sermon in the New Testament (Matthew 5-7), commonly know as "The Sermon on the Mount", lends support to the Pure Monotheism of Islam, not to Trinitarian Christian belief."[3] Peace, Obaid RESOURCES ========= [1] Deedat, Ahmed, Is The Bible God's Word, March 1980. April 2005: http://www.ahmed-deedat.co.za/bible/index.html. [2] Download a free Qur'an viewer: http://www.divineislam.co.uk/ [3] Squires, Robert, "A Muslim Response to a Christian Response." April 30, 2005: http://thetruereligion.org/modules/wfsection/article.php?articleid=261&page=0 PS: I posted a response to BrianQ here: http://groups-beta.google.com/group/microsoft.public.windowsxp.network_web/msg/048f37bac5b14460?hl=en From Pierre_Rouleau at impathnetworks.com Fri Apr 22 10:07:04 2005 From: Pierre_Rouleau at impathnetworks.com (Pierre Rouleau) Date: Fri, 22 Apr 2005 10:07:04 -0400 Subject: Problem deriving a class from the built-in file object Message-ID: Hi all! I'm trying to extend the functionality of the file object by creating a class that derives from file. MyFile class re-implements __init__(), write(), writelines() and close() to augment the capabilities of file. All works fine, except for one thing: 'print >> myfile' does not execute Myfile.write(), it executes the file.write(). If I execute myfile.write() explicitly, then Myfile.write() is called as expected. I was not expecting that behaviour. I though that 'print >> afileobject ' would execute the afileobject.write() as you can easily obtain by defining a simple file-like class that implements write() and writeline(). I am running Python 2.3.4. Can't move to 2.4 yet. Is it the expected behavior? # M y F i l e -- Testing inheritance from file -- # ^^^^^^^^^^^ # class MyFile(file): """ Testing new-style class inheritance from file""" # def __init__(self, name, mode="r", buffering=-1, verbose=False): """Constructor""" self.was_modified = False self.verbose = verbose super(MyFile, self).__init__(name, mode, buffering) if self.verbose: print "MyFile %s is opened. The mode is: %s" % (self.name, self.mode) # def write(self, a_string): """ Write a string to the file.""" super(MyFile, self).write(a_string) self.was_modified = True # def writelines(self, sequence): """ Write a sequence of strings to the file. """ super(MyFile, self).writelines(sequence) self.was_modified = True # def close(self) : """Close the file.""" if self.verbose: print "Closing file %s" % self.name super(MyFile, self).close() self.was_modified = False From Gerald.Klix at klix.ch Mon Apr 11 10:43:50 2005 From: Gerald.Klix at klix.ch (Gerald Klix) Date: Mon, 11 Apr 2005 16:43:50 +0200 Subject: variables exist In-Reply-To: <9622d535.0504110552.1e070e8d@posting.google.com> References: <9622d535.0504110552.1e070e8d@posting.google.com> Message-ID: <425A8D26.9010905@klix.ch> try: myVariable except NameError: print "Not bound" else: print "Bound" If you want to distinguish between the local an the global environment: if globals().has_key( "myVariable" ): ... versus if locals().has_key( "..... HTH, Gerald fabian schrieb: > how testing if a variable exists in python as isset in php?? > > thanks -- GPG-Key: http://keyserver.veridis.com:11371/search?q=0xA140D634 From Bill at SynectixLtd.com Wed Apr 20 07:13:44 2005 From: Bill at SynectixLtd.com (Bill Davy) Date: Wed, 20 Apr 2005 11:13:44 +0000 (UTC) Subject: (Python newbie) Using XP-SP2/MSVC6: No Python24_d.lib, winzip barfs on Python-2.4.1.tar, cannot download bzip2 References: Message-ID: Thanks Jaime, I'm making gradual progress and am finding it quite satisfying. Resorted to tracing Python in MSVC6 to see what it was trying to IMPORT, which is a bit heavy but thank heavens for the sources. Had not thouight of "adapting" SWIG, and will think about it when I have a clearer view of what I am doing (rather deeply embedded at present, trying to get one success). I had not spotted SWIG's wrapper round a wrapper (Module.py imports _Module.pyd) but it's reasonable except they go into different directories. And there's the _d too, of course :-( Many thanks for your help, Bill "Jaime Wyant" wrote in message news:mailman.2108.1113922028.1799.python-list at python.org... I fight the python24_d.lib problem with swig daily. The way I got around it was to modify swig's python configuration module. Mine was located at /lib/swig1.3/python/python.swg (I'm using cygwin) At the top, I changed #include "python.h" to #ifdef _DEBUG #undef _DEBUG #include "python.h" #define _DEBUG #else #include "python.h" #endif Somewhere in the includes, python uses a pragma telling the MSVC compiler which library to link the object files against. Because you're building a _DEBUG build, you magically get the python24_d.lib library. hth, jw On 4/18/05, Bill Davy wrote: > I downlaoded and installed > http://www.python.org/ftp/python/2.4.1/python-2.4.1.msi > > I'm trying to build an extension using SWIG 1.3.24 and the linker needs > python24_d.lib (I do not have the DLL either). I've not found it in any > of > the > downloads. > > So I tried to download the source to build it myself. Of > http://www.python.org/ftp/python/2.4.1/Python-2.4.1.tar.bz2 and > http://www.python.org/ftp/python/2.4.1/Python-2.4.1.tgz, WinZip (9.0 SR1) > just says "Error reading header after processing 0 entries". > > Additionally, I've had no joy downloading the unzipper > (ftp://sources.redhat.com/pub/bzip2/v102/bzip2-102-x86-win32.exe) from the > site cited for the unzipper (http://sources.redhat.com/bzip2/). It > flashed > up a > black console window momentarily. > > Oh, this is sooooo frustrating! :-( > > Can anyone point me in the right direction? > > And then I can get to grips with my work. > > tia > Bill > > -- > http://mail.python.org/mailman/listinfo/python-list > From simon.brunning at gmail.com Wed Apr 20 08:25:07 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Wed, 20 Apr 2005 13:25:07 +0100 Subject: building a small calculator In-Reply-To: <1113999497.480245.47240@g14g2000cwa.googlegroups.com> References: <1113999497.480245.47240@g14g2000cwa.googlegroups.com> Message-ID: <8c7f10c605042005255461ff@mail.gmail.com> On 20 Apr 2005 05:18:17 -0700, aleksander.helgaker at gmail.com wrote: > Now once the user has select a shape and typed in the lengths required, > the result is printed and the program quits. What I want to do is make > the program display the result and then make it wait for the user to > press return (or something like that) after which the screen will be > cleared and they'll be back at the main menu. raw_input('Hit Enter to continue...') > Also I would like to add option nr 4 to the menu and make that the quit > command, but what command does python have to stop a program? I tried > end but that did not work. sys.exit() Welcome to Python! -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From fredrik at pythonware.com Wed Apr 6 07:55:26 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 6 Apr 2005 13:55:26 +0200 Subject: ignoring keywords on func. call References: <1112787673.095411.266170@o13g2000cwo.googlegroups.com> Message-ID: Brano Zarnovican wrote: > Q: Can you call 'f' with keywords that will be > ignored, without changing 'f's definition ? no. > I would like to avoid code like this: > k = {} > k['optional'] = 2 > try: > f(1, **k) > except TypeError: > f(1) why would you write code like this? what's the use case? > Also, the problem is that I don't know if the TypeError > was caused by calling 'f' with keywords or somewhere > "inside" f. > > You can also say that I need to specify optional parameters > on caller side (not called side). you can use reflection mechanisms to check the target function signature, but I won't tell you how to do that until you show me a reasonable use case ;-) From Ian.Sparks at etrials.com Tue Apr 5 17:22:23 2005 From: Ian.Sparks at etrials.com (Ian Sparks) Date: Tue, 5 Apr 2005 17:22:23 -0400 Subject: Class, object question. Message-ID: <41A1CBC76FDECC42B67946519C6677A901915BD5@pippin.int.etrials.com> Use the *args positional-argument to catch all the positional arguments in the constructor then test them to see what you have and call a kind of sub-init based on that : class Point: def __init__(self,x,y,z): self.x = x self.y = y self.z = z class Vector: def __init__(self,*args): if len(args) == 3: self.setFromValues(args) elif len(args) == 2: if isinstance(args[0],Point): self.setFromPoints(args) else: raise "Incorrect constructor" print self.i,self.j,self.k def setFromValues(self,args): self.i,self.j,self.k = args def setFromPoints(self,args): self.i = args[1].x - args[0].x self.j = args[1].y - args[0].y self.k = args[1].z - args[0].z v = Vector(1,2,3) p1 = Point(2,2,2) p2 = Point(4,4,4) v2 = Vector(p1,p2) Hope this helps. -----Original Message----- From: Jeffrey Maitland [mailto:maitj at vianet.ca] Sent: Tuesday, April 05, 2005 10:04 AM To: python-list at python.org Subject: Class, object question. Hello folks, The question I am having is something like this. # ignore the precursing .... I am using them for easy message formatting from point import * Class vector(point): ..........def __init___(self, point1, point2): .................self.i = point2.get_x() - point1.get_x() .................self.j = point2.get_y() - point1.get_y() .................self.k = point2.get_z() - point1.get_z() # methods of vector. Defined here. What I am wondering is if I have a 2nd init or something similar to create a vector. Such as what follows and if I can how do I go about implementing it? Class vector(point): ..........def __init___(self, point1, point2): .................self.i = point2.get_x() - point1.get_x() .................self.j = point2.get_y() - point1.get_y() .................self.k = point2.get_z() - point1.get_z() . ..........def __init___(self, i, j, k): .................self.i = i .................self.j = j .................self.k = k That way I can define a vector either using 2 points or if I have the vector data itself? Thanks in advance Jeff -------------- next part -------------- An HTML attachment was scrubbed... URL: From s_david_rose at hotmail.com Mon Apr 25 15:15:54 2005 From: s_david_rose at hotmail.com (GMane Python) Date: Mon, 25 Apr 2005 15:15:54 -0400 Subject: Pickle an image? Message-ID: Hey all. I have a ( list | tuple | dictionary ) with several graphics in it. Trying to cPickle it to a file, I get errors. For instance, UnpickleableError: Cannon pickle objects. Anyone know of a way to get around this? I'd like to pickle a list or dictionary of about 5 .JPG images. Thanks! Dave From rune.strand at gmail.com Mon Apr 18 12:01:26 2005 From: rune.strand at gmail.com (runes) Date: 18 Apr 2005 09:01:26 -0700 Subject: Behaviour of str.split References: <4263cf31$0$26348$db0fefd9@news.zen.co.uk> Message-ID: <1113838796.626344.309630@l41g2000cwc.googlegroups.com> The behaviour of "".split("*") is not that strange as the splitpoint always disappear. The re.split() have a nice option to keep the splitpoint which the str.split should have, I think. One expectation I keep fighting within myself is that I expect "mystring".split('') to return ['m', 'y', 's', 't', 'r', 'i', 'n', 'g']. But I guess it's in line with "There should be one-- and preferably only one --obvious way to do it." that it's not so. From martin at v.loewis.de Sun Apr 3 10:27:32 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 03 Apr 2005 16:27:32 +0200 Subject: string goes away In-Reply-To: References: Message-ID: <424FFD54.6080401@v.loewis.de> Andreas Beyer wrote: > If I am getting the docs etc. correctly, the string-module is depricated > and is supposed to be removed with the release of Python 3.0. > I still use the module a lot and there are situations in which I don't > know what to do without it. Maybe you can give me some help. Out of curiosity: when thinking about Python 3.0, what is the timespan in which you expect that to appear? Before 2010? After 2010? After 2020? Regards, Martin From merkosh at hadiko.de Thu Apr 28 08:24:30 2005 From: merkosh at hadiko.de (Uwe Mayer) Date: Thu, 28 Apr 2005 14:24:30 +0200 Subject: anonymous function objects? Message-ID: Is it possible to specify anonymous functions, something like: >>> f = {print "hello world"} >>> f() hello world in Pyton? Lambda expressions don't work here. Thanks, Uwe From postmaster at castleamber.com Sat Apr 23 22:48:21 2005 From: postmaster at castleamber.com (John Bokma) Date: 24 Apr 2005 02:48:21 GMT Subject: Python or PHP? References: Message-ID: Leif K-Brooks wrote: > John Bokma wrote: >> my $sort = $cgi->param( "sort" ); >> my $query = "SELECT * FROM table WHERE id=? ORDER BY $sort"; > > And the equivalent Python code: > > cursor.execute('SELECT * FROM table WHERE id=%%s ORDER BY %s' % sort, > [some_id]) > > You're right, of course, about being *able* to write code with SQL > injection vulnerabilities in Python. I can only speak for Perl for now, but I am sure it has been done, and I don't want to know how often :-D (Unless everyone who did pays me 1 USD). > But it's not even close to being as > easy as in PHP. I didn't deny that :-) Personally I don't like PHPs "magicaddslashquote" stuff. It gives beginners the impression that everything is taken care of. It's like giving someone a house with a door with 7 locks, without telling all windows at ground level can't be closed (and the master key is under the doormat) -- John MexIT: http://johnbokma.com/mexit/ personal page: http://johnbokma.com/ Experienced programmer available: http://castleamber.com/ Happy Customers: http://castleamber.com/testimonials.html From sjmachin at lexicon.net Wed Apr 20 08:01:56 2005 From: sjmachin at lexicon.net (John Machin) Date: Wed, 20 Apr 2005 22:01:56 +1000 Subject: trying to understand unicode References: <426635db$0$2079$626a14ce@news.free.fr> Message-ID: On 20 Apr 2005 10:58:35 GMT, "F. Petitjean" wrote: >Python has a very good support of unicode, utf8, encodings ... But I >have some difficulties with the concepts and the vocabulary. You're not alone there. But I don't expect the docs for the Python implementation of Unicode to explain the concepts and vocabulary of Unicode. That's the job of the Unicode consortium, and they do a not-unreasonable job of it; see www.unicode.org and in particular http://www.unicode.org/Public/UNIDATA/UCD.html explains all the things that the Python unicodedata module is implementing. > The >documentation is not bad, but for example in reading >http://docs.python.org/lib/module-unicodedata.html >I had a long time to figure out what unicodedata.digit(unichr) would >mean, a simple example is badly lacking. > >So I wrote the following script : > [snip] > >I think that such code snippets should be included in the documentation >or in a Wiki. > Any effort should be directed (IMESHO) towards (a) keeping the URL in the Python documentation up-to-date [it's not] (b) using the *LATEST* version of the ucd file when each version of Python is released [still stuck on 3.2.0 when the current version available from Unicode.org is 4.1.0] [Exit, pursued by a bear.] [Noises off.] OK OK don't hit me, Martin, how about instructions on how to DIY, then? Cheers, John From mark.hellewell at gmail.com Thu Apr 14 08:47:20 2005 From: mark.hellewell at gmail.com (mark hellewell) Date: Thu, 14 Apr 2005 13:47:20 +0100 Subject: A little request about spam In-Reply-To: <740c3aec05041405157cb90625@mail.gmail.com> References: <1113416856.914310.63930@l41g2000cwc.googlegroups.com> <740c3aec05041405157cb90625@mail.gmail.com> Message-ID: On 4/14/05, BJ?rn Lindqvist wrote: > Please do not reply to spam. Replying to spam makes it much harder for > spam filters to catch all the spam or will produce very many false > positives. Atleast that's how gmail's filter works. And if you must > reply, please change the subject line. Is anybody else finding that Gmails spam filter has started labelling a lot of python-list emails as spam? About 20 python-list emails a day end up getting caught by their filter and I'm having to manually go in and mark them as "Not spam". mark From deetsNOSPAM at web.de Thu Apr 21 18:14:31 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Fri, 22 Apr 2005 00:14:31 +0200 Subject: Jython run scripts problem (2.2.0a0 on Mac OSX 10.3.8) References: Message-ID: scott wrote: > I installed darwinports and did a "sudo port install jython" > > ------------------------- > > scott$ which jython > /opt/local/bin/jython > > ------------------------- > > Jython works in interactive mode as shown below: > > ------------------------- > > pyprogs$ cd hotbits/ > hotbits$ ls > flips50.py jythoninstall.py randomX randomflip.py > hotbits$ jython > Jython 2.2a0 on java1.4.2_05 (JIT: null) > >>> # Truly random (radioactive decay triggered) coin flip > >>> from randomX import randomHotBits > >>> r = randomHotBits() > >>> if r.nextByte() < 0: > ... print 'tails' > ... else: > ... print 'heads' > ... > tails > > -------------------------- > > Jython *doesn't* work if I save the above as a script and try to run it. > It refuses to run the script and simply starts up in interactive mode: > > --------------------------- > > hotbits$ jython randomflip.py > Jython 2.2a0 on java1.4.2_05 (JIT: null) > >>> > > --------------------------- > > Question: > How can I run scripts as expected (outside interactive mode)? > > Thanks in advance. Looks as if the jython shell script does not pass your scriptname as argument to the interpreter class. Mine (on linux) looks like this: "/usr/lib/j2se/1.4/jre/bin/java" -Dpython.home="/home/deets/lib/jython-2.1" -classpath "/home/deets/lib/jython-2.1/jython.jar:$CLASSPATH" "org.python.util.jython" "$@" Note the "$@" - that passes all additional arguments. -- Regards, Diez B. Roggisch From reply-to-group at use.net Sun Apr 10 06:55:05 2005 From: reply-to-group at use.net (T Koster) Date: Sun, 10 Apr 2005 20:55:05 +1000 Subject: Signals and system Message-ID: <42590634$0$29863$afc38c87@news.optusnet.com.au> Hi folks, My python program needs to download a number of files. Each file comes as a list of mirrors of that file. Currently, I am using system (os.system) to run wget. The mechanism is in a loop, so that it will try all the mirrors while wget is exiting with a non-zero exit status. This is working fine as long as the user feels there is no need to interrupt it. If wget receives a SIGINT, it stops (as expected) and returns non-zero (1 from memory). The call to system returns the same status code, indicating that wget failed, but the program has no knowledge that it was a signal the killed wget, rather than a failed download, and as such it tries the next mirror. I would like to be notified if wget received any signals, so that the user doesn't need to repetitively press Ctrl-C for each and every mirror to get the downloading process to stop. Can someone point me in the right direction? Thanks in advance, Koster From bdesth.quelquechose at free.quelquepart.fr Wed Apr 27 17:20:04 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 27 Apr 2005 23:20:04 +0200 Subject: Which IDE is recommended? In-Reply-To: <426f90ac$1_2@rain.i-cable.com> References: <426f90ac$1_2@rain.i-cable.com> Message-ID: <426ffda2$0$17026$626a14ce@news.free.fr> monkey a ?crit : > Read through python site for programming tool, really plenty of choices :-) > (For c++, I just can't breath with very very limited choices) > > Tried Spe, it come with wxGlade built-in very nice(is Spe still actively > develop?). But seem that Boa Constructor and PyDev(the plug-in for Eclipse) > also worth looking. Actually which one are you guys using? and why? I think > it is also valuable for those who are new to python as me. > emacs + ECB + python-mode. From ilias at lazaridis.com Sat Apr 2 10:13:48 2005 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Sat, 02 Apr 2005 18:13:48 +0300 Subject: [EVALUATION] - E03 - jamLang Evaluation Case Applied to Python Message-ID: [EVALUATION] - E02 - Support for MinGW Open Source Compiler http://groups-beta.google.com/group/comp.lang.python/msg/f5cd74aa26617f17 - In comparison to the E02 thread, now a more practical one. - Here is a simple evaluation template (first part) which can be applied to the Python language: http://lazaridis.com/case/lang/index.html If you like, please post the most elegant solutions (either to sections or to the whole document). I will collect the results and write them down in a document, which will compare python with other languages. This document can serve as an flash-start (for people which simply like to take a look on python). http://lazaridis.com/case/lang/python.html - You can see the ruby version here (which shows some limitations, which python can hopefully overcome): http://lazaridis.com/case/lang/ruby.html . -- http://lazaridis.com From martin at v.loewis.de Sat Apr 9 07:37:47 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 09 Apr 2005 13:37:47 +0200 Subject: Thoughts on some stdlib modules In-Reply-To: References: Message-ID: <4257BE8B.9080209@v.loewis.de> vegetax wrote: > Why does people have to put wrappers around about half of the standart > library modules? i have wrappers for urllib,urllib2, [... many more ...] > > I mean is this normal? Not sure what "this" is :-) Is it normal that people write wrappers around libraries? Yes, most certainly so. I see people writing wrappers around the C++ library, around Java collection classes (*), around .NET classes, ... essentially for every library that somebody writes, somebody else will write a wrapper - unless the library is useless. Is it normal that *you* write this many wrappers? I don't know you good enough to answer that question :-) Is it good that people write these wrappers? I don't think so. Is it the library's fault? I don't think so, either. People write these wrappers because they cannot remember how to use the library. This is not because the library is hard to remember, but because people cannot remember much at all - except for the things they have done themselves (**). So they write a library wrapper, and doing so takes them enough time to ingrain their own API into their own memory. If somebody else wrote the very same wrapper for them, they still would not like to use it. So what can be done? Not much, I think - no matter what the library reorganization is, people will continue to write wrappers around it. That is not to say that a library reorganization couldn't be helpful to some people - if people find enough energy, a library reorganization will happen. Some will like it, some will hate it. I personally try to avoid library wrappers like the plague. It makes my code harder to write, but easier to read. Regards, Martin (*) Just look at the Apache Commons library. People write wrappers for stuff like bool isEmptyString(String s){ return s==null || s.length()==0; } (**) of course, most people can only remember a subset of these, as well. From mrtact at gmail.com Wed Apr 6 16:27:47 2005 From: mrtact at gmail.com (Tim Keating) Date: 6 Apr 2005 13:27:47 -0700 Subject: Best editor? In-Reply-To: References: <1112725379.514651.66540@l41g2000cwc.googlegroups.com> Message-ID: <1112819267.956169.107830@l41g2000cwc.googlegroups.com> I bought the Komodo personal edition, and at only $30, it is worth it for the regular expression toolkit alone. From grig.gheorghiu at gmail.com Tue Apr 5 20:22:49 2005 From: grig.gheorghiu at gmail.com (Grig Gheorghiu) Date: 5 Apr 2005 17:22:49 -0700 Subject: oracle interface References: Message-ID: <1112746969.528029.184120@l41g2000cwc.googlegroups.com> I subscribe to the other posters' opinion: cx_Oracle is what I use on Windows, Linux and Solaris. Works great cross-platform and across Oracle versions (I use it with Oracle 9 and 10, haven't tried 8 yet). Grig From bokr at oz.net Tue Apr 26 22:07:44 2005 From: bokr at oz.net (Bengt Richter) Date: Wed, 27 Apr 2005 02:07:44 GMT Subject: What's do list comprehensions do that generator expressions don't? References: <86ll77pgqz.fsf@guru.mired.org><426ddda7.553554359@news.oz.net> <861x8ynha0.fsf@guru.mired.org> Message-ID: <426ef346.3509746@news.oz.net> On Tue, 26 Apr 2005 13:22:28 -0400, "Terry Reedy" wrote: > >"Mike Meyer" wrote in message >> The question under these circumstances is then: do you want bare >> genexp to mean something? Right now, it's a syntax error. But there's >> no reason you couldn't have: >> >> y = x for x in stuff >> >> assign a generator object to y. > >Since this was considered, there is a reason why we don't have this. As I >remenber, but vaguely, Guido's reasoning was both stylistic and technical, >but you'd have to check the archives for more. > Because it is too reminiscent of a lambda expression assignment? ;-) Regards, Bengt Richter From claird at lairds.us Sat Apr 2 14:08:01 2005 From: claird at lairds.us (Cameron Laird) Date: Sat, 02 Apr 2005 19:08:01 GMT Subject: Pseudocode in the wikipedia References: Message-ID: In article , Ivan Van Laningham wrote: . . . >> >>> 25 >> 25 >> >>> (_ | _) >> 25 >> >>> >> >> There's clearly some interesting biometrics research to be done here, >> although there is a well-known ass-capturing attack based on readily >> commercially available machines from Xerox that might make it hard to make >> an ass-based identity system resistant to attacks. > >http://www.jacquelinestallone.com/rumps.html > >Metta, >Ivan > >PS: I don't think this is an 0401 page; it's been there a while. . . . Welcome back, Ivan. Your follow-ups make one wonder about the span of related topics clp has been missing in your absence. From stnchris at xmission.com Tue Apr 19 18:47:01 2005 From: stnchris at xmission.com (Steve Christensen) Date: Tue, 19 Apr 2005 22:47:01 +0000 (UTC) Subject: build flow? SCons? AAP? process creation? References: <1113420994.118316.245190@g14g2000cwa.googlegroups.com> Message-ID: In article <1113420994.118316.245190 at g14g2000cwa.googlegroups.com>, corey.coughlin at comcast.net wrote: > Hey guys, here's a little question. I'm looking for something like a > build system, where I can set up a bunch of jobs with dependencies, and > have them run in parallel. Ideally, I'd like a system where jobs can > be run in parallel, all the stdout and stderr for each job is kept in a > database of some kind, jobs can be anything that can be run at a > command line, and a failing job won't cause the whole run to fail. > I've been looking into some of the standard stuff (GNU make) and some > of the more pythonic stuff like SCons and AAP. SCons seems to do > parallel execution, which is nice, but I can't figure out from the docs > if it's possible to keep stdout and stderr somewhere. AAP seems to > have a nice interface, but it doesn't do parallel. Here's something from the SCons Wiki: http://www.scons.org/cgi-bin/wiki/BuildLog -Steve -- So if you people can't figure out what my birthday is based on subtle hints and vague statements made at random intervals then I'm beginning to think that you really don't care. -- Dean Lenort, a.r.k. From snail at objmedia.demon.co.uk Tue Apr 12 04:33:16 2005 From: snail at objmedia.demon.co.uk (Stephen Kellett) Date: Tue, 12 Apr 2005 09:33:16 +0100 Subject: NSInstaller Vs. Inno Setup References: <1113250756.207904.29670@f14g2000cwb.googlegroups.com> <425AF329.6030603@v.loewis.de> Message-ID: In message <425AF329.6030603 at v.loewis.de>, Martin v. L?wis writes >dcrespo wrote: >> Any comments? > >MSI. MSI fails on every NT 4 system I've seen. Even with all the patches from Microsoft. Inno Setup wins every time in this situation. Its also a lot less hassle than MSI for what I need. Stephen -- Stephen Kellett Object Media Limited http://www.objmedia.demon.co.uk RSI Information: http://www.objmedia.demon.co.uk/rsi.html From henrikpierrou at hotmail.com Wed Apr 20 03:32:20 2005 From: henrikpierrou at hotmail.com (henrikpierrou at hotmail.com) Date: 20 Apr 2005 00:32:20 -0700 Subject: Python instances Message-ID: <1113982340.156937.75530@f14g2000cwb.googlegroups.com> Hi, How do python instances work? Why does the code at the end of my posting produce this output: list in a: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] list in b: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] instead of list in a: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] list in b: [] ---------------------------- class MyClass: list = [] def add(self, x): self.list.append(x) def printer(self): print self.list a = MyClass() b = MyClass() for n in range(10): a.add(n) print "list in a:" a.printer() print "list in b:" b.printer() /H From eurleif at ecritters.biz Sat Apr 2 05:18:25 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Sat, 02 Apr 2005 10:18:25 GMT Subject: Simple thread-safe counter? In-Reply-To: <3b70ntF6fd45tU1@individual.net> References: <7x3bu9ss22.fsf_-_@ruckus.brouhaha.com> <3b70ntF6fd45tU1@individual.net> Message-ID: Artie Gold wrote: > Skip Montanaro wrote: > >> counter = Queue.Queue() >> def f(): >> i = counter.get() > > I think you need: > i = counter.get(True) The default value for the "block" argument to Queue.get is True. From vegeta.z at gmail.com Tue Apr 5 12:58:17 2005 From: vegeta.z at gmail.com (vegetax) Date: Tue, 05 Apr 2005 12:58:17 -0400 Subject: Python Google Server References: <1112696434.623557.97000@g14g2000cwa.googlegroups.com> <1112706994.922193.5610@z14g2000cwz.googlegroups.com> <1112714083.674249.44370@g14g2000cwa.googlegroups.com> Message-ID: Fuzzyman wrote: > Of course - sorry. Thanks for the fix. Out of interest - why are you > using this... just for curiosity, or is it helpful ? because is fun to surf on the google cache, =) From grante at visi.com Mon Apr 25 12:03:30 2005 From: grante at visi.com (Grant Edwards) Date: Mon, 25 Apr 2005 16:03:30 -0000 Subject: PyGTK vs. wxPython References: <1114444582.909431.245450@f14g2000cwb.googlegroups.com> Message-ID: <116q56ie4vqtu04@corp.supernews.com> On 2005-04-25, dcrespo wrote: > Hi all... > > I think wxPython is much better than PyGTK. First of all, PyGTK needs > the GTK runtime installed, whereas wxPython is entirely Python's > modules, Huh? wxPythonGTK requires GTK runtimes as well: $ ldd libwx_gtk2_core-2.5.so> /tmp/foo linux-gate.so.1 => (0xffffe000) libz.so.1 => /lib/libz.so.1 (0x4028d000) libdl.so.2 => /lib/libdl.so.2 (0x4029e000) libgtk-x11-2.0.so.0 => /usr/lib/libgtk-x11-2.0.so.0 (0x402a1000) libgdk-x11-2.0.so.0 => /usr/lib/libgdk-x11-2.0.so.0 (0x40585000) libatk-1.0.so.0 => /usr/lib/libatk-1.0.so.0 (0x405fa000) libgdk_pixbuf-2.0.so.0 => /usr/lib/libgdk_pixbuf-2.0.so.0 (0x40616000) [...] If you run wxPython on top of some other toolkit, then you'll need that toolkit's runtimes instead of GTK. -- Grant Edwards grante Yow! Yow! Those people at look exactly like Donnie visi.com and Marie Osmond!! From bearophileHUGS at lycos.com Fri Apr 1 06:41:49 2005 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 1 Apr 2005 03:41:49 -0800 Subject: Suggesting methods with similar names In-Reply-To: References: <1112188872.175741.225080@f14g2000cwb.googlegroups.com> <424b3db3.107335950@news.oz.net> Message-ID: <1112355709.500870.51200@l41g2000cwc.googlegroups.com> Suggesting method names based on a wrong method name can be useful, but I think the "smart help" can be improved: it can also be useful to have a suggestion for method names on the basis on a short description (or keywords) about what I want to do to/with the object. Maybe some people here can give me some suggestions on how to do this. I think I can add a Keywords: xxxx, xxx, xxxx. final part to each docstring of the methods, so a kind of little search engine can search for the few most fitting methods based on the user text search query, and on the methods keywords+doc texts. User query example: "How to rotate the object" Result (a short ranked list of method names that can perform that operation): rotate, flip, pivot, mirror (Note: the query is inserted calling a "help" method, or something similar, etc. It doesn't require any magic.) Do you know any little search engine that can be used for this purpose? Thank you, Bearophile From stuff at slinkp.com Wed Apr 13 15:52:05 2005 From: stuff at slinkp.com (Paul Winkler) Date: 13 Apr 2005 12:52:05 -0700 Subject: HTTPSConnection script fails, but only on some servers (long) References: <1113286151.373379.30670@l41g2000cwc.googlegroups.com> <1113416410.167018.216860@g14g2000cwa.googlegroups.com> Message-ID: <1113421925.843281.233620@l41g2000cwc.googlegroups.com> pyg... at gmail.com wrote: > I have a couple of recipes at the python cookbook site, that allows > python to do proxy auth and ssl. The easiest one is: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/301740 Thanks for that John! I gave it a whirl, changed the user, passwd, host, and phost and gave it a run. It instantly barfs with this: Traceback (most recent call last): File "testYetAnotherHttpsClient.py", line 25, in ? ssl = socket.ssl(proxy, None, None) File "/usr/lib/python2.3/socket.py", line 73, in ssl return _realssl(sock, keyfile, certfile) socket.sslerror: (8, 'EOF occurred in violation of protocol') Hmm. On reflection, I don't think the problem solved by your script is the same as mine. As I understand it, your script connects to an SSL-protected server on port 443 by going through a plain HTTP proxy on port 80? That's not the case for me. The server on port 80 is behind the server on port 443. From steven.bethard at gmail.com Thu Apr 21 12:54:54 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 21 Apr 2005 10:54:54 -0600 Subject: deprecation of has_key? In-Reply-To: References: <1114069715.945176.73750@l41g2000cwc.googlegroups.com> <426775C8.3000303@holdenweb.com> Message-ID: Fredrik Lundh wrote: > Steven Bethard wrote: > >>> For me dictionary is a collection of key-value pairs, but not a >>> collection of keys (that's what set is). >> >> Ahh, ok. Now I understand. I think you could probably search the >> python-dev archives and see why the decision was made as it was. For >> pretty much all my purposes, "key in dict" is much more useful than >> "item in dict". Practicality beats Purity and all. ;) > > well, for all my purposes, I find that "dict.get(key)" (or sometimes > "dict[key]" is a lot more useful than has_key and in... True enough. Grepping through my (small) code base, I found only five uses of "key in dict" style code... STeVe From ola.natvig at infosense.no Wed Apr 27 02:44:36 2005 From: ola.natvig at infosense.no (Ola Natvig) Date: Wed, 27 Apr 2005 08:44:36 +0200 Subject: python equivalent of php implode In-Reply-To: References: Message-ID: Maksim Kasimov wrote: > > in php-scripts, to insert data to database, i'm doing like this: > > ... > $query_param = array( > 'field0' => 1, > 'field1' => 3, > 'field2' => $var2, > 'field3' => $var3, > ); > ... > > $sql = "INSERT INTO $table (".implode(", ", > array_keys($query_param)).") VALUES ('".implode("','", $query_param)."')"; > > how it can be done, using python (elegantly, without cycles)? > > sql = "INSERT INTO %s (%s) VALUES (%s)" % (table, ','.params.keys()), ','.join(param.values())) should do the trick. -- -------------------------------------- Ola Natvig infoSense AS / development From abuse at solumslekt.org Sat Apr 9 06:03:44 2005 From: abuse at solumslekt.org (Leif B. Kristensen) Date: Sat, 09 Apr 2005 12:03:44 +0200 Subject: Problem with national characters References: <424cdd51$0$21909$9b622d9e@news.freenet.de> Message-ID: <4MN5e.5727$SL4.116043@news4.e.nsc.no> "Martin v. L?wis" skrev: > You need to do locale.setlocale(locale.LC_ALL, "") to get > locale-specific upper-casing. That makes a lot of sense. Thank you. >>> 'f?r'.upper() 'F\xf8R' >>> 'F?R' 'F\xd8R' >>> import locale >>> locale.setlocale(locale.LC_ALL, "") 'no_NO' >>> 'f?r'.upper() 'F\xd8R' >>> 'F?R' 'F\xd8R' I must make a note of the LC_ALL variable in the installation README. I for one have been running Gentoo Linux for two years without ever setting the locale, - but now I've finally gotten around to write my own /etc/env.d/02locale file :-) > Notice that things are more difficult in the Windows terminal window, > as this uses an encoding different from the one that the system's > locale functions expect. The real input will come from a GUI or a browser interface, so the Windows terminal problem isn't really an issue. -- Leif Biberg Kristensen http://solumslekt.org/ From tjreedy at udel.edu Mon Apr 4 19:56:40 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 4 Apr 2005 19:56:40 -0400 Subject: sparse sets of integers? References: Message-ID: "Dan Stromberg" wrote in message news:pan.2005.04.04.21.52.58.910482 at dcs.nac.uci.edu... > > Does anyone have a python implementation (or python C/C+ extension) that > would allow me to perform set operations (union, intersection, > difference, > number of elements, &c) over very large collections of integers? > > Some of the sets may have over 10**11 (probably less than 10**13 > though) integers in them, but there will tend to be runs of integers > being > included or not included, so there might be 10**5 consecutive integers > included, then 10**4 that are not included, and then another 10**6 that > are. I would call this chunky rather than sparse. Or a set (ordered list) of integer ranges, which I am sure is how you implemented it before. I did not find anything Googling 'Python integer range set' but would look harder before coding. Terry J. Reedy From serpent17 at gmail.com Wed Apr 27 12:00:44 2005 From: serpent17 at gmail.com (serpent17 at gmail.com) Date: 27 Apr 2005 09:00:44 -0700 Subject: How do I parse this ? regexp ? In-Reply-To: <87mzrkxnz2.fsf@jupiter.g2ctech> References: <1114613771.165548.60030@g14g2000cwa.googlegroups.com> <87mzrkxnz2.fsf@jupiter.g2ctech> Message-ID: <1114617644.857534.307750@g14g2000cwa.googlegroups.com> Hello, I am not understanding your answer, but I probably asked the wrong question :-) I want to remove the commas, and square brackets [ and ] characters and rewrite this whole line (and all the ones following in a text file where only space would be a delimiter. How do I do this ? I have tried this: f = open(name3,'r') r = r"\d+\.\d*" for line in f: cols = line.split() data1 = re.findall(r,line) and then I don't know what to do with either cols nor data1 Jake. From greg at cosc.canterbury.ac.nz Tue Apr 19 23:38:18 2005 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Wed, 20 Apr 2005 15:38:18 +1200 Subject: pre-PEP: Simple Thunks In-Reply-To: References: <3jl2615c5pckknicc32ccv2cktue3nh603@4ax.com> Message-ID: <3cm15nF6m5qgiU1@individual.net> Brian Sabbey wrote: > do f in with_file('file.txt'): > print f.read() I don't like this syntax. Try to read it as an English sentence: "Do f in with file 'file.txt'". Say what??? To sound right it would have to be something like with_file('file.txt') as f do: print f.read() But, while that works with this particular function name, and others of the form "with_xxx", there are bound to be other use cases which would require different words or word orders in order not to sound contrived. It's very difficult to come up with a good syntax for this that isn't skewed towards one kind of use case. That's probably a large part of the reason why nothing like it has so far been seriously considered for adoption. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From Sibylle.Koczian at Bibliothek.Uni-Augsburg.de Wed Apr 13 08:11:22 2005 From: Sibylle.Koczian at Bibliothek.Uni-Augsburg.de (Sibylle Koczian) Date: Wed, 13 Apr 2005 14:11:22 +0200 Subject: [perl-python] Python documentation moronicities (continued) In-Reply-To: References: <1113301533.054410.203710@z14g2000cwz.googlegroups.com> Message-ID: <3c4gjaF6kr60dU1@news.dfncis.de> Pokerface schrieb: > Gotta say, is we let this man write the docs for us, they'll sure as > sugar be more colorful than the ones we presently have, even if he > doesn't manage to make them better. > > "The [insert relation]****ing Python interpreter is usually installed > as /usr/local/bin/python on those g*dd*mn machines where it is > available; putting /usr/local/bin in your ****ing Unix shell's search > path makes it possible to start it by typing the command python to the > shell. F***er." > > Please think of people with other native languages who can possibly read the existing documentation without a dictionary but would certainly need one for this. Koczian From python.tr at gmail.com Sat Apr 9 02:04:09 2005 From: python.tr at gmail.com (Hasan D) Date: Sat, 9 Apr 2005 09:04:09 +0300 Subject: Https Form Page In-Reply-To: <259dbf1b66d0acb9df2e992507914428@flowtheory.net> References: <764176c10504081313501b1e1f@mail.gmail.com> <87b1fe089f338ada9e53838fd1f7d90e@flowtheory.net> <764176c105040815512969ae22@mail.gmail.com> <259dbf1b66d0acb9df2e992507914428@flowtheory.net> Message-ID: <764176c10504082304cc6f3fa@mail.gmail.com> I cant figure out, always gives me the form page. Everything looks ok but ? On Apr 9, 2005 2:07 AM, Joshua Ginsberg wrote: > If url is your formpage and your formdata is correct, it should work. > > Do you need to have a cookie set? Is it 304 redirecting you? > > -jag > > > > Joshua Ginsberg -- joshg at brainstorminternet.net > Brainstorm Internet Network Operations > 970-247-1442 x131 > On Apr 8, 2005, at 4:51 PM, Hasan D wrote: > > > Thank you for fast reply. > > Your program works fine. But when i print the https_response it gives > > me the form page. I want to send the form and print the result page. > > > > > > > > On Apr 9, 2005 12:19 AM, Joshua Ginsberg > > wrote: > >> Try: > >> > >> import urllib2, urllib > >> formdata = urllib.urlencode({'a':1,'b':2}) > >> request = urllib2.Request(url) > >> request.add_data(formdata) > >> opener = urllib2.build_opener(urllib2.HTTPSHandler()) > >> urllib2.install_opener(opener) > >> fs = urllib2.urlopen(request) > >> https_response = fs.read() > >> https_headers = fs.info().headers > >> https_mimetype = fs.info().type > >> > >> -jag > >> > >> > >> > >> Joshua Ginsberg -- joshg at brainstorminternet.net > >> Brainstorm Internet Network Operations > >> 970-247-1442 x131 > >> On Apr 8, 2005, at 2:13 PM, Hasan D wrote: > >> > >>> I'm new on this httplib and urllib. Actually I dont know what should > >>> i > >>> use. > >>> > >>> I want to fill the form in a "https" page , and return the result . I > >>> write a test code but always gives errors. I cant find any good > >>> example about this on the net. What should I do about this ? > >>> > >>> > >>> import urlparse,urllib,httplib,string,htmllib,formatter > >>> > >>> #port="443" > >>> target="https://www.abc.com/" > >>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0}) > >>> http=httplib.HTTP("https://www.abc.com/",443) > >>> > >>> data='Name=x&Adress=x' > >>> headers = {"Content-type": > >>> "application/x-www-form-urlencoded","Accept": "text/plain"} > >>> > >>> print "Sending Data On "+target+"...\n" > >>> http.putrequest("POST",target+"/xxx.asp?q=7&b=11",params) > >>> > >>> response = http.getresponse() > >>> print response.status, response.reason > >>> > >>> http.send(data) > >>> > >>> code,msg,headers = http.getreply() > >>> > >>> print "HTTP Code : ",str(code) > >>> print "HTTP Connection : ",msg > >>> print "HTTP headers : \n",headers,"\n" > >>> > >>> HTML=http.getfile().read() > >>> MyParser=htmllib.HTMLParser(formatter.NullFormatter()) > >>> MyParser.feed(HTML) > >>> # Print all the anchors from the results page > >>> print MyParser.anchorlist > >>> -- > >>> http://mail.python.org/mailman/listinfo/python-list > >>> > >> > >> > >> -- > >> http://mail.python.org/mailman/listinfo/python-list > >> > >> > >> > > > > > > From opengeometry at yahoo.ca Fri Apr 22 02:41:46 2005 From: opengeometry at yahoo.ca (William Park) Date: Fri, 22 Apr 2005 02:41:46 -0400 Subject: XML parsing per record References: Message-ID: Willem Ligtenberg wrote: > On Sun, 17 Apr 2005 02:16:04 +0000, William Park wrote: > > Care to post more details? > > The XML file I need to parse contains information about genes. > So the first element is a gene and then there are a lot sub-elements with > sub-elements. I only need some of the informtion and want to store it in > my an object called gene. Lateron this information will be printed into a > file, which in it's turn will be fed into some other program. You have to help us a little more here. Which info do you want to extract from below example? > > ... > -- William Park , Toronto, Canada Slackware Linux -- because it works. From Scott.Daniels at Acm.Org Wed Apr 20 12:54:00 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 20 Apr 2005 09:54:00 -0700 Subject: pythonic use of properties? In-Reply-To: References: <5e183f3d05041420053ecd0ee@mail.gmail.com> <5e183f3d05041507417d3fa81d@mail.gmail.com> Message-ID: <42668374$1@nntp0.pdx.net> Michael Spencer wrote: > ... of course there are cases where data must be validated. For > data stored in one type, and used in many contexts - I would validate > where stored. If the reverse, then validate at the point it is used... The big exception to this rule is "temporal" -- data used long after storing is a candidate for more validation. This rule applies "in spades" for persistent data (stored in any form of database). The rule is to catch issues where you can figure them out. --Scott David Daniels Scott.Daniels at Acm.Org From eurleif at ecritters.biz Sat Apr 23 17:40:47 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Sat, 23 Apr 2005 21:40:47 GMT Subject: Python or PHP? In-Reply-To: References: <1114254894.512656.297040@l41g2000cwc.googlegroups.com> Message-ID: Mage wrote: > However one of the worst cases is the sql injection attack. And sql > injections must be handled neither by php nor by python but by the > programmer. But Python's DB-API (the standard way to connect to an SQL database from Python) makes escaping SQL strings automatic. You can do this: cursor.execute('UPDATE foo SET bar=%s WHERE id=%s', ["foo'bar", 123]) And "foo'bar" will be implicitly escaped to whatever is appropriate for your database. How's that for Python handling SQL injection automatically? From pfkeb at kunz-pbdsl1.stanford.edu Thu Apr 28 10:08:07 2005 From: pfkeb at kunz-pbdsl1.stanford.edu (Paul F. Kunz) Date: 28 Apr 2005 07:08:07 -0700 Subject: Fast plotting? References: <5bbea$42706a5a$d1b714b9$22961@PRIMUS.CA> Message-ID: <7td5sfxad4.fsf@kunz-pbdsl1.stanford.edu> William Park writes: > Russell E. Owen wrote: > > Can anyone recommend a fast cross-platform plotting package for 2-D > > plots? > > > > Our situation: > > We are driving an instrument that outputs data at 20Hz. Control is via > > an existing Tkinter application (which is being extended for this new > > instrument) that runs on unix, mac and windows. We wish to update 5-10 > > summary plots at approximately 2 Hz and will be offering controls to > > control the instrument and the plots, preferably (but not necessarily) > > mixed in with the plots. > > That's 10-20 plots per second. The only GUI plotter that I know is > 'gnuplot', and I don't know if it will spit out anything at 10-20Hz. > For character plots (like old days terminal), it has speed but ugly to > look at. > HippoDraw is quite fast and scriptable from Python http://www.slac.stanford.edu/grp/ek/hippodraw From codecraig at gmail.com Tue Apr 19 10:02:05 2005 From: codecraig at gmail.com (codecraig) Date: 19 Apr 2005 07:02:05 -0700 Subject: Update Label when Scale value changes In-Reply-To: <9Z79e.969$cL6.77@news.get2net.dk> References: <1113916746.841747.274550@l41g2000cwc.googlegroups.com> <9Z79e.969$cL6.77@news.get2net.dk> Message-ID: <1113919325.498539.323190@o13g2000cwo.googlegroups.com> Yea that is what i needed. Can you recommend a good Tkinter site (or book, but preferably site) about learning Tkinter. I've tried: http://www.python.org/moin/TkInter http://www.pythonware.com/library/tkinter/introduction/ But I am looking for more about events, etc. Thanks From steven.bethard at gmail.com Wed Apr 6 14:28:42 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 06 Apr 2005 12:28:42 -0600 Subject: Semi-newbie, rolling my own __deepcopy__ In-Reply-To: References: <1112629066.785241.275670@z14g2000cwz.googlegroups.com> <1112787265.022988.205630@z14g2000cwz.googlegroups.com> Message-ID: Michael Spencer wrote: > BTW, as I mentioned in a previous comment, I believe this would be more > plainly written as type(self).__new__(), to emphasize that you are > constructing the object without initializing it. (There is a > explanation of __new__'s behaviour at > http://www.python.org/2.2/descrintro.html#__new__). There is also now documentation in the standard location: http://docs.python.org/ref/customization.html And just to clarify Michael's point here, writing this as __new__ means that __init__ is not called twice: py> class C(object): ... def __new__(cls): ... print '__new__' ... return super(C, cls).__new__(cls) ... def __init__(self): ... print '__init__' ... py> c = C() __new__ __init__ py> c2 = type(c)(); c2.__init__() __new__ __init__ __init__ py> c3 = type(c).__new__(C); c3.__init__() __new__ __init__ But definitely check the docs for more information on __new__. Some of the interworkings are kind of subtle. STeVe From bokr at oz.net Wed Apr 13 06:19:31 2005 From: bokr at oz.net (Bengt Richter) Date: Wed, 13 Apr 2005 10:19:31 GMT Subject: Compute pi to base 12 using Python? References: Message-ID: <425cefae.268278123@news.oz.net> On Wed, 13 Apr 2005 02:06:11 -0700, Dick Moores wrote: >I need to figure out how to compute pi to base 12, to as many digits as >possible. I found this reference, >, but I really don't understand >it well enough. Could someone show me how to do what I need? > >Thanks, > >Dick Moores >rdm at rcblue.com > See if this is enough digits for homework? ;-) (Digits A and B are 10 and 11 in decimal respectively) 3184809493B918664573A6211BB151551A05729290A7809A492742140A60A55256A0661A03753A3AA54805646880181A 3683083272BBBA0A370B12265529A828903B4B256B8403759A71626B8A54687621849B849A8225616B442796A31737B2 29B2391489853943B8763725616447236B027A421AA17A38B52A18A838B01514A51144A23315A3009A8906B61B8B48A6 2253A88A50A43BA0944572315933664476B3AABB77583975120683526B75B462060BB03B432551913772729A21475535 31793848A0402B999B5058535374465A68806716644039539A8431935198527B9399B112990ABB0383B107645424577A 51601B3624A88B7A676A3992912121A213887B92873946A61332242217AA7354115357744939112602BA4B888818A326 9222B528487747839994AB223B65B8762695422822669BA00A586097842A51750362073B5A768363B21BB1A97A4A1944 47749399804922175A068A46739461990A2065BB0A30BBAB7024A585B1A84428195489784A07A331A7B0A1574565B373 B05B03A5A80A13AB87857734679985558A5373178A7B28271992A3894A5776085083B9B238B2220542462888641A2BAB 8B3083AB49659172A312B78518654494A068662586A181835A64440B2970A12281397589881536720890580103288144 9223841428763329617531239B9A657405584014534390B587625606BB80923795944B43757A431B039556282978A6A4 9590553490BA1844947175637A908247B50127722464441380A852B0847B5813019BB70A67663B426565434069884476 132193344BA55A2128A03838974606B851B2979321A408067225A5AA4B3464A1A17473595333909AB9127079655B3164 B68B9B28A9B818A220A025AB0934203995B7A62A7AA739355340539BA3182905B193905603A43B660B9426A922946971 44A896A5B2339358BB2B7294BB89635B071A6351211360B820B1882AB8433B54757B87A373284B1BA182A10326476B36 9A4A6365B58B8018994BB152556765475A704BB94B6B2A39458971A8B90512786B5029404818644323552916170B3ABB 7363496427B088B68725A68570040617949289077B278069A09B559324B8A66828B40549B0296065B2300330592569A7 B76B92BA1293585B6A9B604567A0901362856373B4B56897946256B4172B1B50474351364749A33996A81BA8847347A8 411B850B79A03018291672AA0945656A159AA6AA0A845531A592005B8A34366B882257107B190969A846474836A98007 50778920BA797297A2791101B0685A86BB704B9BAA17B055293679843B35215B0A8B1182B611953B080AA5431B219907 A8448A81B1A9493245676B88013B470335240859594158621014216619553246570601967448B470174B924489244481 7453865A4003B5AA7176451AAB90681A949786154AA040477382BA69371041710B8728458A23979252B254236753A44A 1900AA283536A227648812525743868B410A567794663359A6726A5286783328135114789B7645505B047848020A730A 9557B206776AA56A19682744107901306B29008808619866B4911A05264B872A46B5376383932699531B449195640B62 A63622830886247A47B3957169861239358041AA281333622AA15912B0A636047A489BB0726282A78B96671B27305A96 52496B9B999011A7BA36898891665B1A6009058978850A21B01A158A1473B84A192B8672542A2A7056581995207A436A 5B3BA2824637A3112ABB57176468206A071200A327B3216425148100786502AA21236ABB35499277670A126973058340 3B1922A483856007301983989159BB688A58B602339806B63002A339A50B0BA533B84827793913081070A32595A10180 3A9A20234691B1A0B623274B69B0B44688195169461059543A252BB05208720BA13118266A872B26B9B584959B451795 19534B221A335A2BB6971B3276B3A63A5B791723109B176529BB90651584279B7825712521B8269800738B07A62B1454 7884414451224092937165625696557A78799A82126613535A36B410309B759976119777B895801074B9779B9B513753 8B2799951012273399BB818B721967957713B90947B2A11A6A665848B22B531726616515939323229080B8AB574AA749 4773AB411A57150203067A112944833235A86153803A98689A0762B79835413A46B347888A4AAB259665694B93129B62 1391751430A98B002620718437A7B85B891179479651AA3410663715415B55BA47AA59465AB81567B7655780A8038135 85230122578485B071A529692B19A6537B28616A63556816945380634A90470354AAB303884B7B09B2037B95405BA145 704B19B14AA8028810881AB6072441194A875477836B37704B5199062319A336375437403562A663B835B891957883AB Hint: Lambert Meertens. Tweak the algorithm you find ;-) Regards, Bengt Richter From steven.bethard at gmail.com Wed Apr 13 23:04:58 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 13 Apr 2005 21:04:58 -0600 Subject: sort of a beginner question about globals In-Reply-To: <1113434483.437663.206030@f14g2000cwb.googlegroups.com> References: <1113354531.380490.81190@z14g2000cwz.googlegroups.com> <3aOdnX8D67t5PcHfRVn-qQ@comcast.com> <1113403451.556360.116630@f14g2000cwb.googlegroups.com> <1113405724.301516.232000@f14g2000cwb.googlegroups.com> <6v-dnV7CJ7WZocDfRVn-oA@comcast.com> <1113422470.180010.172970@z14g2000cwz.googlegroups.com> <1113434483.437663.206030@f14g2000cwb.googlegroups.com> Message-ID: fred.dixon wrote: > #global1.py > import global2 > import global3 > import sys > > constant = 'dumb' > option = sys.argv[1:] > pass > #global2.func1() > a=global2.class1() > a.func1() > print newvar > > #global2.py > import __main__ > pass > class class1: > def func1(self): > __main__.newvar = "string" > pass The other ways of getting this behavior would be to write global2.py as: class class1: def func1(self): global newvar newvar = "string" or class class1: def func1(self): globals()["newvar"] = "string" or class class1: def func1(self): __import__(__name__).newvar = "string" I don't know which of these is really preferred. Generally if I see myself writing code like this, I figure I probably need to refactor things. STeVe P.S. Why are you writing all those 'pass' statements? They're not necessary in any of the locations you've placed them. From sarir.khamsi at raytheon.com Fri Apr 8 19:11:41 2005 From: sarir.khamsi at raytheon.com (Sarir Khamsi) Date: Fri, 08 Apr 2005 16:11:41 -0700 Subject: sending signals to child process References: Message-ID: "Diez B. Roggisch" writes: > Sarir Khamsi wrote: > >> I would like to start a child process (like w/ popen3(), or some such) >> and then be able to interrupt it by sending it a control-c. How do I >> do that in Python? Is there a better way to gracefully halt a child > > Use os.kill and the signal module. > >> process? Is there a more cross-platform way to start a child process >> (popen() is only on UNIX/Win32)? Thanks. > > In python2.4 there is the subprocess module. This is what I was looking for...thanks. Sarir From tjreedy at udel.edu Sun Apr 3 19:09:32 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 3 Apr 2005 19:09:32 -0400 Subject: Help me dig my way out of nested scoping References: <1112562768.181026.180140@l41g2000cwc.googlegroups.com> Message-ID: "Brendan" wrote in message news:1112562768.181026.180140 at l41g2000cwc.googlegroups.com... > I have a function, call it F(x), which asks for two > other functions as arguments, say A(x) and B(x). ... If I understand this and the rest, a third party library whose code you cannot modify (easily) has a function F with (at least) three parameters: A, B, and x. During its operation, F calls A(x) and B(x). Because of code commonality for the particular A and B arg funcs you want to feed to F, you want avoid duplication by having the first call to either to calculate both return values. If F calls each of A and B exactly once and always in the same order and only for the value x you supply, the solution is pretty easy. A calls AB, stashes the B value away where it can be retrieved, and return the A value. B retrieves the B value and returns it. But your problem is the stash and retrieve part. Solutions: 1. global variable (easiest) - use global declaration in A; 2. closure variable - use mutable such as 1 element list (see below); 3. instance attribute - with A and B as methods. 2 is what you tried to do, but without knowing the mutable (list or dict) trick: def ABwrapper(): bsave = [None] def A(x): aval,bval = AB(x) bsave[0] = bval return aval def B(x): return bsave[0] return A,B This works because A does not try to *rebind* bsave to a new object. It only mutates the existing object. If the order of calling changes, you need more logic. If F calls A and B on multiple 'x's, as with, for instance, a derivative approximizer, then I would memoize A and/or B using the recipe posted here more than once and on the cookbook site and included in the new Python Cookbook v2 (and maybe v1, don't have it). Terry J. Reedy From serpent17 at gmail.com Sun Apr 17 14:37:48 2005 From: serpent17 at gmail.com (serpent17 at gmail.com) Date: 17 Apr 2005 11:37:48 -0700 Subject: Problem with unpack hex to decimal Message-ID: <1113763068.002612.240940@l41g2000cwc.googlegroups.com> Hello, I was looking at this: http://docs.python.org/lib/module-struct.html and tried the following >>> import struct >>> struct.calcsize('h') 2 >>> struct.calcsize('b') 1 >>> struct.calcsize('bh') 4 I would have expected >>> struct.calcsize('bh') 3 what am I missing ? Thanks in advance, Jake. From kent37 at tds.net Thu Apr 21 07:58:14 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 21 Apr 2005 07:58:14 -0400 Subject: Python instances In-Reply-To: <426776fa.134053138@news.oz.net> References: <1113982340.156937.75530@f14g2000cwb.googlegroups.com> <1113983093.813565.23430@l41g2000cwc.googlegroups.com> <426647ea$1_3@newspeer2.tds.net> <426776fa.134053138@news.oz.net> Message-ID: <4267910f$1_3@newspeer2.tds.net> Bengt Richter wrote: > The following shows nothing static anywhere, yet a class has been defined, an instance created, and > __init__ called with initial value, and the value retrieved as an attribute of the returned instance, > and it's all an expression. > > >>> type('C', (), {'__init__': lambda self,v:setattr(self,'foo',v)})('hello').foo > 'hello' I have no idea what point you are trying to make, except maybe that it is possible to obfuscate a simple class definition. Kenw From skip at pobox.com Mon Apr 18 23:03:00 2005 From: skip at pobox.com (Skip Montanaro) Date: Mon, 18 Apr 2005 22:03:00 -0500 Subject: Wrapping C++ Class Heirachy in Python In-Reply-To: References: Message-ID: <16996.29924.640079.430476@montanaro.dyndns.org> Roy> I've been playing around with ctypes Roy> (http://starship.python.net/crew/theller/ctypes/) recently. So Roy> far, it looks pretty cool. Wrapping C++ libraries? Skip From mcassiano at gmail.com Tue Apr 26 12:06:24 2005 From: mcassiano at gmail.com (Marco Cassiano) Date: Tue, 26 Apr 2005 18:06:24 +0200 Subject: Shelve problem with Python 2.3.4 on RHEL 3 AS Message-ID: <72bcfd7505042609061cadeb28@mail.gmail.com> I installed python 2.3.4 on my system with configure/make/make altinstall in order to preserve the original python installation of RHEL3. I have the following error entering these few python lines : Python 2.3.4 (#3, Apr 26 2005, 14:48:36) [GCC 3.2.3 20030502 (Red Hat Linux 3.2.3-49)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import shelve >>> fl='/tmp/test.shelve' >>> dbase=shelve.open(fl) Traceback (most recent call last): File "", line 1, in ? File "/usr/local/lib/python2.3/shelve.py", line 231, in open return DbfilenameShelf(filename, flag, protocol, writeback, binary) File "/usr/local/lib/python2.3/shelve.py", line 212, in __init__ Shelf.__init__(self, anydbm.open(filename, flag), protocol, writeback, binar y) File "/usr/local/lib/python2.3/anydbm.py", line 83, in open return mod.open(file, flag, mode) File "/usr/local/lib/python2.3/dbhash.py", line 16, in open return bsddb.hashopen(file, flag, mode) File "/usr/local/lib/python2.3/bsddb/__init__.py", line 192, in hashopen d.open(file, db.DB_HASH, flags, mode) bsddb._db.DBError: (38, 'Function not implemented -- DB_ENV->dbremove: method not permitted before open') And typing it again I get : >>> dbase=shelve.open(fl) Exception exceptions.AttributeError: "DbfilenameShelf instance has no attribute 'writeback'" in ignored Traceback (most recent call last): File "", line 1, in ? File "/usr/local/lib/python2.3/shelve.py", line 231, in open return DbfilenameShelf(filename, flag, protocol, writeback, binary) File "/usr/local/lib/python2.3/shelve.py", line 212, in __init__ Shelf.__init__(self, anydbm.open(filename, flag), protocol, writeback, binary) File "/usr/local/lib/python2.3/anydbm.py", line 83, in open return mod.open(file, flag, mode) File "/usr/local/lib/python2.3/dbhash.py", line 16, in open return bsddb.hashopen(file, flag, mode) File "/usr/local/lib/python2.3/bsddb/__init__.py", line 192, in hashopen d.open(file, db.DB_HASH, flags, mode) bsddb._db.DBError: (38, 'Function not implemented -- process-private: unable to initialize environment lock: Function not implemented') If I did it with the standard Python 2.2.3 it works perfectly . The problem is I need Python 2.3.4 on my system... Could you give me any advice ? Thank you Marco Cassiano -- Marco Cassiano Italy email : mcassiano at manord.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From mefjr75 at hotmail.com Mon Apr 18 00:28:18 2005 From: mefjr75 at hotmail.com (M.E.Farmer) Date: 17 Apr 2005 21:28:18 -0700 Subject: Compute pi to base 12 using Python? In-Reply-To: References: <7x3btui27t.fsf@ruckus.brouhaha.com> <1113545886.372148.82420@z14g2000cwz.googlegroups.com> <4262261c.159801732@news.oz.net> Message-ID: <1113798498.092249.5320@g14g2000cwa.googlegroups.com> >>PS. Redirecting with > from a script whose interpreter was started by >>windows extension association >>doesn't work on some version of windows. To be safe, invoke the >>interpreter explicitly, e.g., >> python myscript.py [whatever args here] > pi3003.txt >Thanks very much for this. >What kind of args could I use here? Any that your script allows or understands. an example: python c:/Python22/Lib/PySourceColor.py -i- -s -l < c:/MyFile.py > c:/tmp/myfile.html A few things that might help you write a well behaved script: if sys.stdin.isatty(): "direct" else: "redirected" This snippet can determine if you have redirected IO. I just found this and it looks informative. http://www.jpsdomain.org/windows/redirection.html hth, M.E.Farmer From martin at v.loewis.de Wed Apr 6 16:33:38 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 06 Apr 2005 22:33:38 +0200 Subject: Erroneous line number error in Py2.4.1 [Windows 2000+SP3] In-Reply-To: <1112794029.667294.134370@f14g2000cwb.googlegroups.com> References: <1112794029.667294.134370@f14g2000cwb.googlegroups.com> Message-ID: <425447A2.2070508@v.loewis.de> Timo wrote: > Does anyone have a clue what is going on? No. Please make a bug report to sf.net/projects/python. Regards, Martin From kent37 at tds.net Sun Apr 17 11:44:23 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 17 Apr 2005 11:44:23 -0400 Subject: sscanf needed In-Reply-To: References: Message-ID: <42628025_3@newspeer2.tds.net> Uwe Mayer wrote: > Hi, > > I've got a ISO 8601 formatted date-time string which I need to read into a > datetime object. Something like this (adjust the format to suit): import datetime, time dt = datetime.datetime(*time.strptime(data, "%Y-%m-%d %H:%M:%S")[:6]) Kent From eurleif at ecritters.biz Sat Apr 23 07:59:48 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Sat, 23 Apr 2005 11:59:48 GMT Subject: Python or PHP? In-Reply-To: <1114254894.512656.297040@l41g2000cwc.googlegroups.com> References: <1114254894.512656.297040@l41g2000cwc.googlegroups.com> Message-ID: Lad wrote: > Is anyone capable of providing Python advantages over PHP if there are > any? Python is a programming language in more ways than simple Turing completeness. PHP isn't. From RonGrossi Tue Apr 19 12:03:02 2005 From: RonGrossi (RonGrossi) Date: 19 Apr 2005 11:03:02 -0500 Subject: Do You Want To Know For Sure That You Are Going To Heaven? The reason some people don't know for sure if they are going to Heaven when they die is because they just don't know. The good news is that you can know for sure that you are going to Heaven which is described in the Holy Bible as a beautiful place with no death, sorrow, sickness or pain. (newsgroup-post 142) References: <1113925283.115755.202120@f14g2000cwb.googlegroups.com> Message-ID: !! From steve at holdenweb.com Sun Apr 24 19:03:39 2005 From: steve at holdenweb.com (Steve Holden) Date: Sun, 24 Apr 2005 19:03:39 -0400 Subject: Python or PHP? In-Reply-To: <3d04e3F6pjhi5U1@individual.net> References: <1114254894.512656.297040@l41g2000cwc.googlegroups.com> <3d04e3F6pjhi5U1@individual.net> Message-ID: Leif Biberg Kristensen wrote: > Leif K-Brooks skrev: > > >>But Python's DB-API (the standard way to connect to an SQL database >>from Python) makes escaping SQL strings automatic. You can do this: >> >>cursor.execute('UPDATE foo SET bar=%s WHERE id=%s', ["foo'bar", 123]) > > > So. I've been writing SQL queries in Python like this, using PostgreSQL > and psycopg: > > cursor.execute("select * from foo where bar=%s" % baz) > > Is that wrong, and how should I have been supposed to know that this is > bad syntax? No doc I have seen actually has told me so. It's *wrong* for some value of "wrong" - it does potentially introduce a SQL injection vulnerability into your code. Suppose I provide as input into the baz variable 1; drop table foo Your statement then becomes select * from foo where bar=1; drop table foo which is clearly not such a good idea. More sophisticated attackes are possible, but this gives you the idea. regards Steve -- Steve Holden +1 703 861 4237 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ From bill.mill at gmail.com Thu Apr 14 11:50:22 2005 From: bill.mill at gmail.com (Bill Mill) Date: Thu, 14 Apr 2005 11:50:22 -0400 Subject: A little request about spam In-Reply-To: References: <1113416856.914310.63930@l41g2000cwc.googlegroups.com> <740c3aec05041405157cb90625@mail.gmail.com> <7ee3dcd80504140551385ce25e@mail.gmail.com> Message-ID: <797fe3d405041408506aab4d13@mail.gmail.com> On 4/14/05, C?sar Leonardo Blum Silveira wrote: > Yeah that is happening to me too! Almost all my python-list e-mails go > to the Spam box. > Maybe we should contact the gmail admins? > I've already contacted the gmail admins. There was no response. Peace Bill Mill bill.mill at gmail.com > On 4/14/05, mark hellewell wrote: > > On 4/14/05, James wrote: > > > Yes - it's been like that for the last month or so now and it's quite > > > annoying, especially seeing as before it was working at near enough > > > 100% accuracy. > > > > And I don't suppose there's much we can do about it? > > > > mark > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > -- > http://mail.python.org/mailman/listinfo/python-list > From bokr at oz.net Fri Apr 29 21:37:20 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 30 Apr 2005 01:37:20 GMT Subject: Micro-PEP: str.translate(None) to mean identity translation Message-ID: <4272e00c.260731842@news.oz.net> Just thought None as the first argument would be both handy and mnemonic, signifying no translation, but allowing easy expression of deleting characters, e.g., s = s.translate(None, 'badcharshere') Regards, Bengt Richter From secun at yahoo.com Wed Apr 27 22:42:37 2005 From: secun at yahoo.com (ChrisH) Date: Thu, 28 Apr 2005 02:42:37 GMT Subject: pyqt and Eric 3 Message-ID: Are there any Eric 3 users out there? I've been thinking about trying it. Also, if I write scripts for internal use only at my company, do I have to purchase a Qt or pyqt license? Thanks for the info! Chris From j at b.com Sun Apr 10 07:57:28 2005 From: j at b.com (Charlie9) Date: Sun, 10 Apr 2005 11:57:28 GMT Subject: =?iso-8859-1?q?Re=3A_THE_GREATEST_NEWS_EVER_!_=B0=BA=B7=2E=2E=2E?= =?iso-8859-1?q?=B7=B0=60=B0=BA=B7=2E=2E=2E=B7=B0=60=B0=BA=B7=2E=2E?= =?iso-8859-1?q?=2E=B7=B0=60=B0=BA=B7=2E=2E=2E=B7=B0=60=B0=BA=B7=2E?= =?iso-8859-1?q?=2E=2E=B7=B0=60=B0=BA=B7=2E=2E=2E=B7=B0=60=B0=BA=B7?= =?iso-8859-1?q?=2E=2E=2E=B7=B0=60=B0=BA=B7=2E=2E=2E=B7=B0=60=B0=BA?= =?iso-8859-1?q?=B7=2E=2E=2E=B7=B0=60=B0=BA=B7=2E=2E=2E=B7=B0=60=B0?= =?iso-8859-1?q?=BA=B7=2E=2E=2E=B7=B0=60=B0=BA=B7=2E=2E=2E=B7=B0=60?= =?iso-8859-1?q?=B0=BA=B7=2E=2E=2E=B7=B0=60=B0=BA=B7=2E=2E=2E=B7=B0?= =?iso-8859-1?q?=60=B0=BA=B7=2E=2E=2E=B7=B0=60=B0=BA=B7=2E=2E=2E=B7?= =?iso-8859-1?q?=B0=60=B0=BA=B7=2E=2E=2E=B7=B0=60=B0=BA=B7=2E=2E=2E?= =?iso-8859-1?q?=B7=B0=60=B0=BA=B7=2E=2E=2E=B7=B0=60=B0=BA=B7=2E=2E?= =?iso-8859-1?q?=2E=B7=B0=60=B0=BA=B7=2E=2E=2E=B7=B0=60=B0=BA=B7=2E?= =?iso-8859-1?q?=2E=2E=B7=B0=60=B0=BA=B7=2E=2E=2E=B7=B0=60=B0=BA=B7?= =?iso-8859-1?q?=2E=2E=2E=B7=B0=60_=28new?= References: <1113068396.414326.217300@o13g2000cwo.googlegroups.com> <1113074212.618866.24620@f14g2000cwb.googlegroups.com> <2hW5e.31873$hU7.19808@newssvr33.news.prodigy.com> <9dd7f022.0504092036.51bd14ca@posting.google.com> Message-ID: On 9 Apr 2005 21:36:06 -0700, anthonyjhcnospam at netscape.net (Anthony) wrote: >I thought 'The Greatest News Ever' might mean something serious like >transfer of the classic Beatles albums to SACD. >But no, it's just religious crap. Now that the Pope's dead, do you >think we could declare christianity officially extinct? Please? The Pope is not dead. The man who filled the position is dead. There will be another man. From ajikoe at gmail.com Mon Apr 18 08:31:25 2005 From: ajikoe at gmail.com (ajikoe at gmail.com) Date: 18 Apr 2005 05:31:25 -0700 Subject: Strings and Lists In-Reply-To: References: Message-ID: <1113827485.685341.79540@f14g2000cwb.googlegroups.com> Hello Tom, I think it is more efficient if we can use list (with True,False) member to do genetics algorithms. Of course a lot of works to do to change from string binary into boolean list. I do programming genetics algorithms in C# I guess I have to modify my program also because my old program use binary string manipulation. Sincerely Yours, Pujo From franz.steinhaeusler at utanet.at Tue Apr 5 04:52:42 2005 From: franz.steinhaeusler at utanet.at (Franz Steinhaeusler) Date: Tue, 05 Apr 2005 10:52:42 +0200 Subject: Eric3 under WinXP References: Message-ID: On Tue, 5 Apr 2005 09:17:05 +0100 (BST), "Phil Thompson" wrote: >> Hello NG, >> >> (Win XP) >> >> I have successfully installed pyqt, but not >> qtext, which I need to run Eric3. >> The PyQT demo files run fine. >> >> I've downloaded QScintilla, compiled via MS-VC, >> but (I suppose I need the SIG), to translate or provide >> the Python interface with pyd Files. >> >> Eric complains, that qtext is not found. >> >> Has anyone success with getting this to work and how? >> >> Many thanks in advance for possible answers, > >You haven't said which version of PyQt you are using. I guess it's the >non-commercial version based on Qt v2 - QScintilla (and therefore eric) >requires Qt v3. > >Phil Hello John and Phil, thank you for your answers. I have: PyQt 3.13 Qt v2.3 Non-commercial Edition I compiled: qscintilla-1.62-gpl-1.5.1\ and the results seems ok qmake qscintilla.pro nmake for the qmake, I downloaded: Qt 3.3.4 Evaluation I installed also SIP. sip-4.2.1 What steps are missing? thank you again -- Franz Steinh?usler http://drpython.sourceforge.net/ http://mitglied.lycos.de/drpython/ From bvande at po-box.mcgill.ca Tue Apr 12 12:33:40 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Tue, 12 Apr 2005 12:33:40 -0400 Subject: variables exist In-Reply-To: References: <9622d535.0504110552.1e070e8d@posting.google.com> Message-ID: <425BF864.3060605@po-box.mcgill.ca> Richard Brodie said unto the world upon 2005-04-12 04:56: > "Brian van den Broek" wrote in message > news:mailman.1703.1113237192.1799.python-list at python.org... > > >>I'm a hobbyist and still learning, but the claim the try/except is >>"lousy Python" surprise me a bit. > > > I think it wasn't the use of try/except as such. It's more that > if you're the developer you ought to know whether variables > are defined or not. It might be a sign you're using global > variables more often than would be considered good style in > Python. Richard and STeVe, thanks for the replies :-) I see your point, Richard. Though where it has come up for me most often is code internal to a class, where I only need a "real" value for a class attribute in some cases, depending upon the inputs to the class __init__. "Globals are bad" is one lesson I have learned :-) STeVe stressed that the try/except solution is only really appropriate for cases where the failure to have the variable defined is quite rare. Even though wary of "the root of all evil ... " that seems a good reminder. Thanks. Best to all, Brian vdB From auch-ich-m at g-kein-spam.com Wed Apr 6 11:08:33 2005 From: auch-ich-m at g-kein-spam.com (=?UTF-8?B?QW5kcsOp?= Malo) Date: Wed, 06 Apr 2005 17:08:33 +0200 Subject: regexp weirdness (bug?) References: <1112715308.737856.234580@z14g2000cwz.googlegroups.com><2584344.b1EHUGjtUV@news.perlig.de><1186100.a9ONk7P8cn@news.perlig.de> <1112781872.088784.129280@g14g2000cwa.googlegroups.com> Message-ID: <1534368.LanBPdd5dR@news.perlig.de> * Fredrik Lundh wrote: > Sergey Schetinin wrote: > >> it's line #159 here, but it did work! thanks. so it IS a bug? > > sure looks like one. please report it here: > > http://sourceforge.net/tracker/?group_id=5470&atid=105470 done :) nd -- "Das Verhalten von Gates hatte mir bewiesen, dass ich auf ihn und seine beiden Gef?hrten nicht zu z?hlen brauchte" -- Karl May, "Winnetou III" Im Westen was neues: From duncan.booth at invalid.invalid Thu Apr 28 08:20:07 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 28 Apr 2005 12:20:07 GMT Subject: Setting win32 console title from Python References: <1114684215.236448.212970@g14g2000cwa.googlegroups.com> Message-ID: runes wrote: > I'm trying to set the title of the console window (CMD.EXE) in Windows. > I want it set to the basename of the current directory and it should > stay after the script has finished. > > Any ideas? > I don't think you can do that. Whenever you start an application from the command prompt the title is modified by appending a dash and the name of the program you started. When the application terminates the title is reset (to remove the name of the running program). So any change to the title will only last until the next time CMD.EXE prompts for input. The exception is that any title set using the TITLE command becomes the reset title for that command prompt. I can think of only one way round this, which is to run your python program from a batch file and find some way to pass the desired title back to the batch file where you can set it with the TITLE command. For example, you could write the title to a temporary file, or if your program doesn't produce much other output print it to stdout and parse the program output using a for command: e.g. This sets the title to the current time: C:\>FOR /F "tokens=*" %i in ( More? 'python -c "from time import *; print asctime(localtime())"' More? ) DO @TITLE %i C:\> Obvious notes: In a batch file you would double the % characters, and you don't type C:\> or More? as these are the prompts from CMD.EXE. Also this won't work on really old versions of CMD.EXE or with COMMAND.COM. From fredrik at pythonware.com Fri Apr 22 17:04:46 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 22 Apr 2005 23:04:46 +0200 Subject: handling tar, gz and bz2 with python References: Message-ID: Matthew Thorley wrote: > Is there a module for unpacking tar files in python? >>> import tarfile >>> help(tarfile) ... | open(cls, name=None, mode='r', fileobj=None, bufsize=10240) from __built in__.type | Open a tar archive for reading, writing or appending. Return | an appropriate TarFile class. | | mode: | 'r' open for reading with transparent compression | 'r:' open for reading exclusively uncompressed | 'r:gz' open for reading with gzip compression | 'r:bz2' open for reading with bzip2 compression | 'a' or 'a:' open for appending | 'w' or 'w:' open for writing without compression | 'w:gz' open for writing with gzip compression | 'w:bz2' open for writing with bzip2 compression | 'r|' open an uncompressed stream of tar blocks for reading | 'r|gz' open a gzip compressed stream of tar blocks | 'r|bz2' open a bzip2 compressed stream of tar blocks | 'w|' open an uncompressed stream for writing | 'w|gz' open a gzip compressed stream for writing | 'w|bz2' open a bzip2 compressed stream for writing | | taropen(cls, name, mode='r', fileobj=None) from __builtin__.type | Open uncompressed tar archive name for reading or writing. ... > how about bzip2 and gzips? I know I can use the gzip module for gzips > but is there anything that can detect what format a file is in and decopress > and unpack it using the other methods? see above. From jaywgraves at gmail.com Thu Apr 21 15:54:09 2005 From: jaywgraves at gmail.com (jay graves) Date: 21 Apr 2005 12:54:09 -0700 Subject: recording data between [ and ] References: <1114111155.408043.291950@o13g2000cwo.googlegroups.com> Message-ID: <1114113249.117750.223000@o13g2000cwo.googlegroups.com> bearophileH... at lycos.com wrote: > Beside rxb15, there is also redict, in the standard lib (Jay Graves > shows the HD path): > http://home.earthlink.net/~jasonrandharper/reverb.py I knew there was a newer one out there but my google skills failed me. Thanks for the link. From radam2 at tampabay.rr.com Fri Apr 1 15:32:36 2005 From: radam2 at tampabay.rr.com (Ron_Adam) Date: Fri, 01 Apr 2005 20:32:36 GMT Subject: Pseudocode in the wikipedia References: <1112362451.848227.208120@z14g2000cwz.googlegroups.com> Message-ID: On Fri, 1 Apr 2005 12:15:35 -0800, James Stroud wrote: >Is anybody else bothered by those stupid pascal-like ":=" assignment >operators? > >Maybe, for the sake of adding more variety to the world, wiki should come up >with a new assignment operator, like "==". I like that one because then it >could really be original: > >if (bob = 4): > bob == bob + 2 To me ":=" could mean to create a copy of an object... or should it be "=:" ? Or how about ":=)" to mean is equal and ":=(" to mean it's not. Then there is ";=)", to indicate 'True', and ':=O' to indicate 'False' From tehom at REMOVEpanNOSPAMix.com Fri Apr 1 19:47:58 2005 From: tehom at REMOVEpanNOSPAMix.com (Tom Breton) Date: 01 Apr 2005 19:47:58 -0500 Subject: Lambda: the Ultimate Design Flaw References: Message-ID: Daniel Silva writes: [...] > So now FOLD. This is actually the one we've always hated most, > because, apart from a few examples involving + or *, almost every time > we see a FOLD call with a non-trivial function argument, we have to > grab pen and paper and imagine the *result* of a function flowing back > in as the *argument* to a function. Plus, there are *more* arguments > coming in on the side! This is all absurdly complicated. Because > almost all the examples of FOLD we found in practice could be written > as a simple loop with an accumulator, this style should be preferred, > perhaps with us providing a simple helper function to abstract away > the boilerplate code. At any rate, FOLD must fold. Couldn't you leave it in for just another month? And during the remaining month, we'll just call it the "APRIL FOLD". -- Tom Breton, the calm-eyed visionary From saravanand at vsnl.net Mon Apr 25 09:04:19 2005 From: saravanand at vsnl.net (Saravanan) Date: 25 Apr 2005 06:04:19 -0700 Subject: Exception in Python 2.3.3 Interpreter Message-ID: <1114434259.853654.272420@z14g2000cwz.googlegroups.com> Hello, Im running Python Application as a Windows Service (using windows extensions). But, sporadically the application crashes (crash in Python23.dll) and this stops the service. This problem cann't be reproduced easily in my system and the call stack generated by the application is given below. Occurrence: 2005/4/22 23:24:57 Process Id: 3072 Process Name : D:\Python23\lib\site-packages\win32\PythonService.exe Thread Id: 292 Exception code: C0000005 ACCESS_VIOLATION Fault address: 1E05C202 01:0005B202 C:\WINDOWS\system32\python23.dll Registers: EAX:1E0E2EAC EBX:00732EA8 ECX:1E03E500 EDX:016EC200 ESI:00000000 EDI:00732EA8 CS:EIP:001B:1E05C202 SS:ESP:0023:025FFA3C EBP:00637470 DS:0023 ES:0023 FS:003B GS:0000 Flags:00010246 Call stack: Address Frame 1E05C202 00637470 0001:0005B202 C:\WINDOWS\system32\python23.dll 016EC29C 00000003 0000:00000000 The thread which throws the exception is from the Python-Core and not from the application logic. The above call stack points to PyObject_Compare function in object.c. Any clue about the problem? Thanks in Advance. Saravanan D From jaywgraves at gmail.com Thu Apr 14 17:23:59 2005 From: jaywgraves at gmail.com (jay graves) Date: 14 Apr 2005 14:23:59 -0700 Subject: changing colors in python References: <1113511856.510914.103960@z14g2000cwz.googlegroups.com> Message-ID: <1113513839.557906.32890@l41g2000cwc.googlegroups.com> AFAIK, the cmd.exe program on Win2K/XP doesn't support ANSI escape sequences. There are various other options on windows but they probably won't work on Linux. http://newcenturycomputers.net/projects/wconio.html http://effbot.org/zone/console-handbook.htm From tim at tt1lock.org Sun Apr 10 03:34:02 2005 From: tim at tt1lock.org (Tim Tyler) Date: Sun, 10 Apr 2005 07:34:02 GMT Subject: Are circular dependencies possible in Python? References: Message-ID: Marc 'BlackJack' Rintsch wrote or quoted: > In , Tim Tyler wrote: > > Like C, Python seems to insist I declare functions before calling > > them - rather than, say, scanning to the end of the current script > > when it can't immediately find what function I'm referring to. > > They don't have to be declared but to be *defined* in Python before you > can call them. [...] That makes three of you who have called me on my use of "declare". AFAICT, I was using the standard dictionary definition of this word: http://dictionary.reference.com/search?q=declare The term "declare" doesn't have the same meaning as the term "predeclare". -- __________ |im |yler http://timtyler.org/ tim at tt1lock.org Remove lock to reply. From ptmcg at austin.rr.com Tue Apr 26 06:02:07 2005 From: ptmcg at austin.rr.com (Paul McGuire) Date: 26 Apr 2005 03:02:07 -0700 Subject: Quote-aware string splitting References: <9Kgbe.24031$h6.523@tornado.texas.rr.com> Message-ID: <1114507799.131989.307760@f14g2000cwb.googlegroups.com> Quoted strings are surprisingly stateful, so that using a parser isn't totally out of line. Here is a pyparsing example with some added test cases. Pyparsing's quotedString built-in handles single or double quotes (if you don't want to be this permissive, there are also sglQuotedString and dblQuotedString to choose from), plus escaped quote characters. The snippet below includes two samples. The first 3 lines give the equivalent to other suggestions on this thread. It is followed by a slightly enhanced version that strips quotation marks from any quoted entries. -- Paul (get pyparsing at http://pyparsing.sourceforge.net) ========== from pyparsing import * test = r'''spam 'it don\'t mean a thing' "the life of brian" 42 'the meaning of "life"' grail''' print OneOrMore( quotedString | Word(printables) ).parseString( test ) # strip quotes during parsing def stripQuotes(s,l,toks): return toks[0][1:-1] quotedString.setParseAction( stripQuotes ) print OneOrMore( quotedString | Word(printables) ).parseString( test ) ========== returns: ['spam', "'it don\\'t mean a thing'", '"the life of brian"', '42', '\'the meaning of "life"\'', 'grail'] ['spam', "it don\\'t mean a thing", 'the life of brian', '42', 'the meaning of "life"', 'grail'] From daniel.dittmar at sap.corp Fri Apr 1 08:30:24 2005 From: daniel.dittmar at sap.corp (Daniel Dittmar) Date: Fri, 01 Apr 2005 15:30:24 +0200 Subject: Case-insensitive dict, non-destructive, fast, anyone? In-Reply-To: References: Message-ID: Ville Vainio wrote: >>>>>>"Daniel" == Daniel Dittmar writes: > > > Daniel> Ville Vainio wrote: > > >> I need a dict (well, it would be optimal anyway) class that > >> stores the keys as strings without coercing the case to upper > >> or lower, but still provides fast lookup (i.e. uses hash > >> table). > > Daniel> Store the original key together with the value and use a > Daniel> lowercase key for lookup. > > That's what I thought initially, but the strings take most of the > space in dict and I didn't feel like doubling the size. You could write a string wrapper that changes comparison and hashing. I'm not sure that this (+ 1 (Python object + instance dictionary)) would use less memory than the other proposal (+ 1 Tuple + 1 String). Daniel From pitonero at gmail.com Wed Apr 6 12:28:26 2005 From: pitonero at gmail.com (El Pitonero) Date: 6 Apr 2005 09:28:26 -0700 Subject: Decorator Base Class: Needs improvement. References: <0v4351l5v1f3i9h3fssvcfklifkdlhjv7o@4ax.com> <43d351pq3qmlr8vlealdj818p8mt61p1ps@4ax.com> <4252fec3@nntp0.pdx.net> <1112754535.800594.127430@g14g2000cwa.googlegroups.com> <42538190.432027552@news.oz.net> Message-ID: <1112804906.026086.247650@z14g2000cwz.googlegroups.com> Bengt Richter wrote: > On 5 Apr 2005 19:28:55 -0700, "El Pitonero" wrote: > > >Scott David Daniels wrote: > >> Ron_Adam wrote: > >> > ... > >> > >> def tweakdoc(name): > >> def decorator(function): > >> function.__doc__ = 'Tweak(%s) %r' % (name, function.__doc__) > >> return function > >> return decorator > >> > >> What is confusing us about what you write is that you are referring > >to > >> tweakdoc as a decorator, when it is a function returning a decorator. > > > >"Decorator factory" would be a shorter name for "a function returning a > >decorator". > > > True, but tweakdoc doesn't have to be a function, so IMO we need a better > name for the @-line, unless you want to use many various specific names > like factory. E.g., There are two things: (1) The "tweadoc" object in the example, which no doubt can be called a decorator factory. (2) The @-line, which you called a "decorator expression" and that's fine with me. My preference would be something like the "decorator header". A more clear statement would be something like: a "decorator header expression" or the "expression in the decorator header", though your proposed "decorator expression" would be clear enough, too. I was addressing (1). You jumped in with (2), which I was aware of and was not dissenting. From steve at holdenweb.com Fri Apr 1 18:54:57 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 01 Apr 2005 18:54:57 -0500 Subject: Grouping code by indentation - feature or ******? In-Reply-To: References: <1112162883.943233.37980@o13g2000cwo.googlegroups.com> Message-ID: Javier Bezos wrote: > "Myles Strous" escribi? en el mensaje > news:1112162883.943233.37980 at o13g2000cwo.googlegroups.com... > >>>>satisfy some handy properties, the first of which being: >>>> l[:n] + l[n:] = l >>> >>>I don't think l[:5] + l[5:] = l is a handy property >>>and to me is clearly counterintuitive. Further, >> >>It can be quite useful for inserting something into a list (or string), >>after finding the position where you wish to insert it. >>improvedList = l[:n] + [new stuff] + l[n:] > > > As I answered in another post this is not more > useful than writing l[:n-1]. Of course, I'm aware > of the case where n=0, but this would require only > a bit of extra code (and, after all, I'm just saying > that half-open ranges are not a panacea and that I > don't like their side effects). > > >>I vaguely remember hearing at one stage that the >>sequence[position:position+length] notation is also potentially useful >>for indexing into large strings or buffers. > > > Right, to some extent it's useful, but at the cost > of introducing tricky syntaxes for very specific > cases, like this one, and unexpected off-by-one > errors in other cases, which is my point. For > example, recently I had to get a value from a > list preceded by the two previous values: > lst[n-2:n+1] and not the more logical (at last > to my eyes) lst[n-2:n]. > > Instead of giving further examples I would like > to cite three cases: > > 1) You have a starting point (s) and a > length (t): lst[s:s+t]. > 2) You have an ending point (e) and a > length: lst[e-t+1:e+1]. > 3) You have a starting point and an ending > point: lst[s:e+1]. > > What's odd is that Python applies the syntax of > case 3 to the logic of case 1. While something > like lst[s:s+t-1] for the first case could be > explained in simple mathematical terms (in other > words, it's an integral part of the algorithms), > I cannot find a way to explain the e+1 in cases > 2 and 3 (and the inconsistency with e-t+1 in case > 2 vs. s+t in case 1) except the Python syntax. > While this may be an interesting philosophical (or should that be philological) discussion, since Python has worked this way for donkey's years, and since a change would break 30% of the existing codebase, you clearly can't be advocating change. So, what's the point of this thread now? regards Steve -- Steve Holden +1 703 861 4237 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ From mefjr75 at hotmail.com Sun Apr 17 05:33:49 2005 From: mefjr75 at hotmail.com (M.E.Farmer) Date: 17 Apr 2005 02:33:49 -0700 Subject: whitespace , comment stripper, and EOL converter References: <2ab23d7a.0504120857.14ef094a@posting.google.com> <2ab23d7a.0504130738.622a3605@posting.google.com> <1113410094.102181.315080@l41g2000cwc.googlegroups.com> <1113680973.635576.310510@g14g2000cwa.googlegroups.com> <1113713669.255207.39580@f14g2000cwb.googlegroups.com> <1113726606.945042.71820@z14g2000cwz.googlegroups.com> Message-ID: <1113730429.336626.81360@g14g2000cwa.googlegroups.com> MrJean1 wrote: > There is an issue with both my and your code: it only works if doc > strings are triple quoted and if there are no other triple quoted > strings in the Python code. I had not considered single quoted strings ;) > A triple quoted string used in an assignment will be removed, for > example this case > > s = '''this string should not be removed''' > > > It is still unclear how to distinguish doc strings from other strings. > Also, I have not checked the precise Python syntax, but doc strings do > not need to be enclosed by triple quotes. A single quote may be > allowed too. > > Maybe this rule will work: a doc string is any string preceded by a > COLON token followed by zero, one or more INDENT or NEWLINE tokens. > Untested! Not needed , if you reread my post I explain that I had solved that issue. If you use the line argument that tokenizer supplies we can strip whitespace and 'rRuU' from the start of the line and look for a single quote or a double quote . I have tested it and it works. Reworked the 'pep8' thing and fixed the bug you mentioned here is the changes. > ###################################################################### > > # Python source stripper > > > ###################################################################### > > > > import os > > import sys > > import token > > import keyword > > import StringIO > > import tokenize > > import traceback > > __credits__ = ''' > > J?rgen Hermann > > M.E.Farmer > > Jean Brouwers > > ''' > > __version__ = '.8' > > __author__ = 'M.E.Farmer' > > __date__ = 'Apr 16, 2005,' \ > > 'Jan 15 2005,' \ > > 'Oct 24 2004' \ > > > > > > > ###################################################################### > > > > class Stripper: > > """Python source stripper > > """ > > def __init__(self, raw): > > self.raw = raw > > > > def format(self, out=sys.stdout, comments=0, docstrings=0, > > spaces=1, untabify=1, eol='unix'): > > """ strip comments, > > strip docstrings, > > strip extra whitespace and lines, > > convert tabs to spaces, > > convert EOL's in Python code. > > """ > > # Store line offsets in self.lines > > self.lines = [0, 0] > > pos = 0 > > # Strips the first blank line if 1 > > self.lasttoken = 1 > > self.temp = StringIO.StringIO() > > self.spaces = spaces > > self.comments = comments > > self.docstrings = docstrings > > > > if untabify: > > self.raw = self.raw.expandtabs() > > self.raw = self.raw.rstrip()+' ' > > self.out = out > > > > # Have you ever had a multiple line ending script? > > # They can be nasty so lets get them all the same. > > self.raw = self.raw.replace('\r\n', '\n') > > self.raw = self.raw.replace('\r', '\n') > > self.lineend = '\n' > > > > # Gather lines > > while 1: > > pos = self.raw.find(self.lineend, pos) + 1 > > if not pos: break > > self.lines.append(pos) > > > > self.lines.append(len(self.raw)) > > self.pos = 0 > > > > # Wrap text in a filelike object > > text = StringIO.StringIO(self.raw) > > > > # Parse the source. > > ## Tokenize calls the __call__ > > ## method for each token till done. > > try: > > tokenize.tokenize(text.readline, self) > > except tokenize.TokenError, ex: > > traceback.print_exc() > > > > # Ok now we write it to a file > > # but we also need to clean the whitespace > > # between the lines and at the ends. > > self.temp.seek(0) > > > > # All this should be written into the > > # __call__ method just haven't yet... > > > > # Mac CR > > if eol == 'mac': > > self.lineend = '\r' > > # Windows CR LF > > elif eol == 'win': > > self.lineend = '\r\n' > > # Unix LF > > else: > > self.lineend = '\n' > > > > for line in self.temp.readlines(): > > if spaces == -1: > > self.out.write(line.rstrip()+self.lineend) > > else: > > if not line.isspace(): > > self.lasttoken=0 > > self.out.write(line.rstrip()+self.lineend) > > else: > > self.lasttoken+=1 > > if self.lasttoken<=self.spaces and self.spaces: > > self.out.write(self.lineend) > > > > def __call__(self, toktype, toktext, > > (srow,scol), (erow,ecol), line): > > """ Token handler. > > """ > > # calculate new positions > > oldpos = self.pos > > newpos = self.lines[srow] + scol > > self.pos = newpos + len(toktext) > > > > # kill comments > > if self.comments: > > if toktype == tokenize.COMMENT: > > return > > # kill doc strings if self.docstrings: # Assume if there is nothing on the # left side it must be a docstring if toktype == tokenize.STRING and \ line.lstrip(' rRuU')[0] in ["'",'"']: t = toktext.lstrip('rRuU') # pep8 frowns on triple single quotes if ( self.docstrings == 'pep8' or self.docstrings == 8): # pep8 frowns on single triples if not t.startswith('"""'): return else: return # handle newlines if toktype in [token.NEWLINE, tokenize.NL]: self.temp.write(self.lineend) return # send the original whitespace if newpos > oldpos: self.temp.write(self.raw[oldpos:newpos]) # skip indenting tokens if toktype in [token.INDENT, token.DEDENT]: self.pos = newpos return # send text to the temp file self.temp.write(toktext) return ###################################################################### def Main(): import sys if sys.argv[1]: filein = open(sys.argv[1]).read() Stripper(filein).format(out=sys.stdout, comments=0, docstrings='pep8', untabify=1, eol='win') ###################################################################### if __name__ == '__main__': Main() That should work like a charm for all types of docstrings without disturbing others strings. M.E.Farmer From WLigtenberg at gmail.com Wed Apr 20 06:08:36 2005 From: WLigtenberg at gmail.com (Willem Ligtenberg) Date: Wed, 20 Apr 2005 12:08:36 +0200 Subject: XML parsing per record References: Message-ID: On Sun, 17 Apr 2005 02:16:04 +0000, William Park wrote: > Willem Ligtenberg wrote: >> I want to parse a very large (2.4 gig) XML file (bioinformatics >> ofcourse :)) But I have no clue how to do that. Most things I see read >> the entire xml file at once. That isn't going to work here ofcourse. >> >> So I would like to parse a XML file one record at a time and then be >> able to store the information in another object. How should I do >> that? >> >> Thanks in advance, >> >> Willem Ligtenberg A total newbie to python by the way. > > You may want to try Expat (www.libexpat.org) or Python wrapper to it. > You can feed small piece at a time, say by lines or whatever. Of > course, it all depends on what kind of parsing you have in mind. :-) > > Care to post more details? The XML file I need to parse contains information about genes. So the first element is a gene and then there are a lot sub-elements with sub-elements. I only need some of the informtion and want to store it in my an object called gene. Lateron this information will be printed into a file, which in it's turn will be fed into some other program. This is an example of the XML 9996 1 LocusID 320632 GeneID 320632 2003 8 28 21 39 0 2005 2 17 12 54 0 6 1 1 Mus musculus house mouse taxon 10090 mouse Mus musculus Eukaryota; Metazoa; Chordata; Craniata; Vertebrata; Euteleostomi; Mammalia; Eutheria; Euarchontoglires; Glires; Rodentia; Sciurognathi; Muridae; Murinae; Mus 1 2 ROD LocusLink 9996 9996 1 0 LocusID 9996 LOC320632 From roy at panix.com Fri Apr 1 18:53:14 2005 From: roy at panix.com (Roy Smith) Date: Fri, 01 Apr 2005 18:53:14 -0500 Subject: Ternary Operator in Python References: <20050401072442.73412.qmail@web8408.mail.in.yahoo.com> <1112391650.018826.274970@l41g2000cwc.googlegroups.com> Message-ID: In article <1112391650.018826.274970 at l41g2000cwc.googlegroups.com>, "Carl Banks" wrote: > Terry Reedy wrote: > > "praba kar" wrote in message > > news:20050401072442.73412.qmail at web8408.mail.in.yahoo.com... > > > Dear All, > > > I am new to Python. I want to know how to > > > work with ternary operator in Python. I cannot > > > find any ternary operator in Python. So Kindly > > > clear my doubt regarding this > > > > A unary operator has one operand; a binary operator has two operands; > a > > ternary operator has three operands. Python has none built-in, > > Not so fast, my friend. What about the expression "0.0 < a < 1.0"? I still remember one of the earliest bugs I ever wrote (I've long since forgotten most of the zillions I've written since). It must have been around 1975, and my high school had an ASR-33 connected to a HP-3000 running Time Shared Basic at another school a few towns away. I wrote something like "1 < X < 10" and got an error. I was puzzled by this, since we were using this notation in math class. The answer of course was that I needed to write "1 < X AND X < 10", which I found really annoying and strange looking. Or is my long-term memory returning corrupted data? Maybe BASIC let you do 1 < X < 10, but I ran into this when I moved onto FORTRAN the next year? In any case, I've gotten so used to writing 1 < x && x < 10 (or variations on the theme) that now I've got a language which lets me write it the normal math way, 1 < x < 10, and *that* looks strange. Wierd, huh? How our tools warp our thinking. From michele.simionato at gmail.com Sun Apr 10 00:35:58 2005 From: michele.simionato at gmail.com (Michele Simionato) Date: 9 Apr 2005 21:35:58 -0700 Subject: Puzzling OO design problem In-Reply-To: <20050409142843.26D9.0.NOFFLE@dthierbach.news.arcor.de> References: <1113003772.020556.69550@l41g2000cwc.googlegroups.com> <20050409082128.A3E.0.NOFFLE@dthierbach.news.arcor.de> <20050409142843.26D9.0.NOFFLE@dthierbach.news.arcor.de> Message-ID: <1113107758.450304.65000@o13g2000cwo.googlegroups.com> Dirk wrote: > So I dug through the documentation and found that new-style classes > compute a monotonic linearization of the inheritance graph, observing >local precedence order, using the algorithm also used in Dylan > described here: >http://www.webcom.com/haahr/dylan/linearization-oopsla96.html Actually Dylan authors invented the C3 algorithm but Dylan does not use it: for compatibility with Lisp, Dylan uses the CLOS algorithm. Languages that I know that use C3 are Python and Goo. Playing with the MOP you can get lispy languages to follow C3 too. From polykrombelcentercom Sat Apr 30 14:58:54 2005 From: polykrombelcentercom (Zoool (at dot)) Date: Sat, 30 Apr 2005 20:58:54 +0200 Subject: User Directory Path References: <1114885796.215916.99730@f14g2000cwb.googlegroups.com> Message-ID: Thanks a lot, os.environ["HOMEDRIVE"] os.environ["HOMEPATH"] are what i was looking for .... "wittempj at hotmail.com" a ?crit dans le message de news: 1114885796.215916.99730 at f14g2000cwb.googlegroups.com... > os.getenv or os.envoron, see http://docs.python.org/lib/os-procinfo.html > From michele.simionato at gmail.com Wed Apr 6 08:37:19 2005 From: michele.simionato at gmail.com (Michele Simionato) Date: 6 Apr 2005 05:37:19 -0700 Subject: boring the reader to death (wasRe: Lambda: the Ultimate Design Flaw In-Reply-To: References: Message-ID: <1112791039.362368.58110@l41g2000cwc.googlegroups.com> Sunnan: > The python code I've read so far has looked like that. Not > type declarations, but loooong class declarations. What do you mean? Lots of repetitive "self.variable=variable" in the __init__ method? Use of classes when you would use closures? Or maybe you are comparing with CLOS classes, which are pretty slim, since the (multi)methods are defined outside them? Michele Simionato From eurleif at ecritters.biz Fri Apr 15 20:56:00 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Sat, 16 Apr 2005 00:56:00 GMT Subject: pre-PEP: Simple Thunks In-Reply-To: References: Message-ID: Brian Sabbey wrote: > Thunk statements contain a new keyword, 'do', as in the example below. > The body of the thunk is the suite in the 'do' statement; it gets passed > to the function appearing next to 'do'. The thunk gets inserted as the > first argument to the function, reminiscent of the way 'self' is > inserted as the first argument to methods. It would probably make more sense to pass the thunk as the last argument, not as the first. That would make it easier to create functions with optional thunks, as in: def print_nums(start, end, thunk=None): for num in xrange(start, end+1): if thunk is not None: num = thunk(num) print num print_nums(1, 3) # prints 1, 2, 3 do num print_nums(1, 3): # prints 2, 4, 6 continue num * 2 > Because thunks blend into their environment, a thunk cannot be used > after its surrounding 'do' statement has finished Why? Ordinary functions don't have that restriction: >>> def foo(): ... x = 1 ... def bar(): ... return x ... return bar ... >>> foo()() 1 From tim.peters at gmail.com Mon Apr 18 23:18:36 2005 From: tim.peters at gmail.com (Tim Peters) Date: Mon, 18 Apr 2005 23:18:36 -0400 Subject: Proposal: an unchanging URL for Python documentation In-Reply-To: <1113878396.500420.256230@g14g2000cwa.googlegroups.com> References: <1113878396.500420.256230@g14g2000cwa.googlegroups.com> Message-ID: <1f7befae0504182018211ef530@mail.gmail.com> [Steve] > I have a suggestion/request that will, I think, improve the Python > documentation. > > Currently, the Python documentation in HTML format is stored at URLs > that change with each new release of Python. That is, for example, the > documentation for the os module is at > http://python.org/doc/2.3/lib/module-os.html for release 2.3 of Python, > at http://python.org/doc/2.4/lib/module-os.html for release 2.4 and so > on. Have you tried ? > I propose that an additional a URL be set up for the Python HTML > documentation. This URL will always contain the current version of the > documentation. Suppose we call it "current". Then (while 2.4 is still > the current version) the documentation for the os module would also be > available at > http://python.org/doc/current/lib/module-os.html. Try http://docs.python.org/lib/module-os.html > There are three advantages to this proposal. > > (1) It is cheap and easy to do. > > (2) If a person regularly refers to the documentation for the os > module, he can bookmark > http://python.org/doc/current/lib/module-os.html and always be sure of > getting the most current version. > > (3) This would give Pythonistas -- basically as a freebie -- > annotatable documentation. You may be familiar with Wikalong ( > http://www.wikalong.org/ ). Wikalong basically allows you to annotate > any URL. If we had a "current" URL for Python documentation, people > could add Wikalong notes to the current documentation without worrying > that the annotations would not survive the release of the next version > of Python. Being able to use Wikalong would provide the Python > community with the opportunity to experiment with annotatable documents > (not to mention, ride the leading edge of the Wikalong wave). And > those who dislike annotated documentation can easily ignore it or turn > it off the Wikalong sidebar (assuming that they have Wikalong installed > in the first place). Con: It's already there, and TOOWTDI . From james at wrong.nu Mon Apr 25 09:57:24 2005 From: james at wrong.nu (R. C. James Harlow) Date: Mon, 25 Apr 2005 14:57:24 +0100 Subject: Multiple tuples for one for statement In-Reply-To: <426CF1D5.E9F4396@pauahtun.org> References: <1114398216.258027.105070@g14g2000cwa.googlegroups.com> <200504251356.07715.james@wrong.nu> <426CF1D5.E9F4396@pauahtun.org> Message-ID: <200504251457.28724.james@wrong.nu> On Monday 25 April 2005 14:34, Ivan Van Laningham wrote: > Hi All-- > > "R. C. James Harlow" wrote: > > or just: > > > > for a,b,c in (tup1, tup2, tup3): > > print a > > print b > > print c > > And this works in Python version??? Ah, reading the replies to the original post, this works but doesn't give the result that the original poster wanted. -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From bokr at oz.net Mon Apr 11 23:42:06 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 12 Apr 2005 03:42:06 GMT Subject: singleton objects with decorators References: Message-ID: <425b1421.146537619@news.oz.net> On Mon, 11 Apr 2005 17:26:09 +0200, Uwe Mayer wrote: >Hi, > >I've been looking into ways of creating singleton objects. With Python2.3 I >usually used a module-level variable and a factory function to implement >singleton objects. > >With Python2.4 I was looking into decorators. The examples from PEP 318 >http://www.python.org/peps/pep-0318.html#examples > >don't work - AFAIK because: >- you cannot decorate class definitions (why was it left out?) >- __init__ must return None > > >However, you can use the decorator: > >def singleton(f): > instances = {} > def new_f(*args, **kwargs): > if (f not in instances): > instances[f] = f(*args, **kwargs) > return instances[f] > new_f.func_name = f.func_name > new_f.func_doc = f.func_doc > return new_f > >with a class that overwrites the __new__ methof of new-style classes: > >class Foobar(object): > def __init__(self): > print self > > @singleton > def __new__(self): > return object.__new__(Foobar) > > >Is this particularly ugly or bad? > >Thanks for comments, I thought of a different approach. The singleton function here takes arguments for the initial instance of a class, and instantiates it, and then modifies the class's __new__ and __init__ to return the initial instance and prevent further initialization. Used directly, as normal function decorators can be (i.e., fun = deco(fun) or fun = deco(args)(fun)), singleton works (not counting bugs ;-) as is. To invoke it as decorator demands a trick workaround using an intermediate workaround decorator and a dummy funcion definition synonymous with the class to be decorated (which mus pre-exist for this). BTW, this is different from the class-decorator-as-sugar-for-metaclass, (which I suggested previously) since it take one class argument vs arguments for the metaclass __new__ etc. I added a singularize decorator for when you don't immediately want to specify the first initiazization parameters, but want the first instance to to become the singleton instance whenever that happens later. So here's some hacks to play with: ----< singleton.py >----------------------------------------------- def singleton(*args, **kw): """decorator cacheing singleton instance immediately""" def singdeco(cls): assert isinstance(cls, type) inst = cls(*args, **kw) cls.__new__ = staticmethod(lambda *a, **kw: inst) cls.__init__ = staticmethod(lambda *a, **kw: None) # no re-init return cls return singdeco import sys def workaround(f): cls = sys._getframe(1).f_locals.get(f.func_name) if cls is None: cls = sys._getframe(1).f_globals.get(f.func_name) return cls def singularize(cls): """decorator setting singleton-making mousetrap""" oldnew = cls.__new__ def __new__(cls, *args, **kw): inst = oldnew(cls) inst.__init__(*args, **kw) cls.__new__ = staticmethod(lambda *a,**kw: inst) cls.__init__ = staticmethod(lambda *a, **kw: None) return inst cls.__new__ = staticmethod(__new__) return cls def test(): class Foobar(object): pass Foobar = singleton()(Foobar) print Foobar print [Foobar() for x in xrange(2)] class Boobar(object): def __init__(self, v): print self, v self.v = v @singleton(123) @workaround def Boobar(): pass # dummy used by workaround for name print Boobar print [Boobar(x) for x in xrange(2)] print [Boobar(x).v for x in xrange(2)] class Gee(object): def __init__(self): print 'Gee:', self Gee = singularize(Gee) print Gee print [Gee() for x in xrange(2)] class Haw(object): def __init__(self, *args, **kw): self.args = args self.kw =kw Haw = singularize(Haw) haw = Haw(1,2L, 3.5, s='string', more='example') print vars(haw) print vars(Haw(111, a='222')) print [Haw(), Haw()] print [Haw().args[i] for i in xrange(len(Haw().args))] print [Haw().kw['s'], Haw().kw['more']] if __name__ == '__main__': test() ------------------------------------------------------------------- No guarantees, mind ;-) Output, showing single instances and no repeat initialization: [<__main__.Foobar object at 0x02F03BEC>, <__main__.Foobar object at 0x02F03BEC>] <__main__.Boobar object at 0x02F03DCC> 123 [<__main__.Boobar object at 0x02F03DCC>, <__main__.Boobar object at 0x02F03DCC>] [123, 123] Gee: <__main__.Gee object at 0x02F03E8C> [<__main__.Gee object at 0x02F03E8C>, <__main__.Gee object at 0x02F03E8C>] {'args': (1, 2L, 3.5), 'kw': {'s': 'string', 'more': 'example'}} {'args': (1, 2L, 3.5), 'kw': {'s': 'string', 'more': 'example'}} [<__main__.Haw object at 0x02F03F0C>, <__main__.Haw object at 0x02F03F0C>] [1, 2L, 3.5] ['string', 'example'] Regards, Bengt Richter From exarkun at divmod.com Mon Apr 25 14:16:00 2005 From: exarkun at divmod.com (Jp Calderone) Date: Mon, 25 Apr 2005 18:16:00 GMT Subject: What is situation with threads in Python In-Reply-To: <797fe3d4050425111074475da6@mail.gmail.com> Message-ID: <20050425181600.10340.1919634272.divmod.quotient.24928@ohm> On Mon, 25 Apr 2005 14:10:28 -0400, Bill Mill wrote: >On 4/25/05, Leonard J. Reder wrote: >> Hello Mark, >> >> I took your three day course here at JPL and recall that you said >> something was wrong with the implementation of threads within Python >> but I cannot recall what. So what is wrong with threads in Python? > >I'm going to guess that he meant the Global Interpreter Lock is what's >wrong with Python threads. You can read about it in the docs at >http://docs.python.org/api/threads.html and get some good analysis >from Ian Bicking (with some excellent, and some not so excellent, >comments): http://blog.ianbicking.org/gil-of-doom.html . > >> >> The other part of this question is, if there is something wrong with >> the threads in Python has anyone wrapped the Posix threads C api using >> swig to fix this problem? I work on Solaris/Linux systems and this >> seems like a quick fix - maybe. >> > >Nope, since the interpreter is not entirely thread-safe, I don't >believe you can wrap pthreads. Python _does_ wrap pthreads, where it is appropriate to do so. Whether another threading library is present, it wraps that instead. Whatever happens, it presents the result in the form of the thread module. Jp From mfranklin1 at gatwick.westerngeco.slb.com Fri Apr 22 05:58:17 2005 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Fri, 22 Apr 2005 10:58:17 +0100 Subject: How to prevent Tkinter frame resize? In-Reply-To: <1114139979.992625.282610@l41g2000cwc.googlegroups.com> References: <1114139979.992625.282610@l41g2000cwc.googlegroups.com> Message-ID: phil_nospam_schmidt at yahoo.com wrote: > I am trying to prevent a user from resizing a frame beyond its > "natural" size as given by winfo_reqwidth and winfo_reqheight, without > any success. Can anyone make any suggestions, based on my code below? > > Thanks! > > from Tkinter import * > > class Table(Frame): > def __init__(self, master, > rows=['row 1'], cols=['col 1'], > row_labels=True, > col_labels=True, > row_buttons=True, > col_buttons=True): > Frame.__init__(self, master) > self.rows = rows > self.cols = cols > self.row_labels = row_labels > self.col_labels = col_labels > self.row_buttons = row_buttons > self.col_buttons = col_buttons > self.col_width = 6 > self.draw() > self.bind('', self.changed) > def changed(self, ev): > w, h = self.winfo_reqwidth(), self.winfo_reqheight() > cfg = {} > if ev.height > h: > cfg['height'] = h > if ev.width > w: > cfg['width'] = w > if cfg: > self.config(**cfg) ######## this has no effect ######## I'm not sure I follow your code but this method is bound to the event *but* needs to return the string "break" so that it does not pass that event on to the default event handler. def changed(self, ev): w, h = self.winfo_reqwidth(), self.winfo_reqheight() cfg = {} if ev.height > h: cfg['height'] = h if ev.width > w: cfg['width'] = w if cfg: self.config(**cfg) ######## this has no effect ######## return "break" This may do what you want..... Cheers Martin From http Wed Apr 13 15:39:32 2005 From: http (Paul Rubin) Date: 13 Apr 2005 12:39:32 -0700 Subject: Simple Python + Tk text editor References: <425D6641.5050906@pytex.org> Message-ID: <7xfyxuqxe3.fsf@ruckus.brouhaha.com> Jonathan Fine writes: > I'm looking for a simple Python + Tk text editor. > > I want it as a building block/starting point. Something wrong with IDLE? From aahz at pythoncraft.com Tue Apr 5 18:43:51 2005 From: aahz at pythoncraft.com (Aahz) Date: 5 Apr 2005 18:43:51 -0400 Subject: Best editor? References: <1112725379.514651.66540@l41g2000cwc.googlegroups.com> Message-ID: In article <1112725379.514651.66540 at l41g2000cwc.googlegroups.com>, ChinStrap wrote: > >When not using the interactive prompt, what are you using? I keep >hearing everyone say Emacs, but I can't understand it at all. I keep >trying to learn and understand why so many seem to like it because I >can't understand customization even without going through a hundred >menus that might contain the thing I am looking for (or I could go >learn another language just to customize!). Use vim. 80% of the power of emacs at 20% of the learning curve. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "The joy of coding Python should be in seeing short, concise, readable classes that express a lot of action in a small amount of clear code -- not in reams of trivial code that bores the reader to death." --GvR From glauco.silva at cenpra.gov.br Wed Apr 27 07:48:00 2005 From: glauco.silva at cenpra.gov.br (Glauco Silva) Date: Wed, 27 Apr 2005 08:48:00 -0300 Subject: How can i solve this problem with py2exe ? Message-ID: <00a001c54b1e$f6628140$e87290c8@piau> Hi, I?m with problem to create a executable program in python. I?m using py2exe but i don?t know if it?s right. When i run in prompt "python setup.py py2exe", appear in the end this: ########### The following modules appear to be missing [ '_imaging_gif','libVTKCommonPython', 'libVTKContribPython', 'libVTKGraphicsPython', 'libVTKImagingPython', 'libVTKPatentedPython', libvtkCommonPython', 'libvtkFilteringPython', 'libvtkGraphicsPython', 'libvtkHybridPython', 'libvtkIOPython', 'libvtkImagingPython', 'libvtkParallelPython', 'libvtkPatentedPython', 'libvtkRenderingPython', 'numarray.array', 'numarray.dot', 'numarray.fromfile', 'numarray.size', 'numarray.zeros', 'vtk.vtkActor2D', 'vtk.vtkDCMParser', 'vtk.vtkImageClip', 'vtk.vtkImageFlip', 'vtk.vtkImageImport', 'vtk.vtkImageMagnify', 'vtk.vtkImageMapper', 'vtk.vtkImagePermute', 'vtk.vtkImageReader', 'vtk.vtkImageResample', 'vtk.vtkImageReslice', 'vtk.vtkImageShiftScale', 'vtk.vtkImageThreshold', 'vtk.vtkImageViewer', 'vtk.vtkImageWriter', 'vtk.vtkRenderWindow', 'vtk.vtkRenderer', 'vtk.vtkTextMapper', 'vtk.vtkTextProperty', 'vtk.vtkTransform'] ########### How can i solve this problem? My setup.py: from distutils.core import setup import py2exe from glob import glob setup( # The first three parameters are not required, if at least a # 'version' is given, then a versioninfo resource is built from # them and added to the executables. version = "2.0", description = "programa InVesalius", name = "InVesalius", # targets to build console = ["C:\\promed2.0\\python\\MyMainModule.py"], data_files=[("icons", glob("C:\\promed2.0\\icons\\*.*")), ("docs",glob("C:\\promed2.0\\docs\\*.*")), ("config", ["C:\\promed2.0\\setup.cfg"]) ], packages = ['vtk-windows', 'vtk-windows.vtk', 'vtk-windows.vtk.gtk', 'vtk-windows.vtk.qt', 'vtk-windows.vtk.tk', 'vtk-windows.vtk.util', 'vtk-windows.vtk.wx', 'vtk-windows.vtk.test'], ) My PYTHONPATH = C:\Python23;C:\promed2.0\vtk-windows;C:\promed2.0\python My dir: ########## promed2.0/ setup.cfg setup.py icons/ docs/ python/ MyMainModule.py vtk-window/ vtkpython.py vtkpythontk.py vtk.pth vtkCommon.dll vtkCommonPython.dll vtkCommonTCL.dll ... vtk/ ########### OS: win 2K Python ver: 2.3.5 py2exe ver: 0.5.4 Thanks Glauco -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- No virus found in this outgoing message. Checked by AVG Anti-Virus. Version: 7.0.308 / Virus Database: 266.10.3 - Release Date: 25/4/2005 From vze4rx4y at verizon.net Mon Apr 18 20:38:59 2005 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Tue, 19 Apr 2005 00:38:59 GMT Subject: Removing dictionary-keys not in a set? References: <1113824946.525441.285760@l41g2000cwc.googlegroups.com> Message-ID: [Klaus Alexander Seistrup] > >>> d1 = {1:'a', 2:'b', 3:'c', 4:'d', 5:'e'} > >>> s1 = set(d1) > >>> s1 > set([1, 2, 3, 4, 5]) > >>> s2 = set([1, 3, 5]) > >>> s1-s2 > set([2, 4]) > >>> for k in s1-s2: > ... del d1[k] > ... FWIW, if s2 is not already a set object, it need not be transformed before using it. Instead, write: for k in set(d1).difference([1,3,5]): del d1[k] If you prefer to work with dictionaries instead of sets, then adapt the existing code for symmetric_difference_update() in sets.py. Raymond Hettinger From leo at lspace.org Thu Apr 7 15:23:21 2005 From: leo at lspace.org (Leo Breebaart) Date: 7 Apr 2005 19:23:21 GMT Subject: How to name Exceptions that aren't Errors Message-ID: <3blfl8F6gt80jU1@individual.net> I've recently become rather fond of using Exceptions in Python to signal special conditions that aren't errors, but which I feel are better communicated up the call stack via the exception mechanism than via e.g. return values. For instance, I'm thinking of methods such as: def run(self): """ Feed the input file to the simulator. """ for linenr, line in enumerate(self.infile): try: current_values = self.parse_line(linenr, line) ==> except CommentLineException: continue results = self.do_one_simulation_step(current_values) self.process_simulation_results(results) which I use in order to discard comments from a file I'm parsing line-by-line. My question is twofold. First, I know that many programmers are violently opposed to using exceptions in this fashion, i.e. for anything other than, well, exceptional circumstances. But am I correct in thinking that in Python this usage is actually considered quite normal, and not frowned upon? Is my snippet above indeed sufficiently Pythonic? Second, purely as a question of aesthetics, I was wondering if the folks here might have any opinions about actual naming conventions for the exception classes used in this fashion. 'CommentLineError' would clearly be wrong, but using the 'Exception' prefix seems a bit redundant and pointless too. I suppose I could just call the exception "CommentLine" and leave it at that, but I don't know, maybe there's something better I'm overlooking. Any suggestions? -- Leo Breebaart From steven.bethard at gmail.com Wed Apr 27 16:47:23 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 27 Apr 2005 14:47:23 -0600 Subject: how can I sort a bunch of lists over multiple fields? In-Reply-To: <1114634355.348110.141690@o13g2000cwo.googlegroups.com> References: <1114623282.855415.132040@l41g2000cwc.googlegroups.com> <1114634355.348110.141690@o13g2000cwo.googlegroups.com> Message-ID: Lonnie Princehouse wrote: > Might as well make a class for Book instead of dealing with buckets of > lists... > > class Book(object): > def __init__(self, title, author, publisher, isbn, date): # add > more fields according to CSV > self.__dict__.update(locals()) # lazy! Just for any newbies not paying attention, a slightly less lazy approach that doesn't leave the Book instance referencing itself would do something like: params = locals() del params['self'] self.__dict__.update(params) or just write it out: self.title = title self.author = author self.publisher = publisher self.isbn = isbn self.date = date =) STeVe From rbt at athop1.ath.vt.edu Mon Apr 25 13:23:07 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Mon, 25 Apr 2005 13:23:07 -0400 Subject: Python, Perl & PDF files In-Reply-To: References: Message-ID: Peter Hansen wrote: > Peter Hansen wrote: > >> Dennis Lee Bieber wrote: >> >>> On Mon, 25 Apr 2005 17:24:36 +0300, Christos "TZOTZIOY" Georgiou: >>> >>>> I don't know any related myth of anglo-saxon origin to quote. > > >>> The most commonly known phrasing would likely be "God only helps >>> those who help themselves". >> >> >> Google suggests that removing the word "only" produces a >> phrase many times more commonly known... > > > And very interesting reading (to spawn another diversion > typical to c.l.p) OK, I'm seeking to provoke now... why don't you go hijack some other thread? OK, I'm done seeking to provoke. So, it's official. Perl has *much*, *much* better support for dealing with PDF files than does Python. Hopefully that'll change one day soon. If I had the programming knowledge, I'd get on it right away, but alas I do not so I cannot ;) Thanks to all who responded on topic. From fperez.net at gmail.com Tue Apr 12 12:09:06 2005 From: fperez.net at gmail.com (Fernando Perez) Date: Tue, 12 Apr 2005 10:09:06 -0600 Subject: IPython - problem with using US international keyboard input scheme on W2K References: <3bv5mgF6jbil9U1@individual.net> <3c1qrjF6k3k4fU1@individual.net> Message-ID: Claudio Grondi wrote: > Considering what I found in the ipython mailing archives > and the fact, that after the fix with displaying colors on > bright backgrounds Gary had no time yet to get in touch > with me about the code I have sent him, I suppose, that > there will be no new releases addressing this problem > soon, right? Sorry to hear this; unfortunately readline/win32 is beyond my control, so there is not much I can offer on this front. You could try to write to Gary again, he might just have been swamped with other things at the time. Best, f From stewart.midwinter at gmail.com Tue Apr 26 21:32:56 2005 From: stewart.midwinter at gmail.com (stewart.midwinter at gmail.com) Date: 26 Apr 2005 18:32:56 -0700 Subject: App suggestion please: blog / forum software in Python In-Reply-To: References: Message-ID: <1114565576.866943.77420@g14g2000cwa.googlegroups.com> thanks Kartic. I use Frog already at my office. For this particular application, its design may not be appropriate, since each user gets her own blog space. I'm actually after a community blog, where any one of the registered users can post an item, or discuss on a forum. Drupal, from http://drupal.org, seems to do exactly what I want, except it's written in php. Thanks for the tip on Vellum. I'd like to find a few sites using it, so I can see it in action. S From bjgol at yahoo.com Thu Apr 14 23:15:59 2005 From: bjgol at yahoo.com (Brett) Date: Thu, 14 Apr 2005 22:15:59 -0500 Subject: Rookie Question: Passing a nested list into a function? References: Message-ID: I think so. I later reference it as textfilelist[0][0]. My intent is to be able to use: titlelist1[x][1] as part of my "if" statement in my function. -Brett "James Stroud" wrote in message news:mailman.1945.1113532023.1799.python-list at python.org... > > Do you really want quotation marks around "titlelist1[x][1]" ? > > e.g. > >>>> textfilelist = [["titlelist1[x][1]"]] >>>> textfilelist[0][1] > Traceback (most recent call last): > File "", line 1, in ? > IndexError: list index out of range > > > > On Thursday 14 April 2005 06:51 pm, Brett wrote: >> I am trying to pass the value of a nested list into a function (to my >> "if" >> statement) as follows: >> >> textfilelist = [["titlelist1[x][1]"]] >> def idfer(listlength, comparelistlength, list): >> while x < (listlength - 1): >> while y < comparelistlength: >> if list == titlelist2[y][1]: >> (I cutoff the end to focus on the problem) >> >> #Here i call my function hoping i am passing the value within >> textfilelist[0][0] to my function >> idfer(textfilelist[0][1], textfilelist[1][1], textfilelist[0][0]) >> >> >> -------------- >> I don't if there is a "legal" way to do this, but I would appreciate some >> guidance. >> >> Thanks, >> >> Brett > > -- > James Stroud, Ph.D. > UCLA-DOE Institute for Genomics and Proteomics > Box 951570 > Los Angeles, CA 90095 > > http://www.jamesstroud.com/ From bulliver at badcomputer.org Fri Apr 29 22:40:24 2005 From: bulliver at badcomputer.org (darren kirby) Date: Fri, 29 Apr 2005 19:40:24 -0700 Subject: Python Challenge ahead [NEW] for riddle lovers In-Reply-To: <4272C8A0.7050404@hathawaymix.org> References: <4272C8A0.7050404@hathawaymix.org> Message-ID: <200504291940.29908.bulliver@badcomputer.org> quoth the Shane Hathaway: > pythonchallenge wrote: > > For the riddles' lovers among you, you are most invited to take part > > in the Python Challenge, the first python programming riddle on the net. > > > > You are invited to take part in it at: > > http://www.pythonchallenge.com > > That was pretty fun. Good for a Friday. Too bad it comes to an abrupt > "temporary end". > > Shane > > P.S. I hope I didn't hammer your server on step 3. I was missing the > mark. :-) You're not the only one. This is where I am currently stuck. It's starting to hurt my head. There are 478 results in the form *BBBsBBB* but the thing said 'exactly' right, well there are 10 results in the form *sBBBsBBBs* None of them seem to work... I quit ;) -- darren kirby :: Part of the problem since 1976 :: http://badcomputer.org "...the number of UNIX installations has grown to 10, with more expected..." - Dennis Ritchie and Ken Thompson, June 1972 -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From steve at holdenweb.com Tue Apr 5 19:35:13 2005 From: steve at holdenweb.com (Steve Holden) Date: Tue, 05 Apr 2005 19:35:13 -0400 Subject: Best editor? In-Reply-To: <1112725379.514651.66540@l41g2000cwc.googlegroups.com> References: <1112725379.514651.66540@l41g2000cwc.googlegroups.com> Message-ID: ChinStrap wrote: > When not using the interactive prompt, what are you using? I keep > hearing everyone say Emacs, but I can't understand it at all. I keep > trying to learn and understand why so many seem to like it because I > can't understand customization even without going through a hundred > menus that might contain the thing I am looking for (or I could go > learn another language just to customize!). > > Personally I like SciTE, it has everything I think a midweight editor > should: code folding, proper python support, nice colors out of the > box, hotkey access to compile (I'm sure emacs does this, but I couldn't > figure out for the life of me how), etc. > > Opinions on what the best is? Or reading I could get to maybe sway me > to Emacs (which has the major advantage of being on everyone's system). > There is only a "best" editor if you aare convinced that only oine measure is important, allowing you to place all editors on a single straight line and declare the one that appears furthest to the left or right the "best". In practice, of course, different people value different editor characteristics, so there are a multitude of opinions about which is "best". regards Steve -- Steve Holden +1 703 861 4237 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ From lucio.torre at gmail.com Fri Apr 15 19:40:05 2005 From: lucio.torre at gmail.com (lucio.torre at gmail.com) Date: 15 Apr 2005 16:40:05 -0700 Subject: ANN: Python 2.3.2 for PalmOS available Message-ID: <1113608405.558884.235890@f14g2000cwb.googlegroups.com> Hello, Some months ago i did a port of the Python2.3.2 interpreter to PalmOS. I didnt port any C module or created modules for PalmOS API's. But you can run an interpreter and use stdin/stdout from a form. There is also a tool to freeze scripts and use the interpreter as a pseudo-shared library. While talking with Facundo while in a PyAr meeting (python-argentina, http://www.python.org/ar ) he told me that there is some interest in this platform. So, ive made an initial release that has no documentation on how to use it or compile it (it requires codewarrior). If there is any interest on this, please let me know so we can work on getting this as a real port. As usual, this is just a proof of concept and is ugly in many ways. (ie, in Palm, code segments must be less than 64K, so some files had to be split and rearranged ). If anyone want to check this out, heres the url: http://pyar.decode.com.ar/Members/ltorre/PythonPalm Regards, Lucio. From cappy2112 at gmail.com Thu Apr 7 18:13:04 2005 From: cappy2112 at gmail.com (Cappy2112) Date: 7 Apr 2005 15:13:04 -0700 Subject: how can I extract all urls in a string by using re.findall() ? In-Reply-To: References: <311b5ce105040619052e00e10c@mail.gmail.com> Message-ID: <1112911984.035191.238350@f14g2000cwb.googlegroups.com> >>Reading the documentation on re might be helpfull here :-P Many times, the python docs can make the problem more complicated, espcecially with regexes. From steven.bethard at gmail.com Sun Apr 3 18:09:42 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 03 Apr 2005 16:09:42 -0600 Subject: StopIteration in the if clause of a generator expression In-Reply-To: <_2R3e.3341$7b.3033@trndny06> References: <424db34c.51543105@news.oz.net> <_2R3e.3341$7b.3033@trndny06> Message-ID: Raymond Hettinger wrote: > [Peter Otten] > >>Do you see any chance that list comprehensions will be redefined as an >>alternative spelling for list()? > > Not likely. It is possible that the latter spelling would make it possible for > Py3.0. eliminate list comps entirely. However, they are very popular and > practical, so my bet is that they will live on. I suspect you're right, but I certainly wouldn't complain if list comps disappeared. TOOWTDI and all, and I often find myself alternating between the two when I can't decide which one seems more Pythonic. (These days I generally write a listcomp, but I wouldn't put any money on my code being entirely consistent about this...) STeVe From simoninusa2001 at yahoo.co.uk Sat Apr 23 12:43:52 2005 From: simoninusa2001 at yahoo.co.uk (Simon John) Date: 23 Apr 2005 09:43:52 -0700 Subject: Python or PHP? References: <1114254894.512656.297040@l41g2000cwc.googlegroups.com> <87hdhxwj6s.fsf@debian.kirkjobsluder.is-a-geek.net> Message-ID: <1114274632.128667.281820@l41g2000cwc.googlegroups.com> I've been a PHP and Perl programmer (amongst others) for 10 years or more now, and a Python coder for 3 or so. I have come to hate PHP now, it's pseudo-OOP is awful, it's dog slow at handling XML, it's so easy to use that most of the programmers I've had contact with are very sloppy and do things like extract($_GET); or put database usernames and passwords in index.php. I also have to agree that php.net/manual seems to be the main reference that coders use - which is not good if the comments are wrong! Python seems to force you to write better code, maybe because of the indentation, exception handling, proper OOP etc. Plus it's not so tied into web stuff, in fact most of my Python programming is for the desktop. I still love Perl, it's a bit of an art form, as "there's more than one way to do it", whereas Python usually only allows one way to do it, which may or may not be a better mantra.... I've come to allocate PHP the same standing as ASP, VB or Java - the language is OK, but the programmers are usually crap. From kingofearth.com at gmail.com Thu Apr 14 16:10:26 2005 From: kingofearth.com at gmail.com (kingofearth.com at gmail.com) Date: 14 Apr 2005 13:10:26 -0700 Subject: Socket Error In-Reply-To: References: <1113503903.874232.322370@o13g2000cwo.googlegroups.com> Message-ID: <1113509426.452739.166010@z14g2000cwz.googlegroups.com> Thanks everybody, it works now. I thought I needed to do something like that but it didn't show it in the tutorial so I decided to ask here. From t-meyer at ihug.co.nz Tue Apr 12 20:23:32 2005 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Wed, 13 Apr 2005 12:23:32 +1200 Subject: Python 2.4 killing commercial Windows Python development ? In-Reply-To: Message-ID: > installs it where? the MS docs seem to indicate that they > want you to install it in the program directory, rather than > in a "shared" location: > > http://support.microsoft.com/default.aspx?scid=kb;en-us;326922 From : """This means to install it into the directory containing python.exe. Unfortunately, this does not work if your extension is then used in an embedded Python, e.g. one running as a COM object. In this case, python.exe will not be the main executable, but, say, outlook.exe will be. So Microsoft's recommendation to install the DLL into the EXE directory is flawed for COM and other embedded cases. This is precisely the reason why the Python installer installs both python24.dll and msvcr71.dll into system32.""" =Tony.Meyer From richardblackwood at cloudthunder.com Sun Apr 24 00:14:16 2005 From: richardblackwood at cloudthunder.com (Richard Blackwood) Date: Sun, 24 Apr 2005 00:14:16 -0400 Subject: Variables In-Reply-To: <1114315847.532982.178620@z14g2000cwz.googlegroups.com> References: <426B0283.40602@cloudthunder.com> <1114315847.532982.178620@z14g2000cwz.googlegroups.com> Message-ID: <426B1D18.4030504@cloudthunder.com> Dan Bishop wrote: >Richard Blackwood wrote: > > >>Steven Bethard wrote: >> >> >> >>>Richard Blackwood wrote: >>> >>> >>> >>>>Indeed, this language is math. My friend says that foo is a >>>> >>>> >constant > > >>>>and necessarily not a variable. If I had written foo = >>>> >>>> >raw_input(), > > >>>>he would say that foo is a variable. >>>> >>>> >>>Then what does he say if you write: >>> >>>foo = 5 >>>foo = 6 >>> >>> >... > > >>He says that foo is a constant. At first it was a constant which >> >> >equaled > > >>5, then it was a constant that equaled 6. >> >> > >He must have a very unusual definition of "constant". > > > I believe he argues that foo existed as two separate constants. He also says that if I write: foo = 6 foo = raw_input() then foo first exists as a constant and then as a variable (because it can then be anything, any value that the user inputs). From pgmoscatt at optushome.com.au Fri Apr 15 03:53:49 2005 From: pgmoscatt at optushome.com.au (Peter Moscatt) Date: Fri, 15 Apr 2005 17:53:49 +1000 Subject: Tk Listbox - Selected Item ? References: Message-ID: <425f722b$0$5849$9a6e19ea@news.newshosting.com> Martin Franklin wrote: > Peter Moscatt wrote: >> I am having trouble understanding the methods for the Listbox from Tk. >> >> If I was to select at item in the list using a mouse click (have already >> created the bind event) - what method returns the text of the selected >> item ? >> >> Pete >> > > > Pete, > > pydoc Tkinter.Listbox > > > > | curselection(self) > | Return list of indices of currently selected item. > | > | delete(self, first, last=None) > | Delete items from FIRST to LAST (not included). > | > | get(self, first, last=None) > | Get list of items from FIRST to LAST (not included). > > So to get the value of the selected item: > > lb.get(lb.curselection()[0]) > > > provided the listbox is in single selection mode or only one item is > selected > > Martin Thanks Martin, I used the: lb.get(lb.curselection()[0]) ant this works to a point. When I select the item in the listbox the system generates an error: Exception in Tkinter callback Traceback (most recent call last): File "/usr/lib/python2.3/lib-tk/Tkinter.py", line 1345, in __call__ return self.func(*args) File "/home/linux/programming/dxcluster/servers.py", line 37, in sel items = self.listbox.get(self.listbox.curselection()[0]) IndexError: tuple index out of range Then if I select a second time directly after the error message I get my desired result. Am I to you the code you quoted in your original message: > | curselection(self) > | Return list of indices of currently selected item. > | > | delete(self, first, last=None) > | Delete items from FIRST to LAST (not included). > | > | get(self, first, last=None) > | Get list of items from FIRST to LAST (not included). Pete From jepler at unpythonic.net Mon Apr 18 20:07:34 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 18 Apr 2005 19:07:34 -0500 Subject: New Python regex Doc (was: Python documentation moronicities) In-Reply-To: <1113856843.023012.165500@l41g2000cwc.googlegroups.com> References: <1113301533.054410.203710@z14g2000cwz.googlegroups.com> <1113856843.023012.165500@l41g2000cwc.googlegroups.com> Message-ID: <20050419000731.GA10263@unpythonic.net> On Mon, Apr 18, 2005 at 01:40:43PM -0700, Xah Lee wrote: > i have rewrote the Python's re module documentation. > See it here for table of content page: > http://xahlee.org/perl-python/python_re-write/lib/module-re.html For those who have long ago consigned Mr. Lee to a killfile, it looks like he's making an honest attempt to improve Python's documentation here. Mr Lee, I hope you will submit your documentation changes to python's patch tracker on sourceforge.net. I don't fully agree with some of what you've written (e.g., you give top billing to the use of functions like re.search while I would encourage use of the search method on compiled RE objetcts, and I like examples to be given as though from interactive sessions, complete with ">>>" and "..."), but nits can always be picked and I'm not the gatekeeper to Python's documentation. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From bokr at oz.net Thu Apr 28 13:25:28 2005 From: bokr at oz.net (Bengt Richter) Date: Thu, 28 Apr 2005 17:25:28 GMT Subject: creating very small types References: <427012B4.7090604@gmail.com> <42704f31.92576087@news.oz.net> Message-ID: <4270fbd4.136771827@news.oz.net> On Thu, 28 Apr 2005 05:07:34 GMT, bokr at oz.net (Bengt Richter) wrote: ... some not quite correct code ;-/ (I copy/pasted and created an illusion. My code dict has no EOS, so I decode pad zero bits as code that a single zero stands for ('a' in this case) so that was an oversight. I should have extended the coding some more or reserved perhaps 'F' as EOString, and tested for EOS in the decode stream. > This is revised, sorry. You can make a 'way more efficient decoder as an exercise ;-) Hint: if you make a dict of all the 2**width integers as keys where width is your widest code (4 here for 2**4), then you can do a single mask of 2**width-1 and look up the translation to (char, codewidth) directly, according to the codewidth least significant bits, if you make all the states of the other bits into keys that map to the same (char,codewidth). So for example all the even values of out 2**16 would have to map to ('a', 1) and all the values with 2 LSBs of 01 (of which there are 4) would map to ('b',2) and so forth. Thus the incrementing of width and trying one thing after another is not necessary. I think that will work ... Well, now Andrea has something to do ;-) >----< trivcodec.py >------------------------------------------------ #trivcodec.py EOS = '' import itertools def encode(stream): outchar = count = 0 for char in itertools.chain(stream, [EOS]): bits, width = codes[char] outchar |= (bits<= 8: yield chr(outchar&0xff) outchar >>= 8 count -= 8 if count: yield chr(outchar) def decode(stream): codebuf = count = 0 width = 1; char = None for codebyte in stream: codebyte = ord(codebyte) codebuf |= (codebyte<count: continue while width <= count: code = (codebuf&((1<>= width count -= width width = 1 if char == EOS: break width = 1 #trivial encoding dict: a=0 b=01 C=0011 D=0111 E=1011 EOS=1111 codes = {'a':(0x00,1), 'b':(0x01, 2), 'C':(0x3+0x4*0,4), 'D':(0x3+0x4*1,4), 'E':(0x3+0x4*2,4), EOS:(0x3+0x4*3,4)} chars = dict([(v,k) for k,v in codes.items()]) # reverse def test(*tests): if not tests: tests = ['abaDECbaabbD'] for charstream in tests: print codestream = ''.join(list(encode(charstream))) print '%r [%s] -(encode)-> %r [%s]' % ( charstream, len(charstream), codestream, len(codestream)) recovered = ''.join(list(decode(codestream))) print '%r [%s] -(decode)-> %r [%s]' % ( codestream, len(codestream), recovered, len(recovered)) if __name__ == '__main__': import sys test(*sys.argv[1:]) >-------------------------------------------------------------------- > >Result: Not really. Tack enough a's on the recovered chars to account for zero fill of the last encoded byte ;-/ > >[22:02] C:\pywk\clp>py24 trivcodec.py > >'abaFECbaabbDF' [13] -(encode)-> '\xf2;Q\xf7' [4] >'\xf2;Q\xf7' [4] -(decode)-> 'abaFECbaabbDF' [13] Fine, because the [4] bytes were totally filled. > >[22:02] C:\pywk\clp>py24 trivcodec.py a b C D E F > >'a' [1] -(encode)-> '\x00' [1] >'\x00' [1] -(decode)-> 'a' [1] Not so fine. There is no character serving as EOS mark. > >'b' [1] -(encode)-> '\x01' [1] >'\x01' [1] -(decode)-> 'b' [1] > >'C' [1] -(encode)-> '\x03' [1] >'\x03' [1] -(decode)-> 'C' [1] > >'D' [1] -(encode)-> '\x07' [1] >'\x07' [1] -(decode)-> 'D' [1] > >'E' [1] -(encode)-> '\x0b' [1] >'\x0b' [1] -(decode)-> 'E' [1] > >'F' [1] -(encode)-> '\x0f' [1] >'\x0f' [1] -(decode)-> 'F' [1] That really produced: [ 8:03] C:\pywk\clp>py24 trivcodec.py a b C D E F 'a' [1] -(encode)-> '\x00' [1] '\x00' [1] -(decode)-> 'aaaaaaaa' [8] 'b' [1] -(encode)-> '\x01' [1] '\x01' [1] -(decode)-> 'baaaaaa' [7] 'C' [1] -(encode)-> '\x03' [1] '\x03' [1] -(decode)-> 'Caaaa' [5] 'D' [1] -(encode)-> '\x07' [1] '\x07' [1] -(decode)-> 'Daaaa' [5] 'E' [1] -(encode)-> '\x0b' [1] '\x0b' [1] -(decode)-> 'Eaaaa' [5] 'F' [1] -(encode)-> '\x0f' [1] '\x0f' [1] -(decode)-> 'Faaaa' [5] So we need to assign a code as the EOS. And probably translate that to '' as the return char, and end on that. So now it does (having given up 1111 for EOS instead of F): [10:22] C:\pywk\clp>py24 trivcodec.py 'abaDECbaabbD' [12] -(encode)-> 'r;Q\xf7' [4] 'r;Q\xf7' [4] -(decode)-> 'abaDECbaabbD' [12] [10:22] C:\pywk\clp>py24 trivcodec.py a b C D E 'a' [1] -(encode)-> '\x1e' [1] '\x1e' [1] -(decode)-> 'a' [1] 'b' [1] -(encode)-> '=' [1] '=' [1] -(decode)-> 'b' [1] 'C' [1] -(encode)-> '\xf3' [1] '\xf3' [1] -(decode)-> 'C' [1] 'D' [1] -(encode)-> '\xf7' [1] '\xf7' [1] -(decode)-> 'D' [1] 'E' [1] -(encode)-> '\xfb' [1] '\xfb' [1] -(decode)-> 'E' [1] Goes to show you, eh? Slice and dice similar lines carefully ;-) Regards, Bengt Richter From mwm at mired.org Tue Apr 26 22:59:29 2005 From: mwm at mired.org (Mike Meyer) Date: Tue, 26 Apr 2005 21:59:29 -0500 Subject: python equivalent of php implode References: Message-ID: <8664y8lyb2.fsf@guru.mired.org> Jeff Epler writes: > items = query_param.items() > keys = [item[0] for item in items] > values = [item[1] for item in items] Is there some reason not to do: keys = query_params.keys() values = query_params.values() That would seem to be a lot more obvious as to what was going on. Thanks, http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From grante at visi.com Tue Apr 26 18:13:09 2005 From: grante at visi.com (Grant Edwards) Date: Tue, 26 Apr 2005 22:13:09 -0000 Subject: PyGTK vs. wxPython References: <1114444582.909431.245450@f14g2000cwb.googlegroups.com> <1114551965.718056.197480@g14g2000cwa.googlegroups.com> Message-ID: <116tf7lm0ivnl6c@corp.supernews.com> On 2005-04-26, dcrespo wrote: > Aparently, none of you has tried wxPython recently or properly. Not so. I'm using it currently and have been using it for a couple years now. > wxPython is a cross-platform toolkit. Currently supported platforms are > 32-bit Microsoft Windows, most Unix or unix-like systems, and Macintosh > OS X. Certainly, there may be Linux distributions where it doesn't run > well... I've no idea where that idea came from. It runs just fine on all the Linux distro's I've tried it on. >> The PyGTK is a better choice if you are writing for Linux and >> want your application to also be able to run on windows. > > I want exactly the opossite: my apps must be developed for > running primarly under Windows but also be able to run on > Linux. > > So, tell me PyGTK (with or without Glade/w XML output) or > entirely Python code through wxPython? Truely, what's the best > for CROSS-platform for both Linux and Windows? Not just for > Linux or just for Windows, but for both. Why don't you try them? I've only used PyGTK under Linux, so I can't vouche for it under Windows. Under Linux it worked fine for me. I've used wxPython under Linux and deployed on Windows. Worked fine for me. -- Grant Edwards grante Yow! If this is the DATING at GAME I want to know your visi.com FAVORITE PLANET! Do I get th' MICROWAVE MOPED? From gandalf at geochemsource.com Wed Apr 20 03:52:13 2005 From: gandalf at geochemsource.com (Laszlo Zsolt Nagy) Date: Wed, 20 Apr 2005 09:52:13 +0200 Subject: Python instances In-Reply-To: <1113983093.813565.23430@l41g2000cwc.googlegroups.com> References: <1113982340.156937.75530@f14g2000cwb.googlegroups.com> <1113983093.813565.23430@l41g2000cwc.googlegroups.com> Message-ID: <42660A2D.7030502@geochemsource.com> >Guess i shouldn't think of the __init__(self) function as a constructor >then. > > __init__ is THE constructor in Python -- _________________________________________________________________ Laszlo Nagy web: http://designasign.biz IT Consultant mail: gandalf at geochemsource.com Python forever! From claird at lairds.us Thu Apr 28 15:08:03 2005 From: claird at lairds.us (Cameron Laird) Date: Thu, 28 Apr 2005 19:08:03 GMT Subject: Getting the sender widget's name in function (Tkinter) References: <1114545565.116766.157000@f14g2000cwb.googlegroups.com> <42712098$0$26202$626a14ce@news.free.fr> Message-ID: <3rn7k2-ka5.ln1@lairds.us> In article <42712098$0$26202$626a14ce at news.free.fr>, tiissa wrote: . . . >So far, the OP is proposed the choice to either use the event/bind >mecanism or use different callbacks for his different buttons (either >with the method I proposed or not). Thanks, Tissa. Is there general understanding that "use different callbacks ..." can be implemented as "parametrize the same callback with a widget-specific value"? From claird at lairds.us Sun Apr 3 08:08:03 2005 From: claird at lairds.us (Cameron Laird) Date: Sun, 03 Apr 2005 12:08:03 GMT Subject: text analysis in python References: Message-ID: <1325i2-sd2.ln1@lairds.us> In article , Maurice Ling wrote: . . . >In the Java world, there is GATE (general architecture for text >engineering) and it seems very impressive. Are there something like that >for Python? . . . I don't know if you're aware that, in a fairly strong sense, anything "[i]n the Java world" *is* "for Python". If you program with Jython (for example--there are other ways to achieve much the same end), your source code can be in Python, but you have full access to any library coded in Java. From tiissa at nonfree.fr Mon Apr 18 16:38:55 2005 From: tiissa at nonfree.fr (tiissa) Date: Mon, 18 Apr 2005 22:38:55 +0200 Subject: Tkinter & Tkconstants In-Reply-To: <1113854966.648882.235040@l41g2000cwc.googlegroups.com> References: <1113854966.648882.235040@l41g2000cwc.googlegroups.com> Message-ID: <42641ade$0$18328$636a15ce@news.free.fr> codecraig wrote: > from Tkinter import * > > you have access to the constants in Tkconstants, since Tkinter imports > it automatically. Yes > However, in the shell if I do.. > > from Tkinter import * > > print Tkinter.HORIZONTAL > > I get an error..NameError: Tkinter is not defined Sure, you ask for Tkinter.HORIZONTAL. But if you directly ask for HORIZONTAL it should work. indeed your from statement imported the _content_ of the Tkinter module in the global namespace not the module in itself. It's either: from Tkinter import * print HORIZONTAL or: import Tkinter print Tkinter.HORIZONTAL or even: import Tkinter from Tkinter import * print HORIZONTAL,Tkinter.HORIZONTAL > > any ideas? I usually only use: import OneModule Or sometimes: from OneModule import OneClass, OneConstant But I usually don't import a whole module in my global namespace. > I get what i expect. but according to the tutorial i should only need > Tkinter. You do. From mahs at telcopartners.com Mon Apr 4 23:51:14 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Mon, 04 Apr 2005 20:51:14 -0700 Subject: Unexpected result when comparing method with variable In-Reply-To: <20050405033441.GA15819@arno2> References: <20050405033441.GA15819@arno2> Message-ID: David Handy wrote: > I had a program fail on me today because the following didn't work as I > expected: > > >>>>class C: > > ... def f(self): > ... pass > ... > >>>>c = C() >>>>m = c.f >>>>m is c.f > > False > > I would have expected that if I set a variable equal to a bound method, that > variable, for all intents and purposes, *is* that bound method, especially > since I hadn't changed or deleted anything on the class or its instance. > > The same thing happens when attempting to compare an unbound method with a > variable name bound to that unbound method: > > >>>>M = C.f >>>>M is C.f > > False > > If I were to guess what is going on here, I would say that the expression > c.f invokes a descriptor that manufactures a brand new "method object" each > time. Yes, I believe that's the case. See Martelli's recent 'Black Magic' PyCon presentation for some details of what's going on, but IIRC, the essence is that a bound method is produced by calling __get__ on the function, with the class/instance as the argument The problem is, this is non-intuitive (to me) and prevented me from > doing something I thought was useful. Agreed that: >>> class C(object): ... def f(self):pass ... >>> C.f is C.f False is surprising > > My use case is deferring operations till later, by placing tuples of a > method and its arguments in a list to be processed at some future time, but > doing some special-case processing only for certain methods: > > deferred = [] > ... > deferred.append((c.f, ('abc', 123))) > > ... > > for method, params in deferred: > method(*params) > if method is c.f: > # handle a special case > > But I can't do that special-case handling this way, I have to resort to some > other means to identify a method, "method is c.f" is always False. Which > seems strange to me. Another workaround is to compare method.im_func which does pass the identity test ... > > If I complain about this, would I get any sympathy? ;) > Sympathy, sure ;-) > Michael From philippe at philippecmartin.com Mon Apr 25 16:38:22 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Mon, 25 Apr 2005 20:38:22 GMT Subject: Python, Perl & PDF files References: Message-ID: <2zcbe.312$461.60@newssvr11.news.prodigy.com> This is highly frustrating !! Did Athena come to help or not ? Christos TZOTZIOY Georgiou wrote: > On Mon, 25 Apr 2005 10:32:11 -0400, rumours say that rbt > might have written: > >>I do not seek to provoke. Sorry if my question comes across that way to >>you. > > Thanks for giving attention to my post, no need for apologies. > > By the way, you didn't say in which way ReportLab and pdflib are not > helpful to you (packages suggested directly by Mike Meyer and indirectly > by me). From jack at performancedrivers.com Fri Apr 8 22:54:20 2005 From: jack at performancedrivers.com (Jack Diederich) Date: Fri, 8 Apr 2005 22:54:20 -0400 Subject: Puzzling OO design problem In-Reply-To: <1113010854.638038.173460@g14g2000cwa.googlegroups.com> References: <1113003772.020556.69550@l41g2000cwc.googlegroups.com> <1113010854.638038.173460@g14g2000cwa.googlegroups.com> Message-ID: <20050409025420.GB21924@performancedrivers.com> On Fri, Apr 08, 2005 at 06:40:54PM -0700, George Sakkis wrote: > > Err, you might want to explain what these things do instead of an > > abstract description of how you are doing it. It looks like you are > > using inheritance in the normal way _and_ you are using it to handle > > versioning of some kind (maybe stable interface releases? I don't > know). > > > > Let us know what parts need inheritance for, and what you have > > just been using a side effect of inheritance for as a convenience > > (versioning, I think). > > > > A more concrete example would be easier to comment on, if possible > > do a simple one (maybe just two classes with two versions each). > > > > -jackdied > > I intentionally abstracted the problem to remove the irrelevant > details, but here's a more concrete (though still simplified) example. > I hope it is more clear now. > def worldModelFactory(version): > if version < 2: return WorldModel() > else: return WorldModel_v2() > > class WorldModel_v1(object): > class Player(object): > def foo(self): pass # v1 implementation of foo() > > class WorldModel_v2(object): > class Player(WorldModel_v2.Player): > def foo(self): pass # v2 implementation of foo() So you are using the WorldModel_* classes as a namespace to hold a set of classes that might inherit and extend or redefine the previous classes in a WorldModel_* namespace. This seems to do what you wanted in your original post, namely if a class is defined in v1 but not in v2 that v2 would just use v1's implementation. WorldModel_v2 will inherit Player from _v1 by default, so that should work OK out of the box. So you should be fine there, but I think your question is more practical than "what is the proper OO way to do it?" which is a bit of a shibboleth in python. We like "what is easiest and readable?" So here are some practical recommendations (well, at least that's my intention). Are you using the *_v1 naming convention for backwards compatibility? Backwards compatibility is a giant pain in the ass, I notice you are posting from a .edu address so if this is just something you are working on by yourself or in a small group drop the versioning aspects from the code. Talking to the other people in the group is easier. >From your example (which I over-pruned) it looks like you are using the WorldModel namespace to define parameters for running an iteration of a game. The classes under "WorldModel" are something like the rules/physics definition (MovableObject), coordinates of the team-A goalpost, coordinates of the team-B goalpost, team-A strategy (Player), and team-B strategy (also Player). WorldModel would be the gameboard. If so, make WorldModel just a board - drop putting Player etc under it as a namespace, and give it a run() function that takes parameters. Name the Player derivatives as PlayerDumb, PlayerSmart, PlayerAggressive etc, you'll probably have a lot more of those than goals or physics rules. The actual main routine would look something like ob = WorldModel() # standard 100x100 board winner = ob.run(physics=MovableObject, # defines friction and gravity team_a_goal=(50,25), team_b_goal=(5,5), team_a_strategy=PlayerDumb, team_b_strategy=PlayerAggressive, ) print "Winner is ", winner I wrote more than I meant to, but the basic idea is don't use classes when you don't need to - it just makes things more complex. That should give you more time to tackle the interesting parts (player strategies, I'd imagine). -jackdied From radam2 at tampabay.rr.com Fri Apr 1 12:37:40 2005 From: radam2 at tampabay.rr.com (Ron_Adam) Date: Fri, 01 Apr 2005 17:37:40 GMT Subject: Case-insensitive dict, non-destructive, fast, anyone? References: Message-ID: On 01 Apr 2005 15:55:58 +0300, Ville Vainio wrote: >>>>>> "Daniel" == Daniel Dittmar writes: > > Daniel> Ville Vainio wrote: > > >> I need a dict (well, it would be optimal anyway) class that > >> stores the keys as strings without coercing the case to upper > >> or lower, but still provides fast lookup (i.e. uses hash > >> table). > > Daniel> Store the original key together with the value and use a > Daniel> lowercase key for lookup. > >That's what I thought initially, but the strings take most of the >space in dict and I didn't feel like doubling the size. > >It would be the "simplest thing that could possibly work", though. Try access the keys indirectly though another dictionary. That way you don't have to change the original. Lkeys = {} for k dict.keys(): Lkeys[ k.lower] = dict[k] Then use: value = dict[ Lkeys[ key.lower() ] ] To get your value from the original dictionary. Watch out for duplicate keys in differing case in the original dict. Ron From tores at stud.cs.uit.no Thu Apr 14 10:55:49 2005 From: tores at stud.cs.uit.no (Tor Erik Sønvisen) Date: Thu, 14 Apr 2005 16:55:49 +0200 Subject: EOF-file missing Message-ID: Hi >From a client I read a file into a string using read(). On the server-side (it's a HTTPServer) i access the same string through the input stream rfile. However all useful read-methods (readlines, readline, read) expect an EOF before terminating. And for some reason the stream doesn't have the seek method either, so it's impossible to set the file-pointer to the end of the stream. how can I access the whole string then? Is it possible to add an EOF to the string before sending it from the client? Or maybe there are other solutions? regards From zsolt-googleP6463 at mailblocks.com Wed Apr 13 17:01:49 2005 From: zsolt-googleP6463 at mailblocks.com (pythonUser_07) Date: 13 Apr 2005 14:01:49 -0700 Subject: Programming Language for Systems Administrator In-Reply-To: <1113253691.821235.9750@o13g2000cwo.googlegroups.com> References: <1113253691.821235.9750@o13g2000cwo.googlegroups.com> Message-ID: <1113422698.396417.45280@l41g2000cwc.googlegroups.com> Python is great, but having much "admin" type experience, I've found python to be less than Ideal when dealing with system calls and standard Input Ouput. For example, I've written complex tools that use perforce, I've taken advantage of both regular IO and the perforce marshalled IO. Under heavy load, some of the threads in my scripts experience IO hang (Linux and WIndows) (solaris and BSD were fine). I did not get the same behavior with Perl. Having said that I still do 99% of my utilities in python. Just be aware. From cam.ac.uk at mh391.invalid Fri Apr 29 19:40:50 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sat, 30 Apr 2005 00:40:50 +0100 Subject: Best way to parse file into db-type layout? In-Reply-To: References: <7v1371pn9gvsh52m7nld6ddjm9b9k3elgf@4ax.com> Message-ID: John Machin wrote: > [Michael Hoffman]: >>John Machin wrote: >>>[Michael Hoffman]: >>> >>>>for row in csv.reader(fileinput.input()): >>> >>>csv.reader requires that if the first arg is a file that it be opened >>>in binary mode. >> >>fileinput.input() is not a file. > > Hair-splitter. Is name-calling really necessary? > It's an awk simulation and shouldn't be used for real-world data. I don't see why not, so long as your data is text. >>I have tested this code and it works fine for the provided example. > > Well I've got news for you: real-world data has embedded CRs, LFs and > (worst of all) ^Zs often enough, and you won't find them mentioned in > any documentation, nor find them in examples. That's nice. Well I agree with you, if the OP is concerned about embedded CRs, LFs and ^Zs in his data (and he is using Windows in the latter case), then he *definitely* shouldn't use fileinput. And otherwise, there's really no reason not to. -- Michael Hoffman From mylastnameruntogether at mycompanyname.com Tue Apr 12 12:10:15 2005 From: mylastnameruntogether at mycompanyname.com (Brandon J. Van Every) Date: Tue, 12 Apr 2005 16:10:15 GMT Subject: web authoring tools References: Message-ID: Steve Holden wrote in > Brandon J. Van Every wrote: >> >> I believe Dreamweaver-esque. I see myself writing articles and >> eventually doing snazzy eye candy layouts. I do not see myself >> engaging in elaborate flow control or anything terribly programmatic. >> I want to concentrate on the content, not the mechanism. >> >> > I've stayed out of this one so far because of a natural disinclination > to join religious discussions, but sine we are now talking good common > sense I'd like to ask whether a *batch-oriented* system for folding > database content into a static web site with common look-and-feel > would be of interest. > > Now PyCon is over I've been able to blog about the techniques used to > generate the web site at http://www.holdenweb.com/, and most recently > about using reStructured Text in the database to ease authorship > problems for the less-taxing content. See > > http://www.holdenweb.com/blogs/2005/04/versioned-reviews-implemented-po > st.html > > to determine whether the overall approach would work for you. I have 2 goals: 1) to worry about plumbing as little as possible, as I generate articles and content. Once a framework is established, this can be handled "cookie cutter." 2) to create a unique brand identity based on good eye candy. For this part of the problem, the website cannot look generic. At a minimum, I would need a facility that allows me to painlessly arrange my own 2D artwork. -- Cheers, www.indiegamedesign.com Brandon Van Every Seattle, WA "The pioneer is the one with the arrows in his back." - anonymous entrepreneur From bdesth.quelquechose at free.quelquepart.fr Sun Apr 24 15:47:55 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 24 Apr 2005 21:47:55 +0200 Subject: Python or PHP? In-Reply-To: <1114254894.512656.297040@l41g2000cwc.googlegroups.com> References: <1114254894.512656.297040@l41g2000cwc.googlegroups.com> Message-ID: <426bf398$0$20479$626a14ce@news.free.fr> Lad a troll? : > Is anyone capable of providing Python advantages over PHP if there are > any? Why don't you check by yourself ? From dcrespo at gmail.com Tue Apr 26 17:46:05 2005 From: dcrespo at gmail.com (dcrespo) Date: 26 Apr 2005 14:46:05 -0700 Subject: PyGTK vs. wxPython In-Reply-To: References: <1114444582.909431.245450@f14g2000cwb.googlegroups.com> Message-ID: <1114551965.718056.197480@g14g2000cwa.googlegroups.com> Hi all... Thank you for your answers... wxPython, under Linux, tries to use GTK... A better way to say it is: wxPython uses whatever it needs: under Windows, his API; under Linux, his API (may imply the use of GTK or GNOME), etc... Aparently, none of you has tried wxPython recently or properly. wxPython is a cross-platform toolkit. Currently supported platforms are 32-bit Microsoft Windows, most Unix or unix-like systems, and Macintosh OS X. Certainly, there may be Linux distributions where it doesn't run well... > The PyGTK is a better choice if you are writing for > Linux and want your application to also be able to run on windows. I want exactly the opossite: my apps must be developed for running primarly under Windows but also be able to run on Linux. So, tell me PyGTK (with or without Glade/w XML output) or entirely Python code through wxPython? Truely, what's the best for CROSS-platform for both Linux and Windows? Not just for Linux or just for Windows, but for both. Anyone who had used any a lot? Thanks Daniel From tjreedy at udel.edu Fri Apr 1 14:23:31 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 1 Apr 2005 14:23:31 -0500 Subject: Pseudocode in the wikipedia References: <1112362451.848227.208120@z14g2000cwz.googlegroups.com> Message-ID: wrote in message news:1112362451.848227.208120 at z14g2000cwz.googlegroups.com... > The free wikipedia is adopting a standard pseudocode: > http://en.wikipedia.org/wiki/Wikipedia_talk:Wikicode/Specification > > MShonle says something nice: Calling a feature 'baggage' is not especially nice. Neither is getting facts wrong. > I support the idea of wikicode. Basically I think we should present > code in a Python-like language that doesn't carry so much baggage. For > example, we can use English sentences (or sentence fragments) instead > of requiring the reader to understand some obscure Python library. > (Further, Python has the baggage that there are no block-terminators: Python does too have block terminators. They are called dedents. In doing so it follows standard English outline formatting and the practice of many algorithm pseudocode writers. (I roughly estimate around half or more.) Two examples I have handy: Jon Bently in Programming Pearls and Steven Skiena in The Algorithm Design Manual. > i.e., no "}" or "end"s or "fi"s or "repeat"s. So add #whateve-ender-you want, but leave the code executable if at all possible. > By adding such terminators, we can make it a lot less ambiguous to all > readers. Dedents are unambiguous. Be adding additional redundant terminators, one adds the possibility of mismatch and ambiguity. Terry J. Reedy From cpl.19.ghum at spamgourmet.com Sat Apr 23 10:41:16 2005 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Sat, 23 Apr 2005 14:41:16 +0000 (UTC) Subject: a=[ lambda t: t**n for n in range(4) ] References: <42698692$1@nntp0.pdx.net> Message-ID: Mage wrote in news:mailman.2339.1114242211.1799.python- > The "lambda functions" was an unclear part of the tutorial I read. > Should I use them? Are they pythonic? > As far I see they are good only for type less a bit. And to obfusicate code. lambda is evil, do not play with it. Harald From greg at cosc.canterbury.ac.nz Thu Apr 7 23:30:03 2005 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Fri, 08 Apr 2005 15:30:03 +1200 Subject: Using weakrefs instead of __del__ In-Reply-To: <1112808016.630995.87690@l41g2000cwc.googlegroups.com> References: <1112808016.630995.87690@l41g2000cwc.googlegroups.com> Message-ID: <3bmc6aF6jt8okU1@individual.net> Rhamphoryncus wrote: > class RealFoo: > refs = set() > def __init__(self, front): > self.refs.add(weakref.ref(front, self.cleanup)) > def blah(self): > print "Blah!" > def cleanup(self, ref): > print "Doing cleanup" > self.refs.remove(ref) That won't work, because the bound method you're using as the cleanup function contains a reference to the object, preventing it from being deallocated. The weakref callback is only called *after* the object has been deallocated. If you try to contrive a way of passing the object to the callback, you will just end up keeping it alive. To use a weakref as a finalizer, the information needed for finalization needs to be kept somewhere outside of the object triggering the finalization. This may be what you were trying to achieve by separating your object into a Foo and a RealFoo. If that's so, you should have made the weak ref point to the Foo, not the RealFoo. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From thesonoftruth at aol.com Mon Apr 18 03:02:23 2005 From: thesonoftruth at aol.com (thesonoftruth) Date: 18 Apr 2005 00:02:23 -0700 Subject: Do You Want To Know For Sure That You Are Going To Heaven? The reason some people don't know for sure if they are going to Heaven when they die is because they just don't know. The good news is that you can know for sure that you are going to Heaven wh References: <1113707535.383715.327170@g14g2000cwa.googlegroups.com> Message-ID: <1113806696.907908.323410@g14g2000cwa.googlegroups.com> I wonder if anyone yells VISHNU !! VISHNUUUUUUUUUUUUU ! when making out, From yhdanid at yahoo.com Sat Apr 30 15:44:28 2005 From: yhdanid at yahoo.com (Obaid R.) Date: 30 Apr 2005 12:44:28 -0700 Subject: Ron Grossi: God is not a man References: <1114098221.580669.86300@g14g2000cwa.googlegroups.com> <1114127633.859113.292290@l41g2000cwc.googlegroups.com> <#2tJ0r3RFHA.3664@TK2MSFTNGP15.phx.gbl> <1114328806.147822.64660@z14g2000cwz.googlegroups.com> <1114329202.229148.82550@o13g2000cwo.googlegroups.com> <1114654290.690332.155200@f14g2000cwb.googlegroups.com> <3dc8hjF6s5i2uU1@individual.net> <3desu2F6qoj7aU1@individual.net> <#ATbpqMTFHA.3980@TK2MSFTNGP12.phx.gbl> <1114831490.664193.236140@l41g2000cwc.googlegroups.com> Message-ID: <1114890268.799739.309290@g14g2000cwa.googlegroups.com> Donald L McDaniel wrote: > 1) I am posting to a newsgroup on the Microsoft Usenet Server. It's not my > fault the demon-lover who posted the original anti-Christian article > cross-posted to so many newsgroups across so many servers. Talk to him > about cross-posting. > 1) I will go away, when Christ returns for me. I hope you are ready for His > return, else you are in for a living Hell here on the Earth before the REAL > Hell rises up to swallow you in its Flames. > > -- > Donald L McDaniel > Please reply to the original thread, > so that the thread may be kept intact. > ============================== And the demon lover would be the one who quotes from the "word of God" as reported in your own Bible which proclaims that "God is not a man ... neither the son of man" (Numbers 23: 19)? Is it your contention that this is demonic truth? See what the world is comming to? And it was not I who originally cross-posted as you claim. I was replying to Mr. Grossi who did start the cross-posting. Does your words: "the demon-lover who posted the original anti-Christian article cross-posted to so many newsgroups across so many servers" apply to him? Here is a quote from the head of his original post: >From: RonGrossi382... at yahoo.com >Newsgroups: Microsoft.public.windowsxp.network_web,rec.music.beatles,rec.music.makers.guitar.acoustic,alt.showbiz.gossip,comp.lang.python In case you are interested in comparitive religion then maybe these links might be of help: Qur'an: ======= [1] Download a free Qur'an viewer: http://www.divineislam.co.uk/ Audio: ====== [1] Christ in Islam - Parts 1, 2 & 3; a lecture by Ahmed Deedat. http://islam.org/audio/ra622_1.ram [2] Crucification: Fact or Fiction - Parts 1, & 2; a Christain Muslim debate in the USA with a Christian and Muslim audience in attendence. http://islam.org/audio/ra622_3.ram [3] Is the Bible God's Word - Parts 1, & 2; a Christian Muslim debate in the USA with a Christian and Muslim audience in attendence. http://islam.org/audio/ra622_4.ram [4] Audio & Video Files; Misc. topics. http://www.beconvinced.com/SPEECHES.htm Articles and booklets: ====================== [1] Christ In Islam by Sheikh Ahmad Deedat. http://www.thestraightway.com/literature/0011.html [2] What Does the Bible Say about Mohammed (PBUH)? by Sheikh Ahmad Deedat. http://www.thestraightway.com/literature/0014.html [3] The God That Never Was by Sheikh Ahmad Deedat. http://www.thestraightway.com/literature/0016.html [4] What was the Sign of Jonah? by Sheikh Ahmad Deedat. http://www.thestraightway.com/literature/0017.html [5] Who moved the Stone? by Sheikh Ahmad Deedat. http://www.thestraightway.com/literature/0018.html [6] Resurrection or Resuscitation? by Sheikh Ahmad Deedat. http://www.thestraightway.com/literature/0019.html [7] Other work by Sheikh Ahmed Deedat. http://www.jamaat.net/deedat.htm From fredrik at pythonware.com Tue Apr 12 05:44:20 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 12 Apr 2005 11:44:20 +0200 Subject: Python 2.4 killing commercial Windows Python development ? References: <425a9869$0$38039$bed64819@news.gradwell.net><20050411194907.1769.17472.XPN@orion.homeinvalid> <425AF2FD.2080006@v.loewis.de> Message-ID: Martin v. L?wis wrote: >> What happens if I try to install Python2.4 on a system wich doesn't have >> the dll? > > It will just work. Python installs the DLL if it is missing, and leaves > it alone (just incrementing the refcount) if it is present on the target > system. installs it where? the MS docs seem to indicate that they want you to install it in the program directory, rather than in a "shared" location: http://support.microsoft.com/default.aspx?scid=kb;en-us;326922 From rodney.maxwell at gmail.com Sun Apr 17 21:16:28 2005 From: rodney.maxwell at gmail.com (Rodney Maxwell) Date: 17 Apr 2005 18:16:28 -0700 Subject: python.exe on Mac OS X!? In-Reply-To: References: <1113777681.330094.34320@l41g2000cwc.googlegroups.com> Message-ID: <1113786988.312168.265180@g14g2000cwa.googlegroups.com> > The default file system on MacOSX is case insensitive. As a result the .exe > extension is required to disambiguate the generated executable from the > Python directory in the source distro. OK. I got it. From dan at dontspammecauseidontlikit.com Wed Apr 13 20:50:07 2005 From: dan at dontspammecauseidontlikit.com (Dan) Date: Thu, 14 Apr 2005 08:50:07 +0800 Subject: Can't Stop Process On Windows References: Message-ID: On Tue, 12 Apr 2005 06:53:04 -0600, Dave Brueck wrote: >Are you calling select with a long timeout? An alternative would be to call >select with a much shorter timeout, but call it multiple times from a loop. That seems to have fixed the problem. Changed it from no timeout to one second. Thanks Dan From mahs at telcopartners.com Fri Apr 15 00:17:54 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Thu, 14 Apr 2005 21:17:54 -0700 Subject: pythonic use of properties? In-Reply-To: <5e183f3d05041420053ecd0ee@mail.gmail.com> References: <5e183f3d05041420053ecd0ee@mail.gmail.com> Message-ID: Marcus Goldfish wrote: > I'd like advice/opinions on when it is appropriate to do Just an opinion... > attribute/property validation in python. I'm coming from a C#/Java > background, where of course tons of "wasted" code is devoted to > property validation. Here is a toy example illustrating my question: > > # Example: mixing instance attributes with properties. Is it pythonic to > # validate property data in setters? Since tens and ones are never > # validated, the class can be "broken" by setting these directly > class SillyDecimal(object): > """A silly class to represent an integer from 0 - 99.""" > def __init__(self, arg=17): > if isinstance(arg, tuple): > self.tens = arg[0] > self.ones = arg[1] > else: > self.number = arg > > def getNumber(self): > return self.tens*10 + self.ones > def setNumber(self, value): > if value < 0 or value > 99: > raise ArgumentException("Must in [0, 99]") > self.tens = value // 10 > self.ones = value % 10 > number = property(getNumber, setNumber, None, "Complete number, [0-99]") It is conventional to indicate 'private' attributes with the _ prefix. By this standard, you have three 'public' interfaces: number, get/setNumber and ones/tens, which is confusing and error-prone. Moreover, if you are going to validate number, it might make more sense to put all the validation logic into the setter vs. splitting some into __init__. So your class could look like: class SillyDecimal1(object): """A silly class to represent an integer from 0 - 99.""" def __init__(self, value = 17): self.number = value def _getNumber(self): return self._tens*10 + self._ones def _setNumber(self, value): if isinstance(value, tuple): value = value[0] * 10 + value[1] if value in range(100): self._tens = value /10 self._ones = value % 10 else: raise ValueError, "Number out of range(100)" number = property(_getNumber, _setNumber, None, "Complete number, [0-99]" There is nothing to stop a user from setting _tens and _ones directly, but their names indicate that this should not be done. As for whether it is appropriate to validate the value at all, I think that depends on your larger design. Note that one of the main purposes of properties is retrofitting bare attributes with getters/setters. So, an initial version of your class might be: class SillyDecimal0(object): """A silly class to represent an integer from 0 - 99.""" def __init__(self, value = 17): self.number = value Later you can add the getter/setter/property logic if it turns out to be necessary, without changing the interface (except for the addition of a couple of 'private' attributes and 'private' methods, which well-behaved callers should not touch anyway. Michael From fredrik at pythonware.com Tue Apr 19 06:24:22 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 19 Apr 2005 12:24:22 +0200 Subject: Why does python class have not private methods? Will this neverchanged? References: <311b5ce105041902165a0969a0@mail.gmail.com> Message-ID: "could ildg" wrote: > Private stuff always makes programming much easier. says who? From simon.brunning at gmail.com Wed Apr 6 11:50:19 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Wed, 6 Apr 2005 16:50:19 +0100 Subject: Lambda: the Ultimate Design Flaw In-Reply-To: <4253fe0c$1@nntp0.pdx.net> References: <4253fe0c$1@nntp0.pdx.net> Message-ID: <8c7f10c6050406085020a24b44@mail.gmail.com> On Apr 6, 2005 4:42 PM, Scott David Daniels wrote: > I've always wondered about this turn of phrase. I seldom > eat a cake at one sitting. Clearly you're just not trying. ;-) -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From dmj111.9352919 at bloglines.com Fri Apr 8 22:14:52 2005 From: dmj111.9352919 at bloglines.com (David Jones) Date: Fri, 08 Apr 2005 22:14:52 -0400 Subject: Python extension performance Message-ID: Hi, I am trying to hunt down the difference in performance between some raw C++ code and calling the C++ code from Python. My goal is to use Python to control a bunch of number crunching code, and I need to show that this will not incur a (big) performance hit. This post includes a description of my problem, ideas I have for the cause, and some things I plan to try next week. If anyone knows the real cause, or thinks any of my ideas are way off base, I would appreciate hearing about it. My C++ function (testfunction) runs in 2.9 seconds when called from a C++ program, but runs in 4.3 seconds when called from Python. testfunction calculates its own running time with calls to clock(), and this is for only one iteration, so none of the time is in the SWIG code or Python. Both the C++ executable and python module were linked from the same object files, and linked with the same options. The only difference is that the Python module is linked with -shared, and the C++ code is not. The computer is an Itanium 2. The code was compiled with the Intel Compiler, and uses the Intel Math Libraries. Python is version 2.2 (with little hope of being able to upgrade) from the Red Hat rpm install. When I link the C++ exe, I get some warnings about "log2l not implemented" from libimf, but I do not see these when I link the Python .so. Some potential causes of my problems: - linking to a shared library instead building a static exe. - intel libraries are not being used when I think they are - libpython.so was built with gcc, so I am getting some link issues - can linking to python affect my memory allocation and deallocation in c++?? Some things I can try: - recompile python with the intel compiler and try again - compile my extension into a python interpreter, statically - segregate the memory allocations from the numerical work and compare how the C++ and Python versions compare --end brain dump Dave From mcfletch at rogers.com Mon Apr 18 12:55:16 2005 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Mon, 18 Apr 2005 12:55:16 -0400 Subject: Any movement on FreeBSD segfaults when using threads? Message-ID: <4263E674.8060406@rogers.com> There was a post a few months ago from "snacktime" in which they described a failure when running under Twisted: http://mail.python.org/pipermail/python-list/2005-February/265137.html which they eventually narrowed down to an apparent problem with pycrypto: http://mail.python.org/pipermail/python-list/2005-February/265146.html and which generated this sourceforge bug report for Python: http://twistedmatrix.com/pipermail/twisted-python/2005-February/009475.html http://sourceforge.net/tracker/index.php?func=detail&aid=1080660&group_id=5470&atid=105470 I am seeing a similar effect, (though only after the program has been running a few days), in one of our products running on FreeBSD 5.3-RC2 with Python 2.3.4, PyOpenSSL 0.6, Twisted 2.0, and PyPgSQL 2.4 (which is somewhat different than snacktime's library collection (different OpenSSL and PostgreSQL bindings)). Note particularly, that the PyCrypto library to which the problem was apparently localised is *not* installed on the failing machine. As with snacktime, I see the failure coming from pthread_testcancel() (gdb) bt #0 0x28222f17 in pthread_testcancel () from /usr/lib/libpthread.so.1 #1 0x2821b39f in pthread_mutexattr_init () from /usr/lib/libpthread.so.1 #2 0x00000000 in ?? () I haven't been able to isolate the failures to a particular piece of code (this is showing up on a live server, so I'm hesitant to run under gdb for a couple of days to try to catch the failure). I'm *not* using RSA encryption (which was the area to which snacktime localised their problem). I *do* use SSL sockets from Twisted, however. I am running a background thread for database access, with a Queue mediating the set of items to process and reactor.callFromThread returning control to Twisted when the items are finished. Anyway, my question is really "has this been solved already"? If so, what was the solution? If not, I'll have to work at building a minimal failing test case so I can begin to debug it. Thanks for any information, Mike -- ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From rkern at ucsd.edu Wed Apr 27 13:30:26 2005 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 27 Apr 2005 10:30:26 -0700 Subject: How do I parse this ? regexp ? In-Reply-To: <1114620387.283743.163460@z14g2000cwz.googlegroups.com> References: <1114620387.283743.163460@z14g2000cwz.googlegroups.com> Message-ID: serpent17 at gmail.com wrote: > Thank you, it works, but I guess not all the way: > > for instance, I have this: > 04242005 18:20:42-0.024329, 271.2469504, [-4.097900390625, > 3.4332275390625, 105.062255859375], [0.0384521484375, 0.08416748046875, > -1.026885986328125], [0.00640869140625, 0.00885009765625, > 0.00701904296875] > > translates into > > > '04242005 18:20:42-0.024329 271.2469504 -4.097900390625 > 3.4332275390625 105.062255859375 0.0384521484375 0.08416748046875 > -1.026885986328125 0.00640869140625 0.00885009765625 > 0.00701904296875 \n' > > but I need to remove the first - between 18:20:42 and 0.024329 but not > the others. Use the find() method on the string to locate the index of this first '-', then break the line into two parts before and after the '-'. You should spend some quality time with the string documentation to internalize the possibilities for yourself. There's only so much work we can do for you. Also, take a look at David Mertz's fine _Text Processing in Python_ available in dead-tree form or online. http://gnosis.cx/TPiP/ -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From cam.ac.uk at mh391.invalid Sat Apr 30 06:35:05 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sat, 30 Apr 2005 11:35:05 +0100 Subject: Best way to parse file into db-type layout? In-Reply-To: References: <7v1371pn9gvsh52m7nld6ddjm9b9k3elgf@4ax.com> Message-ID: John Machin wrote: > I beg your pardon. How does: "Your point addresses the letter rather > than the spirit of the 'law'" sound? Sure, thanks. > Real-world data is not "text". A lot of real-world data is. For example, almost all of the data I deal with is text. >>That's nice. Well I agree with you, if the OP is concerned about embedded >>CRs, LFs and ^Zs in his data (and he is using Windows in the latter case), >>then he *definitely* shouldn't use fileinput. > > And if the OP is naive enough not to be concerned, then it's OK, is > it? It simply isn't a problem in some real-world problem domains. And if there are control characters the OP didn't expect in the input, and csv loads it without complaint, I would say that he is likely to have other problems once he's processing it. > Except, perhaps, the reason stated in fileinput.py itself: > > """ > Performance: this module is unfortunately one of the slower ways of > processing large numbers of input lines. > """ Fair enough, although Python is full of useful things that save the programmer's time at the expense of that of the CPU, and this is frequently considered a Good Thing. Let me ask you this, are you simply opposed to something like fileinput in principle or is it only because of (1) no binary mode, and (2) poor performance? Because those are both things that could be fixed. I think fileinput is so useful that I'm willing to spend some time working on it when I have some. -- Michael Hoffman From mahs at telcopartners.com Sat Apr 9 12:36:46 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Sat, 09 Apr 2005 09:36:46 -0700 Subject: Are circular dependencies possible in Python? In-Reply-To: References: Message-ID: Tim Tyler wrote: > Like C, Python seems to insist I declare functions before calling > them - rather than, say, scanning to the end of the current script > when it can't immediately find what function I'm referring to. > > C lets you predeclare functions to allow for the existence of > functions with circular dependencies. > > Does Python allow you to do something similar? > > If not how do you create functions with circular dependencies in > Python - where function A could call function B; and function > B could call function A - or is that not possible? Of course, for example: def A(*args): if len(args) > 1: print "Calling B%s" % repr(args[1:]) return B(*args[1:]) else: print "A Called with: %s" % args[0] def B(*args): if len(args) > 1: print "Calling A%s" % repr(args[1:]) return A(*args[1:]) else: print "B Called with: %s" % args[0] >>> A("Arg1","Arg2","Arg3","Arg4") Calling B('Arg2', 'Arg3', 'Arg4') Calling A('Arg3', 'Arg4') Calling B('Arg4',) B Called with: Arg4 >>> Functions have to exist before you call them, but they are not 'declared'. def and its enclosed suite is a statement, like print, while, etc... The def statement is executed to define the function. For functions defined at module level, this statement is executed when the module is first imported (or reloaded) in source-code order along with any other module-level code. Executing a def statement compiles (but does not execute) the body of the function. Each function, when def'd also gets a reference to the global scope in which it is defined. When you execute the function body (by calling the function), identifiers that are not resolved in the functions own local scope are looked up in this global scope. So in the example above, the body of A calls B. B is not defined in A's local scope, so it is looked up in A's globals, which is the module. As long as def B(... has been executed in the same module before you first call A, everything is fine. Michael From bvande at po-box.mcgill.ca Fri Apr 22 11:39:03 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Fri, 22 Apr 2005 11:39:03 -0400 Subject: Overiding error message when using a python program In-Reply-To: <1114181140.609745.192580@g14g2000cwa.googlegroups.com> References: <1114181140.609745.192580@g14g2000cwa.googlegroups.com> Message-ID: <42691A97.8030406@po-box.mcgill.ca> aleksander.helgaker at gmail.com said unto the world upon 2005-04-22 10:45: > I've completely rewritten a calculator I wrote to help me learn Python. > After someone told me about the def command I reliesed that I could > make the program much better, but there is a very anoying problem which > ocours when I run the program. > > Here is the code > > # IMPOSRTS # > import sys > import os > > # DEF'S # > def print_intro(): > os.system('clear') > print "Welcome to Calc v 0.1a" > print "----------------------" > > def main(): > print_intro() > while True: > prompt_user() > > def prompt_user(): > userinput = input(">") > > def fib(n): # write Fibonacci series up to n > """Print a Fibonacci series up to n.""" > a, b = 0, 1 > while b < n: > print b, > a, b = b, a+b > print > > def quit(): > sys.exit() > > # PROGRAM FLOW > main() > > > Now when I run this program and I type in a command which I have no > code for e.g. "pi" (which is 3,14....) I get the error message > "NameError: name 'pi' is not defined" and then the program quits. > > I'm creating this program for my own use but naturally sometimes I > would make spelling mistakes (being a dyslexic and all) and so having a > long error message and having the program quit is more then a bit > irritating. It would be much more preferable if the program simply > wrote "Command not recognised" and then kept going. Is this possible? > Sure, its possible. How to do it from where you are is a bit more dark; you've not included the part of your code which acts on the user's input. (And your prompt_user function should use raw_input and return the user input for processing by other functions. raw_input is safer; input executes arbitrary code.) I see just before sending, that you seemed happy with Simon Brunning's suggestion. But, as I hate to waste the typing, here's another way sketched: def funct1(): print 'This is funct1' def funct2(): print 'This is funct2' funct_dict = {'1': funct1, '2': funct2} # strings as keys because of raw_input # functions are objects, and thus can be values in a dict def prompt_user(): return raw_input('Well?') def dispatch(request): function = funct_dict.get(request, None) if function: function() else: print 'You entered %s, but there is no such command' %request Put that in a script and run dispatch(prompt_user()) and you should see the desired behaviour. I will leave integrating the idea into the structure you have as yet to you. HTH, Brian vdB From modelnine at ceosg.de Sat Apr 30 16:28:10 2005 From: modelnine at ceosg.de (Heiko Wundram) Date: Sat, 30 Apr 2005 22:28:10 +0200 Subject: Writing to log file when script is killed In-Reply-To: <1114864012.637007.295800@z14g2000cwz.googlegroups.com> References: <1114851873.072376.225820@z14g2000cwz.googlegroups.com> <1114864012.637007.295800@z14g2000cwz.googlegroups.com> Message-ID: <200504302228.13863.modelnine@ceosg.de> Am Samstag, 30. April 2005 14:26 schrieb wittempj at hotmail.com: > If you run on unix you can use the signal module to intercept a kill - > see http://docs.python.org/lib/node368.html for a quick example You cannot intercept a kill (that's the whole meaning of SIGKILL, rather than SIGTERM)... Read up on UNIX signal handling. But, for the rest: you could intercept SIGTERM, log a message, and raise a SystemExit exception. That should do the trick. -- --- Heiko. see you at: http://www.stud.mh-hannover.de/~hwundram/wordpress/ -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From martin at v.loewis.de Mon Apr 18 13:34:12 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 18 Apr 2005 19:34:12 +0200 Subject: EasyDialogs module problem with python 2.4.1 In-Reply-To: References: Message-ID: <4263EF94.9060806@v.loewis.de> scott wrote: > EasyDialogs module > > ( http://www.python.org/doc/2.4.1/mac/module-EasyDialogs.html ) > > works with pyshell (interactive python program included with wxPython) > but not with python launched at the terminal: Could you be more precise what "works not" means? What do you expect to happen, what happens instead? Did you try pythonw? Regards, Martin From steve at holdenweb.com Thu Apr 7 12:51:45 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 07 Apr 2005 12:51:45 -0400 Subject: Lambda: the Ultimate Design Flaw In-Reply-To: <42556347.9030901@chamonix.reportlab.co.uk> References: <4253fe0c$1@nntp0.pdx.net> <3bjtvuF6d00nnU2@individual.net> <42556347.9030901@chamonix.reportlab.co.uk> Message-ID: Robin Becker wrote: > Greg Ewing wrote: > >> Scott David Daniels wrote: >> >>> Aahz wrote: >>> >>>> You just can't have your cake and eat it, too. >>> >>> >>> >>> I've always wondered about this turn of phrase. I seldom >>> eat a cake at one sitting. >> >> >> >> You need to recursively subdivide the cake until >> you have a piece small enough to fit in your input >> buffer. Then the atomicity of the cake-ingestion >> operation will become apparent. >> > Ok course according to Tarski we can cut the cake up so it increases in > volume. > The slices have to be immeasurable, but the final volume can be almost > anything. > I bet that makes cake buffering harder to plan for. > > -paradoxically yrs- > Robin Becker > Not at all - we just apply the same division techniques to the buffer space until we can map the pieces of cake one-to-one onto the buffers. stick-that-in-your-cakehole-ly y'rs - steve -- Steve Holden +1 703 861 4237 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ From pitonero at gmail.com Sat Apr 9 13:39:48 2005 From: pitonero at gmail.com (El Pitonero) Date: 9 Apr 2005 10:39:48 -0700 Subject: Puzzling OO design problem References: <1113003772.020556.69550@l41g2000cwc.googlegroups.com> <1113010854.638038.173460@g14g2000cwa.googlegroups.com> <1113018015.535852.53250@z14g2000cwz.googlegroups.com> <1113043759.765568.9920@o13g2000cwo.googlegroups.com> Message-ID: <1113068388.567089.18950@z14g2000cwz.googlegroups.com> It may be useful to separate the code into version-independent part and version-dependent part. Also, one can try to implement the higher-level logic directly in the class definition of A, B, etc., and then use the version objects only as patches for the details. That is, one can use place-holder calls. The place-holder calls do nothing if a feature is not really implemented (either in a parent class, or in an older version). class World(object): def __init__(w, version): class A(object): def ff(): pass # place holder for version-dependent code def f(self): # version-independent code return self.ff() class B(A): def gg(): pass def g(self): return self.gg() for cls in (A, B): setattr(w, cls.__name__, w.versionize(cls, version)) def versionize(w, cls, version): import inspect methods = inspect.getmembers(version, inspect.ismethod) methods = [m[1] for m in methods if m[0].split('_')[0] == cls.__name__] for m in methods: m_name = '_'.join(m.__name__.split('_')[1:]) import new im = new.instancemethod(m.im_func, None, cls) setattr(cls, m_name, im) return cls class Version1(object): def A_ff(self): return 'A.ff: version 1' def B_gg(self): return 'B.gg: version 1' class Version2(Version1): def A_ff(self): return 'A.ff: version 2' def B_ff(self): return 'B.ff: version 2' w1, w2 = World(Version1), World(Version2) a1, b1 = w1.A(), w1.B() a2, b2 = w2.A(), w2.B() print a1.f() # prints 'A.ff: version 1' print b1.f() # prints 'A.ff: version 1' print b1.g() # prints 'B.gg: version 1' print '------------' print a2.f() # prints 'A.ff: version 2' print b2.f() # prints 'B.ff: version 2' print b2.g() # prints 'B.gg: version 1' From fphsml at gmail.com Sun Apr 10 13:51:41 2005 From: fphsml at gmail.com (James) Date: 10 Apr 2005 10:51:41 -0700 Subject: Document exchange! Message-ID: <1113155501.394204.92470@o13g2000cwo.googlegroups.com> This is not so much as a Python question though I will implement it in it. I am looking to securely aggregate documents based on a metadata from multiple providers. I am getting the feeling that I am reinventing the wheel. If anyone knows similar work elsewhere, please point me to it. Security and simplicity (is it possible to use the two in the same sentence? :-) ) of the protocol is king. I have the luxury of implementing any protocol I choose on each reposity. Thanks, James From fredrik at pythonware.com Wed Apr 6 07:59:21 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 6 Apr 2005 13:59:21 +0200 Subject: regexp weirdness (bug?) References: <1112715308.737856.234580@z14g2000cwz.googlegroups.com><2584344.b1EHUGjtUV@news.perlig.de><1186100.a9ONk7P8cn@news.perlig.de> <1112781872.088784.129280@g14g2000cwa.googlegroups.com> Message-ID: Sergey Schetinin wrote: > it's line #159 here, but it did work! thanks. so it IS a bug? sure looks like one. please report it here: http://sourceforge.net/tracker/?group_id=5470&atid=105470 From grig.gheorghiu at gmail.com Mon Apr 4 19:51:36 2005 From: grig.gheorghiu at gmail.com (Grig Gheorghiu) Date: 4 Apr 2005 16:51:36 -0700 Subject: unittest vs py.test? References: <114pqf31isr8k4d@news.supernews.com> <1112372685.034751.99410@o13g2000cwo.googlegroups.com> <1I2dnUmAu5ZPSdDfRVn-rA@powergate.ca> <%Fl3e.1804$7b.990@trndny01> <_4-dnaRR8dv8dNDfRVn-tg@powergate.ca> <6I-dnbpiIZJNJNPfRVn-hA@powergate.ca> <6oQ3e.10378$db.6219@trndny07> <878y3y6ts4.fsf@pobox.com> Message-ID: <1112658696.587335.12530@z14g2000cwz.googlegroups.com> py.test intercepts the assert statements before they are optimized away. It's part of the profuse "magic" that py.test does. Grig From oren at REMOVETHIS1.hishome.net Sun Apr 17 02:06:10 2005 From: oren at REMOVETHIS1.hishome.net (Oren Tirosh) Date: 16 Apr 2005 23:06:10 -0700 Subject: pre-PEP: Suite-Based Keywords References: Message-ID: Take a look at Nick Coglan's "with" proposal: http://groups.google.co.uk/groups?selm=mailman.403.1105274631.22381.python-list%40python.org It addresses many of the same issues (e.g. easy definition of properties). It is more general, though: while your proposal only applies to keyword arguments in a function call this one can be used to name any part of a complex expression and define it in a suite. I think that a good hybrid solution would be to combine the "with" block with optional use of the ellipsis to mean "all names defined in the with block". See also the thread resulting from Andrey Tatarinov's original proposal (using the keyword "where"): http://groups.google.co.uk/groups?selm=3480qqF46jprlU1%40individual.net Oren From mwm at mired.org Mon Apr 25 09:51:17 2005 From: mwm at mired.org (Mike Meyer) Date: Mon, 25 Apr 2005 08:51:17 -0500 Subject: What's do list comprehensions do that generator expressions don't? References: <86ll77pgqz.fsf@guru.mired.org> <426CB5DC.1050301@freemail.gr> Message-ID: <86hdhvotgq.fsf@guru.mired.org> jfj writes: > I think a better question would be "What do *generator expressions* do > that list comprehensions don't?". And always use list comprehensions > unless you want the extra bit. As the OP, I can say why I didn't ask those questions. Generator expressions don't build the entire list in memory before you have to deal with it. This makes it possible to deal with expressions that are to long to fit in memory. Which means that the real rule should be always use generator expressions, unless you *know* the expression will always fit in memory. Which leads to the obvious question of why the exception. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From gsakkis at rutgers.edu Tue Apr 26 02:31:29 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 25 Apr 2005 23:31:29 -0700 Subject: Injecting code into a function References: <1114425158.092697.99030@o13g2000cwo.googlegroups.com> <426dab5c.540679656@news.oz.net> Message-ID: <1114497089.020512.309660@o13g2000cwo.googlegroups.com> > I'm not clear on what your real goal is, but if you just want a snapshot > of what locals() is just before exiting func, that could be done with > a byte-code-hacking decorator with usage looking something like > > #func defined before this > func_locals = {} > @getlocals(func, func_locals) > def probefunc(): pass > > which would make a probefunc function that would be identical to func > except that before exiting, it would do func_locals.update(locals()). > (you might want func_locals to be a list and do func_locals.append(locals()) > in case func is recursive and you are interested in the all the locals). That's all good, at least if I knew how to poke with bytecodes ;-) What's a good starting point to look at ? By the way, the original problem was yet another property packager, which I posted as recipe at the cookbook: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/410698. George From robbiefcarlton at hotmail.com Fri Apr 15 08:14:21 2005 From: robbiefcarlton at hotmail.com (robcarlton) Date: 15 Apr 2005 05:14:21 -0700 Subject: eval function not working how i want it dag namn Message-ID: <1113567261.483667.198430@z14g2000cwz.googlegroups.com> hi everybody I've written this function to make a list of all of an objects attributes and methods (not for any reason, I'm just learning) def list_members(obj) l = dir(obj) return map(lambda x : eval('obj.'+x), l) but I get an error saying that obj isn't defined. As I understand it eval has access to the current local namespace, which does contain object, so I'm not sure whats going wrong. ps Im sure there are better ways of doing the above which doesn't call the eval function, and while I'd be glad to know what it is, I'd still like to understand why my way isnt working thanks From exogen at gmail.com Thu Apr 28 06:21:32 2005 From: exogen at gmail.com (Brian Beck) Date: Thu, 28 Apr 2005 06:21:32 -0400 Subject: Which IDE is recommended? In-Reply-To: References: <426f90ac$1_2@rain.i-cable.com> Message-ID: Ville Vainio wrote: > Perhaps you are just being impatient? > > Also, make sure that Preferences/pydev/code completion has > "Autocomplete on '.'" box checked. Yeah, that option is enabled. I actually just discovered that it does work in the example you give and for other modules in the standard library. But calls to standard library modules only occur maybe twice in any of my big scripts... the problem is I've been trying code completion with third-party modules and local classes, which still doesn't work. -- Brian Beck Adventurer of the First Order From steve at holdenweb.com Tue Apr 26 06:03:06 2005 From: steve at holdenweb.com (Steve Holden) Date: Tue, 26 Apr 2005 06:03:06 -0400 Subject: Order of elements in a dict In-Reply-To: References: Message-ID: Marcio Rosa da Silva wrote: > Hi! > > In dictionaries, unlinke lists, it doesn't matter the order one inserts > the contents, elements are stored using its own rules. > > Ex: > > >>> d = {3: 4, 1: 2} > >>> d > {1: 2, 3: 4} > > So, my question is: if I use keys() and values() it will give me the > keys and values in the same order? > > In other words, it is safe to do: > > >>> dd = dict(zip(d.values(),d.keys())) > > to exchange keys and values on a dictionary? Or I can have the values > and keys in a different order and end with something like this: > > >>> dd > {2: 3 , 4: 1} > > instead of: > > >>> dd > {2: 1, 4: 3} > > For this example it works as I wanted (the second output), but can I > trust this? > > Also, if someone has a better way to exchange keys and values in a dict, > I would like to learn. :-) > > Thanks! > > Marcio Well, a footnote to the "Mapping types" page in the Library Reference says """Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary's history of insertions and deletions. If items(), keys(), values(), iteritems(), iterkeys(), and itervalues() are called with no intervening modifications to the dictionary, the lists will directly correspond. This allows the creation of (value, key) pairs using zip(): "pairs = zip(a.values(), a.keys())". The same relationship holds for the iterkeys() and itervalues() methods: "pairs = zip(a.itervalues(), a.iterkeys())" provides the same value for pairs. Another way to create the same list is "pairs = [(v, k) for (k, v) in a.iteritems()]". """ So it looks as though you will be safe, since there's a promise in the documentation. If you just want to iterate over the (key, value) pairs, however, you should normally choose items() or iteritems() to do so. Then you could use (for example): dd = dict((x[1], x[0]) for x in d.items()) I presume you are confident that each value will only occur once in the original dictionary, as otherwise the result will be smaller than the input. regards Steve -- Steve Holden +1 703 861 4237 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ From ivanlan at pauahtun.org Mon Apr 25 09:34:13 2005 From: ivanlan at pauahtun.org (Ivan Van Laningham) Date: Mon, 25 Apr 2005 07:34:13 -0600 Subject: Multiple tuples for one for statement References: <1114398216.258027.105070@g14g2000cwa.googlegroups.com> <200504242020.27440.jstroud@mbi.ucla.edu> <200504251356.07715.james@wrong.nu> Message-ID: <426CF1D5.E9F4396@pauahtun.org> Hi All-- "R. C. James Harlow" wrote: > > or just: > > for a,b,c in (tup1, tup2, tup3): > print a > print b > print c > And this works in Python version??? Metta, Ivan ---------------------------------------------- Ivan Van Laningham God N Locomotive Works http://www.andi-holmes.com/ http://www.foretec.com/python/workshops/1998-11/proceedings.html Army Signal Corps: Cu Chi, Class of '70 Author: Teach Yourself Python in 24 Hours From kay.schluehr at gmx.net Sat Apr 9 15:00:24 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 9 Apr 2005 12:00:24 -0700 Subject: Puzzling OO design problem References: <1113003772.020556.69550@l41g2000cwc.googlegroups.com> Message-ID: <1113073224.002152.306200@l41g2000cwc.googlegroups.com> Hi George, it's a nice little puzzle and it is more fun to solve it if one is not a student anymore :) Filling the gaps in the lattice is somehow necessary but it is not necessary to create all the classes. Ansatz: We can consider two matrices: one is filled with nodes ( class names ) the other is filled with arrows between the nodes representing the inheritance relationships. In symbolic notatation: | A B C | Nodes = | D 0 F | | G H I | | 0 l l | Arrows = | u 0 u*l | | u u*l u*l | Remarks: 1 ) if a node or an arrow is empty a 0 is inserted into the matrix. 2 ) u is for uppermost, l is for leftmost. A multiplication between arrows should read as a logical AND: u*l ~ upper AND left. With this interpretation the above matrizes contains the same information than the lattice: A <- B <- C ^ ^ ^ | | | D <- 0 <- F ^ ^ ^ | | | G <- H <- I Now we need an algorithm to create all the classes from the matrix information using multiple inheritance when needed: # arrows symbolized as primes. Only u and l are used in the impl. # d and r are somewhat more complicated to implement l = 2 r = 3 u = 5 d = 7 class ClassGridError(Exception):pass class ClassGrid(object): def __init__(self): self.class_names = [] # rows of the class-name matrix self.arrows = [] # rows of the arrow matrix self.classes = {} # store the resulting classes def add_names(self,names): self.class_names.append(names) def add_arrow(self,arrow): self.arrows.append(arrow) def __repr__(self): if self.classes: return self.classes.__repr__() return object.__repr__(self) def create_classes(self): for i,class_row in enumerate(self.class_names): for j,cls_name in enumerate(class_row): if cls_name == 0: continue arrow = self.arrows[i][j] if arrow == 0: self.classes[cls_name] = type(cls_name,(),{}) else: bases = [] name = 0 if arrow%u == 0: # search uppermost k = i-1 while k>=0: name = self.class_names[k][j] if name: break k-=1 if not name: raise ClassGridError,"Wrong arrow matrix" bases.append(self.classes[name]) if arrow%l == 0: # search leftmost k = j-1 while k>=0: name = self.class_names[i][k] if name: break k-=1 if not name: raise ClassGridError,"Wrong arrow matrix" bases.append(self.classes[name]) self.classes[cls_name] = type(cls_name,tuple(bases),{}) cg = ClassGrid() cg.add_names(("A","B","C")) cg.add_names(("D", 0, "F")) cg.add_names(("G","H","I")) cg.add_arrow(( 0, l, l )) cg.add_arrow(( u, 0, u*l)) cg.add_arrow(( u, u*l, u*l)) cg.create_classes() Now You can checkout Your solution: >>> cg.classes["A"].__subclasses__() [, ] >>> cg.classes["B"].__subclasses__() [, ] >>> cg.classes["C"].__subclasses__() [] >>> cg.classes["D"].__subclasses__() [, ] >>> cg.classes["F"].__subclasses__() [] >>> cg.classes["G"].__subclasses__() [] >>> cg.classes["H"].__subclasses__() [] >>> cg.classes["I"].__subclasses__() [] Ciao, Kay From qwweeeit at yahoo.it Sat Apr 16 10:48:08 2005 From: qwweeeit at yahoo.it (qwweeeit) Date: 16 Apr 2005 07:48:08 -0700 Subject: whitespace , comment stripper, and EOL converter References: <2ab23d7a.0504120857.14ef094a@posting.google.com> <2ab23d7a.0504130738.622a3605@posting.google.com> <1113410094.102181.315080@l41g2000cwc.googlegroups.com> Message-ID: <2ab23d7a.0504160648.2bcbfa9f@posting.google.com> Hi, At last I succeded in implementing a cross reference tool! (with your help and that of other gurus...). Now I can face the problem (for me...) of understanding your code (I have not grasped the classes and objects...). I give you a brief example of the xref output (taken from your code, also if the line numbers don't match, because I modified your code, not beeing interested in eof's other than Linux). and 076 if self.lasttoken<=self.spaces and self.spaces: append 046 self.lines.append(pos) append 048 self.lines.append(len(self.raw)) argv 116 if sys.argv[1]: argv 117 filein = open(sys.argv[1]).read() __author__ 010 __author__ = s_ break 045 if not pos: break __call__ 080 def __call__(self, toktype, toktext, (srow,scol), . . (erow,ecol), line): class 015 class Stripper: COMMENT 092 if toktype == tokenize.COMMENT: comments 021 def format(self, out=sys.stdout, comments=0, spaces=1,untabify=1): comments 033 self.comments = comments comments 090 if not self.comments: comments 118 Stripper(filein).format(out=sys.stdout, comments=0, . untabify=1) __credits__ 008 __credits__ = s_ __date__ 011 __date__ = s_ DEDENT 105 if toktype in [token.INDENT, token.DEDENT]: def 018 def __init__(self, raw): def 021 def format(self, out=sys.stdout, comments=0, . spaces=1,untabify=1): def 080 def __call__(self, toktype, toktext, (srow,scol), (erow,ecol), line): def 114 def Main(): ecol 080 def __call__(self, toktype, toktext, (srow,scol), . (erow,ecol), line): erow 080 def __call__(self, toktype, toktext, (srow,scol), . (erow,ecol), line): ex 059 except tokenize.TokenError, ex: except 059 except tokenize.TokenError, ex: expandtabs 036 self.raw = self.raw.expandtabs() filein 117 filein = open(sys.argv[1]).read() filein 118 Stripper(filein).format(out=sys.stdout, comments=0, untabify=1) find 044 pos = self.raw.find(self.lineend, pos) + 1 format 021 def format(self, out=sys.stdout, comments=0, spaces=1,untabify=1): format 118 Stripper(filein).format(out=sys.stdout, comments=0, untabify=1) import 005 import keyword, os, sys, traceback import 006 import StringIO import 007 import token, tokenize import 115 import sys INDENT 105 if toktype in [token.INDENT, token.DEDENT]: __init__ 018 def __init__(self, raw): isspace 071 if not line.isspace(): keyword 005 import keyword, os, sys, traceback lasttoken 030 self.lasttoken = 1 lasttoken 072 self.lasttoken=0 lasttoken 075 self.lasttoken+=1 lasttoken 076 if self.lasttoken<=self.spaces and self.spaces: ... To obtain this output, you must remove comments and empty lines, move strings in a db file, leaving as place holder s_ for normal strings and m_ for triple strings. See an example: m_ """python comment and whitespace stripper :)""" #016 m_ ''' strip comments, strip extra whitespace, convert EOL's from Python code.'''#023 m_ ''' Token handler.''' #082 s_ 'just another tool that I needed' |008 __credits__ = 'just another tool that I needed' s_ '.7' |009 __version__ = '.7' s_ 'M.E.Farmer' |010 __author__ = 'M.E.Farmer' s_ 'Jan 15 2005, Oct 24 2004' |011 __date__ = 'Jan 15 2005, Oct 24 2004' s_ ' ' |037 self.raw = self.raw.rstrip()+' ' s_ '\n' |040 self.lineend = '\n' s_ '__main__' |122 if __name__ == '__main__': I think that this tool is very useful. Bye From rkern at ucsd.edu Thu Apr 14 04:15:03 2005 From: rkern at ucsd.edu (Robert Kern) Date: Thu, 14 Apr 2005 01:15:03 -0700 Subject: Python license (2.3) In-Reply-To: References: Message-ID: Antoon Pardon wrote: > Op 2005-04-13, Robert Kern schreef : > >>Antoon Pardon wrote: >>>Well if it comes so far I have to consult a lawyer I'd rather not publish >>>it in the first place. >> >>Then take the (free) advice that you asked for. > > I'll do that and I appreciate your time in giving it. Gladly given, and I apologize if I sound a bit snippy. >>And please do read Rosen's book. > > I started already. > >>>The only reason I'm concerned is that this is to be part of a tutorial >>>and I prefer not to burden those who read the tutoral with any kind of >>>license. As far as I'm concerned people reading the tutorial can use >>>any code provided with it in any way they see fit. >> >>You can't *quite* go that far if you are deriving code from Python, but >>it's about as close as you can get. You still have those light >>restrictions about attribution and notification of changes. > > I'm not sure I follow. As far as I understand, I can license the result > however I see fit, as long as I go by the conditions for using the > original code. So it seems I can use a license so that the readers > of the tutorial don't have to be concerned in how they use the code. You can't take away the requirement to keep the PSF's copyright notice on their bits of code. You can give permission for users to do what they like with your parts of the code. However, the requirements of the PSF license are about as trivial as you get outside of the public domain. >>>I see this as my contribution to the communities who has provided me >>>with all kinds of things that are usefull to me. I'm willing to put >>>time into this, but if I have to spend money because it is impossible >>>otherwise to find out how to contribute legally, that is a hurdle >>>I'm reluctant to take. >> >>You could take a look at what other people are doing. Most of us here >>are writing and releasing software derived from Python, legally so and >>without complication. > > I would do that if I were just writing code I thought others could > find usefull. I then would feel no problem "burdening" those users > with the same kind of license I found in the product I took some > code from. But I also think that readers of documentation should > be free to use any code included in any way they see fit. If they have issues with distributing code derived from Python, why are they reading a Python tutorial? -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From sidharth.kuruvila at gmail.com Fri Apr 1 15:36:45 2005 From: sidharth.kuruvila at gmail.com (Sidharth) Date: 1 Apr 2005 12:36:45 -0800 Subject: how to close a gzip.GzipFile? In-Reply-To: References: <200504011154.18640.jguerin@cso.atmel.com> Message-ID: <1112387805.759423.54120@o13g2000cwo.googlegroups.com> GzipFile has a parameter 'fileobj' which you could use. GzipFile( [filename[, mode[, compresslevel[, fileobj]]]]) For iteratng over the file how about : line = oldfileobj.readline() while line !="": oldmd5.update(line) line = oldfileobj.readline() From robin at reportlab.com Mon Apr 25 12:08:18 2005 From: robin at reportlab.com (Robin Becker) Date: Mon, 25 Apr 2005 17:08:18 +0100 Subject: Python, Perl & PDF files In-Reply-To: References: Message-ID: <426D15F2.7080201@chamonix.reportlab.co.uk> Dennis Lee Bieber wrote: ....... > > > The most commonly known phrasing would likely be "God only helps > those who help themselves". > Of course for politicians and others with troughed snouts it should read "God punish those that help themselves", never seems to work out in practice though :( -guzzling-ly yrs- Robin Becker From prasad413in at gmail.com Mon Apr 18 04:00:25 2005 From: prasad413in at gmail.com (hue) Date: 18 Apr 2005 01:00:25 -0700 Subject: Parse command line options Message-ID: <1113811225.458022.195270@g14g2000cwa.googlegroups.com> I am trying to parse command line options using getopt module. I have written the following Code import string import getopt def usage(): print '''haarp_make.py -- uses getopt to recognize options Options: -n -- No -t -- Time -h -- help -i -- image_file -o -- Output:filename''' sys.exit(1) def main(): try: opts,args = getopt.getopt(sys.argv[1:], 'n:t:h:i:o:', ["Number=","time=","help=","image_file=","Output Filename="]) except getopt.GetoptError: print 'Unrecognized argument or option' usage() sys.exit(0) I have gone through getopt module from the help in python Library, but i couldnot proceed from here. My Task is python MyScriptName.py n t h i o How to parse those arguments, i is an Image File. Please try to give some comments. Hoping for a reply. From jepler at unpythonic.net Wed Apr 27 09:34:41 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 27 Apr 2005 08:34:41 -0500 Subject: python equivalent of php implode In-Reply-To: <8664y8lyb2.fsf@guru.mired.org> References: <8664y8lyb2.fsf@guru.mired.org> Message-ID: <20050427133438.GA24236@unpythonic.net> On Tue, Apr 26, 2005 at 09:59:29PM -0500, Mike Meyer wrote: > Jeff Epler writes: > > > items = query_param.items() > > keys = [item[0] for item in items] > > values = [item[1] for item in items] > > Is there some reason not to do: > > keys = query_params.keys() > values = query_params.values() > > That would seem to be a lot more obvious as to what was going on. I was afraid that .keys() and .values() might not "match up" (so that the i'th key maps to the i'th value in query_param). Now that I've glanced at the documentation, I see that this *is* guaranteed[1], and I should have written the code you proposed. Jeff [1] http://docs.python.org/lib/typesmapping.html note 3 -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From richardjones at optushome.com.au Fri Apr 1 00:42:14 2005 From: richardjones at optushome.com.au (richard) Date: Fri, 01 Apr 2005 15:42:14 +1000 Subject: 48-hour game programming competition only 14 days away Message-ID: <424cdf36$0$5397$afc38c87@news.optusnet.com.au> The 48-Hour Game Programming Competition is a "mostly from scratch", timed, solo coding challenge where all willing game developers spend their allowed time making the best game they can under a common theme. http://www.mechanicalcat.net/tech/ld48/ There have been numerous entries in the past using Python and PyGame or PyOpenGL. Personally, I'll be using it again. Come along, it's a hella lot of fun :) Richard From steve at holdenweb.com Fri Apr 1 01:59:23 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 01 Apr 2005 01:59:23 -0500 Subject: Stylistic question about inheritance In-Reply-To: References: <424C5B09.9090006@v.loewis.de> Message-ID: Andrew Koenig wrote: > ""Martin v. L?wis"" wrote in message > news:424C5B09.9090006 at v.loewis.de... > > >>You would normally try to avoid type queries, and rely on virtual >>methods instead, if possible. > > > Of course. > > >>It seems likely for the application >>that code can be shared across different subclasses, for example, >>you might be able to define >> >>def Expr: >> def __str__(self): >> return '%s(%s)' % (self.__class__.__name__, >> ", ".join(map(str, self.operands())) >> >>requiring you only to implement .operands() in the subclasses. > > > Indeed. > > >>If you can anticipate such common code, it is easier to add >>a base class right away. If you cannot think of a specific >>use case, there is little point in having a common base class. > > > So, for example, you don't think it's worth including the base class as a > way of indicating future intent? > > The obvious XP response to the question is "You aren't going to need it". If you already have the intent then basically you appear to be saying "I *am* going to need it". Since you say that almost as an integral feature of the specification I'm not sure I understand why you asked the question in the first place - unless it's really an anthropological inquiry. regards Steve -- Steve Holden +1 703 861 4237 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ From mrmaple at gmail.com Wed Apr 20 13:58:18 2005 From: mrmaple at gmail.com (James Carroll) Date: Wed, 20 Apr 2005 13:58:18 -0400 Subject: Why Python does *SLICING* the way it does?? In-Reply-To: <1113976729.450677.261130@o13g2000cwo.googlegroups.com> References: <1113976729.450677.261130@o13g2000cwo.googlegroups.com> Message-ID: If you have five elements, numbered 0,1,2,3,4 and you ask for the elements starting with the first one, and so on for the length you would have [0:length]. So [0:5] gives you elemets 0,1,2,3,4. Think of the weirdess if you had to ask for [0:length-1] to get length elements... One based 1... n are what I call _counting numbers_ Zero based 0... n-1 are the _indexes_ (offsets) into the collection. The first element is at offset 0. It is a little weired that slicing does [index: count] instead of [index:index] or [count:count] I agree, but python really does just flow wonderfully once you see how clean code is that's written [index: count]. In C++ the STL also has the idea that there's an 'end()' iterator that is really one element past the end of your container. It makes things flow really well there too. All code interates up to but not including the last element you specify. always. -Jim On 19 Apr 2005 22:58:49 -0700, seberino at spawar.navy.mil wrote: > Many people I know ask why Python does slicing the way it does..... > > Can anyone /please/ give me a good defense/justification??? > > I'm referring to why mystring[:4] gives me > elements 0, 1, 2 and 3 but *NOT* mystring[4] (5th element). > > Many people don't like idea that 5th element is not invited. > > (BTW, yes I'm aware of the explanation where slicing > is shown to involve slices _between_ elements. This > doesn't explain why this is *best* way to do it.) > > Chris > > -- > http://mail.python.org/mailman/listinfo/python-list > > From gdamjan at gmail.com Mon Apr 11 18:57:05 2005 From: gdamjan at gmail.com (Damjan) Date: Tue, 12 Apr 2005 00:57:05 +0200 Subject: non-ascii charater image gereration with PIL References: Message-ID: <425b010e_2@x-privat.org> > PIL has 'text(position, string, options)' method in its ImageDraw module. > Does this work with unicode or other 2byte encoded string? > It seems not working on my python2.3.5 with PIL 1.1.5. Yes, just tried and it works (python-2.4/PIL 1.1.5), but you also need a font that supports your characters, see this script: text = unicode('some cyrillic text: ??????', 'utf-8') from PIL import ImageFont, ImageDraw, Image image = Image.new('RGB',(400,300)) draw = ImageDraw.Draw(image) font = ImageFont.truetype(".fonts/dejavu-ttf/DejaVuSans.ttf", 12) draw.text((10, 10), text, font=font) image.save('wow.jpg') -- damjan From mauriceling at acm.org Sun Apr 17 03:42:30 2005 From: mauriceling at acm.org (Maurice LING) Date: Sun, 17 Apr 2005 17:42:30 +1000 Subject: new to mac OS10 References: <1113571800.485209.169320@z14g2000cwz.googlegroups.com> <4261C311.8070502@acm.org> Message-ID: Robert Kern wrote: >> 3. Apple-installed Python's command line tools are symlinked from >> /usr/bin to /System/Library/Frameworks/Python.framework but the OSX >> installer for Python 2.4.1 places the commandline tools in >> /usr/local/bin and symlinked to /Library/Frameworks/Python.framework. >> So it seems to me that Python 2.4.1 (installed using OSX installer for >> Python 2.4.1) is not a precise replacement of Apple-installed Python... > > > Bingo. It's not intended to be one. > Hi Robert, Once I've tried to install Python 2.4.1 through the installer Bob Ippolito built. I've already for Fink installed Python 2.3.5 in my system. So, /usr/bin/python -> /sw/bin/python and the newly installed Python 2.4.1 created /usr/local/bin/python -> /Library/Frameworks/Python.framework/python Does /usr/bin/python takes precedence over /usr/local/bin/python? Somehow it rings an alarm in me... Cheers Maurice From fredrik at pythonware.com Fri Apr 22 13:38:03 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 22 Apr 2005 19:38:03 +0200 Subject: XML parsing per record References: Message-ID: Willem Ligtenberg wrote: > So I get a list database names and two! lists of ID's > And those two are in no way related. Is there an easy way to create a > dictionary like this DBname --> ID why not just check for both alternatives? text = elem.findtext("Object-id_str") if text is None: text = elem.findtext("Object-id_id") (or you can loop over the child elements and map elem.tag through a dictionary...) > If not, I still might need to revert to SAX... :( you still have to check for both alternatives... (if you find a parsing problem that you cannot solve with a light-weight DOM, SAX won't help you...) From axel at white-eagle.invalid.uk Tue Apr 26 03:54:32 2005 From: axel at white-eagle.invalid.uk (Axel) Date: Tue, 26 Apr 2005 02:54:32 -0500 Subject: Python or PHP? References: <1114254894.512656.297040@l41g2000cwc.googlegroups.com> <86y8b8rgg5.fsf@guru.mired.org> <86d5skr2l3.fsf@guru.mired.org> <86y8b7pydc.fsf@guru.mired.org> <86u0lvph0n.fsf@guru.mired.org> <86mzrmo5j8.fsf@guru.mired.org> Message-ID: Jeremy Bowers wrote: > Nobody ever changed their mind as a result of a 20-thread endless > reply-fest. As usual, the posters aren't about to admit anything, and none > of the bystanders are reading any more. Well I am reading... always interested to learn. Axel From whocaresrmb at yahoo.com Sat Apr 23 02:29:23 2005 From: whocaresrmb at yahoo.com (Johnny Gentile) Date: 22 Apr 2005 23:29:23 -0700 Subject: Spamming nut won't go away In-Reply-To: References: <1114186957.814776.238490@z14g2000cwz.googlegroups.com> Message-ID: <1114237763.730599.164900@l41g2000cwc.googlegroups.com> There is no God. OK, Ron, discuss. Ron wrote: > Reports to groups-abuse at google.com, abuse at aol.net, domains at aol.net, > abuse at yahoo.com, abuse at yahoo-inc.com > > And do not feed the troll! From steve at holdenweb.com Mon Apr 25 06:23:29 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 25 Apr 2005 06:23:29 -0400 Subject: Changing a line in a text file In-Reply-To: <1114423528.568195.12750@l41g2000cwc.googlegroups.com> References: <1114421951.029066.190120@g14g2000cwa.googlegroups.com> <1114423528.568195.12750@l41g2000cwc.googlegroups.com> Message-ID: kah wrote: > Hi, > > the example provided by Vishnu is quite close to what I want but it > still required me to write all the data back to the file. > > Is there any way where I can just write a particular line? > If you are asking whether you can update a file in place, the answer is "yes" - look up "lseek" in the Python documentation (module os, under "File Descriptor Operations". However, you asked about replacing one line with another of a different length: since this will mean changing the offsets of all subsequent bytes you have no way to do this other than writing out the whole content of the file following the modification. You would also have to ensure that you truncated the file to the correct length. In general, although they don't make it obvious that they are doing so most programs that "change" files (text editors and the like) are really writing new copies. regards Steve -- Steve Holden +1 703 861 4237 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ From kay.schluehr at gmx.net Sun Apr 17 02:43:03 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 16 Apr 2005 23:43:03 -0700 Subject: pre-PEP: Suite-Based Keywords - syntax proposal In-Reply-To: References: Message-ID: <1113720183.913168.184770@f14g2000cwb.googlegroups.com> Robert Brewer wrote: > Bengt Richter wrote: > > The '::' unary suite operator should return an ordered dict > > subtype representing the bindings > > Why ordered? Because You can't otherwise guarantee to feed optional argument parameters in a correct way. Example: x = property(*seq) where: seq = (item[1] for item in :: def get_x(): return self.__x def set_x(value): self.__x = value del_x = None doc = "I'm the 'x' property." ) This statement would not work if the result of '::' ( considered as an "ordered dict" ) would return simply a dict because the order of the input parameters matters. Ciao, Kay From postmaster at castleamber.com Sat Apr 23 22:51:59 2005 From: postmaster at castleamber.com (John Bokma) Date: 24 Apr 2005 02:51:59 GMT Subject: Python or PHP? References: Message-ID: Leif K-Brooks wrote: > Peter Ammon wrote: >> I'm bewildered why you haven't mentioned magic quotes. A one line >> change to the configuration file can render your PHP site almost >> entirely immune to SQL injection attacks. > > PHP's magic quotes is one of the most poorly-designed features I can > think of. Instead of magically escaping only strings which will actually > be passed to a database (like Python's DB-API does), it escapes every > string that comes from the user, meaning that strings which will be sent > back to the user have to be manually unescaped. Yup, I recently downloaded a script that required grc_magic_quotes (IIRC the name) to be *off* I looked it up, and one has to do such a thing in the ini (!!!) file. > Even worse, since it can be turned on and off, code which is designed > for a magic_quotes=on environment will become seriously vulnerable when > moved to an environment with magic_quotes on. Security-related features > should never be toggleable! Amen. And quite some people who nowadays install PHP scripts are the same ones who reply to questions like "My messenger program doesn't work" with "Did you disable the firewall?". -- John MexIT: http://johnbokma.com/mexit/ personal page: http://johnbokma.com/ Experienced programmer available: http://castleamber.com/ Happy Customers: http://castleamber.com/testimonials.html From jbo at cannedham.ee.ed.ac.uk Mon Apr 4 06:34:02 2005 From: jbo at cannedham.ee.ed.ac.uk (Jim) Date: Mon, 04 Apr 2005 11:34:02 +0100 Subject: Raise Error in a Module and Try/Except in a different Module In-Reply-To: References: <7f285d16.0504040211.1e1b8783@posting.google.com> Message-ID: > > You're not *calling* FUNC1 here, you're just assigning a reference to > it to the name 'a'. Try FUNC1() instead. > Oh yeah. From RonGrossi382791 at yahoo.com Fri Apr 22 12:22:37 2005 From: RonGrossi382791 at yahoo.com (RonGrossi382791 at yahoo.com) Date: 22 Apr 2005 09:22:37 -0700 Subject: =?iso-8859-1?q?Good_morning_or_good_evening_depending_upon_your_?= =?iso-8859-1?q?location=2E_I_want_to_ask_you_the_most_important_qu?= =?iso-8859-1?q?estion_of_your_life=2E_Your_joy_or_sorrow_for_all_e?= =?iso-8859-1?q?ternity_depends_upon_your_answer=2E_The_question_is?= =?iso-8859-1?q?=3A_Are_you_saved=3F_It_is_not_a_question_of_how_go?= =?iso-8859-1?q?od_you_are=2C_nor_if_you_are_a_church_member=2C_but?= =?iso-8859-1?q?_are_you_saved=3F_Are_you_sure_you_will_go_to_Heave?= =?iso-8859-1?q?n_when_you_die=3F_GOOGLE=B7NEWSGROUP=B7POST=B7147?= Message-ID: <1114186957.814776.238490@z14g2000cwz.googlegroups.com> The reason some people don't know for sure if they are going to Heaven when they die is because they just don't know. The good news is that you can know for sure that you are going to Heaven which is described in the Holy Bible as a beautiful place with no death, sorrow, sickness or pain. God tells us in the Holy Bible how simple it is to be saved so that we can live forever with Him in Heaven. "For if you confess with your mouth Jesus is Lord and believe in your heart that God raised Him from the dead, you WILL BE SAVED." (Romans 10:9) Over 2000 years ago God came from Heaven to earth in the person of Jesus Christ to shed His blood and die on a cross to pay our sin debt in full. Jesus Christ was born in Israel supernaturally to a virgin Jewish woman named Mary and lived a sinless life for thirty-three years. At the age of thirty-three Jesus was scourged and had a crown of thorns pressed onto His head then Jesus was crucified. Three days after Jesus died on a cross and was placed in a grave Jesus rose from the dead as Jesus said would happen before Jesus died. If someone tells you that they are going to die and in three days come back to life again and it happens then this person must be the real deal. Jesus Christ is the only person that ever lived a perfect sinless life. This is why Jesus is able to cover our sins(misdeeds) with His own blood because Jesus is sinless. The Holy Bible says, "In Him(Jesus) we have redemption through His blood, the forgiveness of sins..." (Ephesians 1:7) If you would like God to forgive you of your past, present and future sins just ask Jesus Christ to be your Lord and Saviour. It doesn't matter how old you are or how many bad things that you have done in your life including lying and stealing all the way up to murder. Just pray the prayer below with your mouth and mean it from your heart and God will hear you and save you. Dear Jesus Christ, I want to be saved so that I can have a home in Heaven with You when I die. I agree with You that I am a sinner. I believe that You love me and want to save me. I believe that You bled and died on the cross to pay the penalty for my sins and that You rose from the dead. Please forgive my sins and come into my heart and be my Lord and Saviour. Thanks Lord Jesus Christ for forgiving me and saving me through Your merciful grace. Amen. Welcome to the family of God if you just allowed God to save you. Now you are a real Christian and you can know for sure that you will live in Heaven forever when this life comes to an end. As a child of God we are to avoid sin(wrongdoing), but if you do sin the Holy Bible says, "My dear children, I write this to you so that you will not sin. But if anybody does sin, we have one who speaks to the Father in our defense Jesus Christ, the Righteous One." Those of you that have not yet decided to place your trust in the Lord Jesus Christ may never get another chance to do so because you do not know when you will die. Jesus said, "I am the way, the truth and the life: no one can come to the Father(God)(in Heaven), but by me." (John 14:6) This means that if you die without trusting in Jesus Christ as your Lord and Saviour you will be forever separated from the love of God in a place called Hell. The Holy Bible descibes Hell as a place of eternal torment, suffering, pain and agony for all those who have rejected Jesus Christ. The good news is that you can avoid Hell by allowing Jesus Christ to save you today. Only then will you have true peace in your life knowing that no matter what happens you are on your way to Heaven. Praise the Lord! Servant of the Lord Jesus Christ Ronald L. Grossi *Show this to your family and friends so they can know that they have a choice where they will spend eternity. Thanks! ____________________________________________________ Got Questions? http://www.gotquestions.org/archive.html Other Languages http://www.godssimpleplan.org/gsps.html Free Movie: To Hell and Back http://www.tbn.org/index.php/8/1.html Animation http://www.gieson.com/Library/projects/animations/walk/index.html The Passion Of The Christ http://www.thepassionofthechrist.com Beware Of Cults http://www.carm.org/cults/cultlist.htm About Hell http://www.equip.org/free/DH198.htm Is Jesus God? http://www.powertochange.com/questions/qna2.html Free Online Bible http://www.biblegateway.com ____________________________________________________ From __peter__ at web.de Tue Apr 19 05:03:08 2005 From: __peter__ at web.de (Peter Otten) Date: Tue, 19 Apr 2005 11:03:08 +0200 Subject: Question about python 2.4 documentation References: <4264b584$0$786$626a14ce@news.free.fr> Message-ID: Fouff wrote: > I have a small question concerning the functions open(...) and file(...) > with python 2.4 >> The intent is for open() to continue to be preferred for use as a factory >> function which returns a new file object. versus >> The previous spelling, open(), is retained for compatibility, and is an >> alias for file(). > what is the favorite function you recommend me to use ? The former has BDFL blessing. Let Guido speak: http://mail.python.org/pipermail/python-dev/2004-July/045921.html Peter From rkoida at yahoo.com Wed Apr 20 02:36:20 2005 From: rkoida at yahoo.com (rkoida at yahoo.com) Date: 19 Apr 2005 23:36:20 -0700 Subject: Refactoring in Python. In-Reply-To: References: <8764yiog3y.fsf@hector.domek> Message-ID: <1113978980.824324.88240@l41g2000cwc.googlegroups.com> Hello From postmaster at castleamber.com Sat Apr 23 22:49:26 2005 From: postmaster at castleamber.com (John Bokma) Date: 24 Apr 2005 02:49:26 GMT Subject: Python or PHP? References: Message-ID: Peter Ammon wrote: > Leif K-Brooks wrote: >> John Bokma wrote: >> >>> my $sort = $cgi->param( "sort" ); >>> my $query = "SELECT * FROM table WHERE id=? ORDER BY $sort"; >> >> >> And the equivalent Python code: >> >> >> cursor.execute('SELECT * FROM table WHERE id=%%s ORDER BY %s' % sort, >> [some_id]) >> >> You're right, of course, about being *able* to write code with SQL >> injection vulnerabilities in Python. But it's not even close to being >> as easy as in PHP. > > I'm bewildered why you haven't mentioned magic quotes. A one line > change to the configuration file can render your PHP site almost > entirely immune to SQL injection attacks. There is no almost in security. -- John MexIT: http://johnbokma.com/mexit/ personal page: http://johnbokma.com/ Experienced programmer available: http://castleamber.com/ Happy Customers: http://castleamber.com/testimonials.html From tiissa at nonfree.fr Wed Apr 20 16:26:28 2005 From: tiissa at nonfree.fr (tiissa) Date: Wed, 20 Apr 2005 22:26:28 +0200 Subject: pyGTK on Mouse over event ? In-Reply-To: <1114027819.338892.278590@z14g2000cwz.googlegroups.com> References: <1114022408.677746.287630@f14g2000cwb.googlegroups.com> <4266af16$0$31058$626a14ce@news.free.fr> <1114027819.338892.278590@z14g2000cwz.googlegroups.com> Message-ID: <4266baf3$0$7208$626a14ce@news.free.fr> Domenique.Tilleuil at gmail.com wrote: > if i add a motion_notify or even a butten_press event to an image > object it does absolutly nothing :s > I have tried coding a simple application in pyGTK and I remember I had trouble getting button_press event in a DrawingArea. I was using glade and despite having declared a handler to this event, I had to manually call add_events(gtk.gdk.BUTTON_PRESS_MASK) (the connect was ok but the event mask was not). Have you checked this? From raghulj at gmail.com Thu Apr 7 04:54:13 2005 From: raghulj at gmail.com (Raghul) Date: 7 Apr 2005 01:54:13 -0700 Subject: logging as root using python script In-Reply-To: <1112852658.339035.185600@g14g2000cwa.googlegroups.com> References: <1112847155.108154.180290@g14g2000cwa.googlegroups.com> <1112852658.339035.185600@g14g2000cwa.googlegroups.com> Message-ID: <1112864053.764844.210950@o13g2000cwo.googlegroups.com> But this not the right answer From exarkun at divmod.com Wed Apr 27 11:53:54 2005 From: exarkun at divmod.com (Jp Calderone) Date: Wed, 27 Apr 2005 15:53:54 GMT Subject: compile shebang into pyc file In-Reply-To: Message-ID: <20050427155354.15422.1469236266.divmod.quotient.3740@ohm> On Wed, 27 Apr 2005 10:37:11 -0400, Michael Soulier wrote: >On 26 Apr 2005 18:15:51 -0700, johnlichtenstein at gmail.com > wrote: >> Is there some reason why you want to run the .pyc file, rather than the >> .py file? If you start the script with > >a. It's more efficient, since the code doesn't need to be compiled >before it's run. >b. What if you want to ship closed-source? > I don't think either of these reasons is particularly compelling. To avoid the costs of byte compilation (which are typically pretty minimal), structure your code to have a simple, short main .py file which imports most of its code from other modules. This gives you the automatic byte compilation caching behavior Python normally uses for imports for the bulk of your code. Shipping closed source takes a lot more than just shipping .pyc files. .pyc files are trivially (or near trivially) converted back into .py files. The only parts which cannot be restored are the comments, which are discarded at compilation time. Jp From bokr at oz.net Sat Apr 30 16:50:45 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 30 Apr 2005 20:50:45 GMT Subject: Micro-PEP: str.translate(None) to mean identity translation References: <4272e00c.260731842@news.oz.net> Message-ID: <4273eeb4.330019032@news.oz.net> On Sat, 30 Apr 2005 08:44:21 GMT, "Raymond Hettinger" wrote: >[Bengt Richter] >> Just thought None as the first argument would be both handy and mnemonic, >> signifying no translation, but allowing easy expression of deleting >characters, >> e.g., >> >> s = s.translate(None, 'badcharshere') > >Log a feature request on SF and assignment to me. >I'll put this in for you. > Thanks. It has request ID # 1193128 Regards, Bengt Richter From codecraig at gmail.com Thu Apr 14 16:07:22 2005 From: codecraig at gmail.com (codecraig) Date: 14 Apr 2005 13:07:22 -0700 Subject: SimpleXMLRPCServer - turn of output Message-ID: <1113508180.313755.216940@f14g2000cwb.googlegroups.com> Hi, I have a simple script which starts a SimpleXMLRPCServer. A client connects to the server and executes one of the servers methods. When the server processes the request and returns it, the server prints some info out to the console, something like this.. localhost - - [14/Apr/2005 15:47:12] "POST /RPC2 HTTP/1.0" 200 - Any idea how I can prevent it from printing out? Thanks From fred.dixon at gmail.com Fri Apr 15 09:59:52 2005 From: fred.dixon at gmail.com (fred.dixon) Date: 15 Apr 2005 06:59:52 -0700 Subject: sort of a beginner question about globals In-Reply-To: References: <1113354531.380490.81190@z14g2000cwz.googlegroups.com> <3aOdnX8D67t5PcHfRVn-qQ@comcast.com> <1113403451.556360.116630@f14g2000cwb.googlegroups.com> <1113405724.301516.232000@f14g2000cwb.googlegroups.com> <6v-dnV7CJ7WZocDfRVn-oA@comcast.com> <1113422470.180010.172970@z14g2000cwz.googlegroups.com> <1113434483.437663.206030@f14g2000cwb.googlegroups.com> <1113481607.615479.72920@g14g2000cwa.googlegroups.com> Message-ID: <1113573592.248241.38550@z14g2000cwz.googlegroups.com> :) unit test is something on my to-learn list. seems involved and i haven't seen any straight forward tutorials yet. as yet i still consider myself a hobbyist at best. From rogerb at rogerbinns.com Sat Apr 23 23:11:21 2005 From: rogerb at rogerbinns.com (Roger Binns) Date: Sat, 23 Apr 2005 20:11:21 -0700 Subject: GUI woes References: Message-ID: "jeff elkins" wrote in message news:mailman.2361.1114307134.1799.python-list at python.org... > under debian sid, I installed (via apt-get) the various wxpython stuff > available.: > > libwxgtk2.4-python > libwxgtk2.5.3-python > python-opengl > python-pythoncard > python2.1-opengl > python2.2-opengl > python2.3-opengl > python2.3-pythoncard > pythoncard > pythoncard-doc > pythoncard-tools > wx2.5-examples > wxpython2.5.3 > wxwin2.4-examples You have a mixture of different versions of wxPython in there. > AttributeError: MyFrame instance has no attribute 'Bind' Bind was introduced in wxPython 2.5. Looks like you are running against thr 2.4 library. Roger From pitonero at gmail.com Sat Apr 2 10:22:39 2005 From: pitonero at gmail.com (El Pitonero) Date: 2 Apr 2005 07:22:39 -0800 Subject: Docorator Disected References: <4p9t419ockcg8578g6guse3a14t16orebf@4ax.com> Message-ID: <1112455359.773729.92080@l41g2000cwc.googlegroups.com> Ron_Adam wrote: > > # (0) Read defined functions into memory > > def decorator(d_arg): # (7) Get 'Goodbye' off stack > > def get_function(function): # (8) Get func object off stack > > def wrapper(f_arg): # (9) Get 'Hello' off stack > > new_arg = f_arg+'-'+d_arg > result = function(new_arg) # (10) Put new_arg on stack > # (11) Call func object > > return result # (14) Return result to wrapper > > return wrapper # (15) Return result to get_function > > return get_function # (16) Return result to caller of func > > > > @decorator('Goodbye') # (5) Put 'Goodbye' on stack > # (6) Do decorator > > def func(s): # (12) Get new_arg off stack > > return s # (13) Return s to result > > # (1) Done Reading definitions > > > print func('Hello') # (2) Put 'Hello' on stack > # (3) Put func object on stack > # (4) Do @decorator > # (17) print 'Hello-Goodbye' > > # Hello-Goodbye Is it possible that you mistakenly believe your @decorator() is being executed at the line "func('Hello')"? Please add a print statement to your code: def decorator(d_arg): def get_function(function): print 'decorator invoked' def wrapper(f_arg): new_arg = f_arg+'-'+d_arg result = function(new_arg) return result return wrapper return get_function When you run the program, you will see that the comment "decorator invoked" is printed out at the moment when you finish defining: @decorator('Goodbye') def func(s): return s That is, decorator is invoked before you run the line "func('Hello')". Decorator feature is a metaprogramming feature. Not a programming feature. By metaprogramming I mean you are taking a function/code object, and try to do something with it (e.g., wrap it around.) By the time you finish defining the function "func(s)", the decorator "get_function()" was already invoked and will never be invoked again. It's better to view functions as individual objects. And try to think who holds reference to these objects. If no one holds reference to an object, it will be garbage collected and will be gone. After you define the function "func()" and before you execute "func('Hello')", this is the situation: decorator() <--- held by the module get_function() <--- temporary object, garbage collected wrapper() <--- held by the module, under the name "func" func() <--- held by wrapper(), under the name "function" 'Goodbye' <--- string object, held by the wrapper function object, under the name d_arg Objects can be rebound to different names. In your code you have rebound the original wrapper() and func() function objects to different names. I think the confusing part is that, for function name binding, Python does not use the = operator, but instead relies on the "def" keyword. Maybe this is something to be considered for Python 3K. Anonymous function or codeblock objects are good to have, when you are doing metaprogramming. From jepler at unpythonic.net Sun Apr 3 22:59:48 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Sun, 3 Apr 2005 21:59:48 -0500 Subject: Silly question re: 'for i in sys.stdin'? In-Reply-To: References: Message-ID: <20050404025945.GB7293@unpythonic.net> The iterator for files is a little bit like this generator function: def lines(f): while 1: chunk = f.readlines(sizehint) for line in chunk: yield line Inside file.readlines, the read from the tty will block until sizehint bytes have been read or EOF is seen. If you want this kind of line-at-a-time functionality, then you could use the iter(callable, sentinel) form, and switch between it and the readlines method based on a commandline flag or whether the file satisfies 'os.isatty()': def lines(f): # untested """lines(f) If f is a terminal, then return an iterator that gives a value after each line is entered. Otherwise, return the efficient iterator for files.""" if hasattr(f, "fileno") and isatty(f.fileno()): return iter(f.readline, '') return iter(f) for line in lines(sys.stdin): doSomethingWith(line) Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From pajo at pajo.com Thu Apr 28 09:10:33 2005 From: pajo at pajo.com (Pajo) Date: Thu, 28 Apr 2005 15:10:33 +0200 Subject: Can .py be complied? In-Reply-To: <4270defb$1_1@rain.i-cable.com> References: <426ec8f7_2@rain.i-cable.com> <426f562f$1_3@rain.i-cable.com> <116v84ftiq01ucb@corp.supernews.com> <426fb233$1_2@rain.i-cable.com> <116vefldolc6p88@corp.supernews.com> <4270defb$1_1@rain.i-cable.com> Message-ID: I've just tried to build both console and windows exe and it works just fine monkey wrote: > Thx very much, I got the point now ( ; > > From sdementen at hotmail.com Tue Apr 12 04:57:31 2005 From: sdementen at hotmail.com (Sebastien de Menten) Date: 12 Apr 2005 01:57:31 -0700 Subject: args attribute of Exception objects References: <8dad5312.0504110231.68f6a21b@posting.google.com> <425ae097.133343848@news.oz.net> Message-ID: <8dad5312.0504120057.19c60370@posting.google.com> Thank you guys for those good advices (and the very interesting example of AST hacking). However, this was an example of use for Exception.args. It does not alleviate my concerns about the fact that the args attribute is poorly designed for standard Exceptions. It is as if the Exception design was only made for end users (display of a string in an interpreter) without thinking about original ways to use them :-) Seb From richardblackwood at cloudthunder.com Sun Apr 24 01:25:06 2005 From: richardblackwood at cloudthunder.com (Richard Blackwood) Date: Sun, 24 Apr 2005 01:25:06 -0400 Subject: Variables In-Reply-To: References: <426B0283.40602@cloudthunder.com> <426b0d03_3@newspeer2.tds.net> <426B1300.6090802@cloudthunder.com> <426B1A6F.2060401@cloudthunder.com> Message-ID: <426B2DB2.7080005@cloudthunder.com> Robert Kern wrote: > Richard Blackwood wrote: > >> Robert Kern wrote: > > >>> If you must, http://en.wikipedia.org/wiki/Variable >>> >> Fantastic, wikipedia deals precisely with the difference between >> variables in mathematics versus programming. However, he would never >> trust a definition from such an "unreputable" source. If you have any >> other sources I might direct him to...he maintains that the notion of >> foo being a variable where it's value is known (versus unknown) is >> illogical. > > > His problem is that he doesn't respect that technical terms can have > different meanings in different fields and contexts. No authoritative > reference can solve his problem for him. He's being overly pedantic > about a field in which *he* is clearly not an authority. You can't > convince such people, only ignore them. > Unfortunately that's not much of an option for me. We are working on a project together so I am forced to either prove his notion incorrect or I give in to his conception. *throws hands in air* From bokr at oz.net Thu Apr 28 22:52:13 2005 From: bokr at oz.net (Bengt Richter) Date: Fri, 29 Apr 2005 02:52:13 GMT Subject: Setting win32 console title from Python References: <1114684215.236448.212970@g14g2000cwa.googlegroups.com> <1114696780.653849.220080@o13g2000cwo.googlegroups.com> <1114698836.708809.32780@o13g2000cwo.googlegroups.com> <1114717354.209028.30270@z14g2000cwz.googlegroups.com> Message-ID: <42719bb9.177704245@news.oz.net> On 28 Apr 2005 12:42:34 -0700, "runes" wrote: >Hi Duncan, sorry, I was unprecise. I'm thinking of a script, called >t.py that can be used in the console like an ordinary command. Som if >I change directory from S:\scripts to d:\projects and execute the >script the title changes to "projects" etc. > >I have that functionality today with a combination of a python script >and a batch file. I just wondered if I could use python all the way. >Apparently I cannot. > >Here are the scripts: > > >------ DirInPath:\t.bat -------------------------------- >@echo off >:: reads bare directory name from file >:: created by external Python script >set DIR_FILE_NAME=DOS_IS_TERRIBLE.tmp >PyBareDir.py %DIR_FILE_NAME% > >for /F "eol=;" %%t in (%DIR_FILE_NAME%) do ( > title %%t >) > >del /Q /F DOS_IS_TERRIBLE.tmp >------------------------------------------------------------ > > >------ DirInPath:\PyBareDir.py -------------------------------- ># extracts bare directory name and writes ># it to file with name given as argument. > >from os import getcwd >from os.path import basename >import sys > >try: > saveAsName = sys.argv[1] > lastDir = basename(getcwd()) > XWwz(saveAsName, 'w+').write(lastDir + '\n;') >except: > print "PyBareDir failed:", sys.exc_info()[1] > >----------------------------------------------------------------------- > I think I'd try one of the win32 api packages and see if SetConsoleTitle would work. I.e., from some old API docs: ---- The SetConsoleTitle function sets the title bar string for the current console window. BOOL SetConsoleTitle( LPTSTR lpszTitle // address of new title ); Parameters lpszTitle Points to a null-terminated string that contains the string to appear in the title bar of the console window. Return Value If the function succeeds, the return value is TRUE. If the function fails, the return value is FALSE. To get extended error information, call GetLastError. See Also GetConsoleTitle ---- Alternatively, you could compile your own extension for title setting/getting called consoletitle.dll using the above API (assuming it works) and its companion GetConsoleTitle. Regards, Bengt Richter From http Sat Apr 2 18:08:38 2005 From: http (Paul Rubin) Date: 02 Apr 2005 15:08:38 -0800 Subject: Simple thread-safe counter? References: <7x3bu9ss22.fsf_-_@ruckus.brouhaha.com> <7xmzsg3ov6.fsf@ruckus.brouhaha.com> Message-ID: <7xmzsgbwuh.fsf@ruckus.brouhaha.com> Tim Peters writes: > If you don't want to exploit it, that's fine: there was always an > obvious approach using an explicit mutex here, and the only thing > stopping you from using it is a desire to be clever. Exploiting the > GIL in CPython is clever; using an explicit mutex is utterly > straightforward. Pick your poison. For my immediate requirement I'm going to use xrange as you suggested (thanks!). It will work exactly as I want. I'd be uncomfortable publishing such a program for long-term use by other people, but this is just for a short-term hack (famous last words). I think using an explicit mutex goes against Guido's quote mentioned yesterday, about avoiding tedious code. But relying on the GIL results in a brittle program that only works correctly in one Python implementation. As use of other implementations becomes more widespread, one of three things has to happen: 1) Python programs will become uglier and more mistake-prone (from using explicit mutexes all over the place); 2) Python programs will become unreliable (from depending on a GIL that doesn't exist any more); or 3) Python will acquire some new mechanisms for handling reliable synchronization easily and cleanly, as other languages already have. I think (3) is the preferable choice and it's reasonable to try to figure out how such mechanisms should work. From claudio.grondi at freenet.de Mon Apr 11 09:32:39 2005 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Mon, 11 Apr 2005 13:32:39 -0000 Subject: IPython - problem with using US international keyboard input scheme on W2K Message-ID: <3bv5mgF6jbil9U1@individual.net> German Windows 2000, SP 4 Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] IPython 0.6.10 -- An enhanced Interactive Python. Is it already known, that after switching the keyboard input scheme on German Windows 2000 to english USA International IPython generates \x00" instead of " when trying to input quotation marks? Idle works still OK under same conditions, so I suppose, that this is because IPyhon catches the keyboard input before the appropriate driver processes the raw keypresses - e.g. the key combination AltGr-s (i.e. Ctrl-Alt-s) which should generate a German ß i.e. ? doesn't work in IPython at all. Claudio From vincent at visualtrans.de Thu Apr 14 01:00:12 2005 From: vincent at visualtrans.de (vincent wehren) Date: Thu, 14 Apr 2005 07:00:12 +0200 Subject: String manipulation References: Message-ID: "Nicholas Graham" schrieb im Newsbeitrag news:Pine.LNX.4.44.0504132237250.11173-100000 at feynman.ece.ualberta.ca... | | I'm writing a program that requires some string manipulations. Let's say | I have a string | | s='x' | | Now, the ascii code for 'x' is 0x78. I want to be able to perform | operations on this number, and print the character corresponding to the | results of the operation. For example, the pseudo-code looks like: | | -read in string s from external file (for simplicity, we'll keep s='x') | | -determine the code for s (should be 0x78 or 120 in base 10), store it in | variable c | | -add a literal to c (let's say c=c+1) | | -find out which character corresponds to the new code c=0x79 | | -store the character in a new string s2 | | At the end of this, I want s2='y' | | Any suggestions? Take a look at the built-in functions ord() and chr() -- Chapter 2.1 of the manual. >> s = 'x' >> c = ord(s) >> c 120 >> c+=1 >> s2 = chr(c) >> s2 'y' -- Vincent Wehren | | NG | From roman.yakovenko at gmail.com Thu Apr 14 00:30:27 2005 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Thu, 14 Apr 2005 06:30:27 +0200 Subject: Freezing python application In-Reply-To: <7465b61705041321255cebadc4@mail.gmail.com> References: <425cefae.268278123@news.oz.net> <7465b61705041321255cebadc4@mail.gmail.com> Message-ID: <7465b61705041321302535b26c@mail.gmail.com> Sorry for previous post - hit the wrong button Hi. I would like to freeze python application on linux. There are a few tools that make the job to be done: freeze ( comes with python ) cx_Freeze Gordon McMillan's installer I have one problem with all of them: they require python to be installed on target machine. May be I missed something or did not understand right the docs? Also if I am right could you point me to "freeze" tool that doesn't require python installed on customer computer? For windows I have py2exe. What should I use for linux to get same affect? Thanks Roman From dthierbach at usenet.arcornews.de Sat Apr 9 04:21:28 2005 From: dthierbach at usenet.arcornews.de (Dirk Thierbach) Date: Sat, 9 Apr 2005 10:21:28 +0200 Subject: Puzzling OO design problem References: <1113003772.020556.69550@l41g2000cwc.googlegroups.com> Message-ID: <20050409082128.A3E.0.NOFFLE@dthierbach.news.arcor.de> George Sakkis wrote: > 1. There is a (single inheritance) hierarchy of domain classes, say > A<-B<-..<-Z (arrows point to the parent in the inheritance tree). > 2. This hierarchy evolved over time to different versions for each > class. So for example, version's 1 hierarchy would be A_v1 <-B_v1 > <-..<-Z_v1. > 3. At runtime, only one version is selected by a factory function. > Up to this point, the inheritance graph would be the following: > > A <- A_V1 ... <- A_Vn > ^ ^ ^ > | | | > B <- B_V1 ... <- B_Vn > . . . > . . . > . . . > ^ ^ ^ > | | | > Z <- Z_V1 ... <- Z_Vn Interesting problem. > This could be implemented either with multiple inheritance (e.g. > B_V1(B,A_V1)) To help myself thinking about that, let's make a somewhat complicated example, somewhere in the middle of the graph, with the possibility of introducing a hole at B3. I also shorten A_Vn to An etc. Consider the subgraph (with nonstandard annotations of method definition after the bar (to save space) as explained below): A2 | f <- A3 | f ^ ^ | | B2 <- B3 ^ ^ | | C2 | g <- C3 | h Assume a method g that is present in C2 but not changed in C3. Now g calls a method f, which is inherited unchanged in C2 from A2 (and not changed in B2, B3 or C3, either), but changed in A3. Finally, let h call g in C3. As here the "inheritance columns" have "priority", one would expect then g to call f in A3, and not in A2, for example. So what you need is that every method, even if not originating from the "real" class, is looked up first in the column above the "real" class, then in the column left to that, and so on. Ok. Multiple inheritance can often select priority for conflicting methods. If you can specify yhat tou want "column priority" for each class, you're fine. > or using the bridge design pattern |Z| times, one per each row. When I read your description above, I also thought immediately "bridge pattern", but then I tried to write down details, and got stuck. How would you do it? > Now the problem is that there are 'holes' in this > inheritance lattice: Not all versions introduced new variations of > all types; [...] > My first thought was to create all the missing classes dynamically, > but it's somewhat obscure and it may not be that simple. Is there a > more elegant solution, either a general design pattern or some > clever python metaprogramming hack ? In the most general case, you need to access time the whole "upper left" subgraph at class creation, collect all methods defined in this subgraph with "column priority", and overwrite or add to that any methods defined in the newly defined class. I don't know enough about the intricacies of Python's class creation to make a concrete suggestion, but I'd think that would be possible with the help of __metaclass__. You would need some sort of repository for the complete inheritance. One way to do that would be to create the chain A ... Z first, letting A inherit from some special class with __metaclass__ set, and then store an array of all versions somewhere inside the class namespace. You'd also need some special syntax to create a new version of a class (say, again inheriting from some special class with __metaclass__ set). You could set the version inside the class definition, and then let the __metaclass__ routine disable the normal inheritance mechanism, and add missing methods as appropriate. This could for example look like class A(Versioning): ... class B(A): ... class C(B): def h ... ... class A2(NewVersion,A): __version__ = 2 def f(): ... class B2(NewVersion,B): __version__ = 2 class C2(NewVersion,C): __version__ = 2 def g(): ... f() ... class A3(NewVersion,A): __version__ = 3 def f(): ... class C3(NewVersion,C): __version__ = 3 def h(): ... g() ... with a hole at B3, as in the example. C3 will get g from C2 and f from A3, and hence the call chain will work correctly. Also, C3 will have no base classes (or maybe only the __metaclass__ ones), the inherited class A, B, C are just used by the class creation process to find out where to look for the inheritance matrix. Others who know more about the class creation mechanism will no doubt improve this suggestion, point out my errors, and tell you how to implement it :-) Note that you're basically completely changing the normal inheritance mechanism, and the class objects will be larger, because they'll have to copy all the necessary methods. I cannot think of any pattern that would give similar flexibility. - Dirk From tom at cs.otago.ac.nz Mon Apr 4 21:59:24 2005 From: tom at cs.otago.ac.nz (Tom Eastman) Date: Tue, 05 Apr 2005 13:59:24 +1200 Subject: Silly question re: 'for i in sys.stdin'? References: <20050404025945.GB7293@unpythonic.net> Message-ID: Jeff Epler wrote: > The iterator for files is a little bit like this generator function: > Cool thanks for that, it looks like iter(f.readline, '') is the best solution for the job. Tom From steven.bethard at gmail.com Sat Apr 23 18:13:40 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 23 Apr 2005 16:13:40 -0600 Subject: func_code vs. string problem In-Reply-To: References: <04mdnXLeedaPLvffRVn-vQ@comcast.com> Message-ID: <-OedncKowsANVfffRVn-tg@comcast.com> Filip Dreger wrote: > Uzytkownik "Steven Bethard" napisal w > wiadomosci news:04mdnXLeedaPLvffRVn-vQ at comcast.com... > >>See the documentation: >> >>http://docs.python.org/ref/dynamic-features.html >> >>"""The eval(), execfile(), and input() functions and the exec >>statement do not have access to the full environment for resolving >>names. Names may be resolved in the local and global namespaces of >>the caller. Free variables are not resolved in the nearest enclosing >>namespace, but in the global namespace.""" > > Thank you! I feel silly I have not found the piece of instruction > myself. And even worse, as I still do not understand: if exec() > resolves free bariable names in the global namespace, how come it > works well with code in a string? Or with a code in a compiled string? Well, probably the best thing to do is to check out what byte-code is generated in each case: py> s = compile('print b', 'string', 'exec') py> def f(): ... print b ... py> import dis py> dis.dis(s) 1 0 LOAD_NAME 0 (b) 3 PRINT_ITEM 4 PRINT_NEWLINE 5 LOAD_CONST 0 (None) 8 RETURN_VALUE py> dis.dis(f) 2 0 LOAD_GLOBAL 0 (b) 3 PRINT_ITEM 4 PRINT_NEWLINE 5 LOAD_CONST 0 (None) 8 RETURN_VALUE So, the code is basically identical, except that with the string, the code uses LOAD_NAME, while with the function, the code uses LOAD_GLOBAL. Note that this is because Python can tell that b is not defined in the function, and so it assumes that is must be a global lookup. Look what happens if I give f a parameter: py> def f(b): ... print b ... py> dis.dis(f) 2 0 LOAD_FAST 0 (b) 3 PRINT_ITEM 4 PRINT_NEWLINE 5 LOAD_CONST 0 (None) 8 RETURN_VALUE Now f is using LOAD_FAST, which looks at the locals. I believe the point of LOAD_GLOBAL and LOAD_FAST (instead of always using LOAD_NAME) is to increase performance in the common case, where exec is not used. Seems like the documentation is being a little conservative -- it does look like some statements will do the lookup in the locals too... If I was more confident about what goes on here, I'd probably try to file a documentation bug... > The manual says I can pass two dictionaries to exec, one for global > namespace and one for local. But, strange as it seems, I could not get > it to work. In the example I gave, changing exec f.func_code to exec > f.func_code in globals(),locals() does not help a bit. That's because, as the dis.dis output above shows, the function you've defined is only searching the global namespace. So the locals() dict you pass won't ever be looked at. [snip example using locals as globals] > > I thought about that... I don't know why, but it seems wrong. Maybe > the updating dictionaries is not very expensive, but there must be > some better way. This code has a 'workaround - fixme' written all over > it. Yeah, I agree. On the other hand, whenever I see exec, it has 'workaround - fixme' written all over it too. ;) STeVe From ajw140NO at SPAMyork.ac.uk Tue Apr 19 07:47:23 2005 From: ajw140NO at SPAMyork.ac.uk (Andrew Wilkinson) Date: Tue, 19 Apr 2005 12:47:23 +0100 Subject: Wrapping C++ Class Heirachy in Python References: Message-ID: Steve Juranich wrote: >> I've found the tp_base and tp_bases elements and I've set them to the >> base type object (and a tuple containing the base type object) before I >> call PyType_Ready but in Python the base class isn't recognised. Is there >> anything obvious I'm missing? > > Well, I can't really recommend without seeing what you did (did you > remember the preceding "&" for the type struct? I realised it will be a little difficult to help without seeing my source, but I was hoping someone would point me to some documentation so I wouldn't have to cut my source down to an example suitable for a usenet post. ? > Otherwise, I'd have to recommend Objects/unicodeobject.c in the Python > source as a reference for how to do this. Thanks! I was trying to think of a built in object hierarchy in Python, I didn't think of unicode strings. Cheers! Andrew Simple distributed computing with Python... PyLinda - http://www-users.cs.york.ac.uk/~aw/pylinda From rune.strand at gmail.com Thu Apr 28 10:33:56 2005 From: rune.strand at gmail.com (runes) Date: 28 Apr 2005 07:33:56 -0700 Subject: Setting win32 console title from Python References: <1114684215.236448.212970@g14g2000cwa.googlegroups.com> <1114696780.653849.220080@o13g2000cwo.googlegroups.com> Message-ID: <1114698836.708809.32780@o13g2000cwo.googlegroups.com> Hi Jay. It seems like my requirement is a light edition of your. I like having many console windows open, and to make it easier to switch between them, I like to name them. Todays solution is rather tedious - a batch file that calls a python script that isolates the directory name and stores it in temp file the batch file reads and use as argument in the title command. It works fine, but I dislike the combination and the entire concept of having to create a temporary file for such a small task. The "batch language" is probably the most terrible scripting environment ever created ;-) From bokr at oz.net Fri Apr 1 18:52:53 2005 From: bokr at oz.net (Bengt Richter) Date: Fri, 01 Apr 2005 23:52:53 GMT Subject: Case-insensitive dict, non-destructive, fast, anyone? References: <424dc33c.55623752@news.oz.net> Message-ID: <424dda51.61532058@news.oz.net> On Fri, 01 Apr 2005 23:04:42 GMT, "Raymond Hettinger" wrote: >[Bengt Richter] >> I wonder if a dict with a general override hook for hashing all keys would be >useful. >> E.g., a dict.__keyhash__ that would take key as arg and default as now >returning key.__hash__() >> but that you could override. Seems like this could potentially be more >efficient than key wrappers, >> and would also make it so you wouldn't have to chase all the affected methods >in doing an idict >> like the above (e.g., get, setdefault, update etc. etc.) > >There has also been a discussion of adding a seqdict that maintains a keys in >insertion order. Another idea was to have a defaultdict that could be >instructed to create values as necessary (either zero for counting or [] for >list building). Putting the three ideas together, perhaps we should write an >extension module with a custom dictionary type with methods/attributes >implementing those ideas. Essentially, the thought is to put all the bells and >whistles in one place. If the extension became popular, it could ultimately >wend its way into the collections module. > >A facetious naming idea would be to call it TrickyDict, a relative to DictMixin >and no relation to a former U.S. president ;-) > >t = TrickyDict() >t.keytransform(str.lower) >t['abC'] = 1 # case insensitive dictionary >assert t['Abc'] == 1 assert t.keys() == ['abC'] # actual keys unchanged (but transformed for hash and cmp) [...] > >Taken together, these six attributes/methods could cover many wished for >features for the 10% of the cases where a regular dictionary doesn't provide the >best solution. You think as much as 10% ? Regards, Bengt Richter From fuzzyman at gmail.com Mon Apr 25 04:34:25 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 25 Apr 2005 01:34:25 -0700 Subject: bytecode non-backcompatibility In-Reply-To: References: Message-ID: <1114418065.581779.52480@l41g2000cwc.googlegroups.com> Maurice LING wrote: > Hi, > > I've been using Python for about 2 years now, for my honours project and > now my postgrad project. I must say that I am loving it more and more > now. From my knowledge, Python bytecodes are not back-compatible. I must > say that my technical background isn't strong enough but is there any > good reason for not being back-compatible in bytecodes? > It *shouldn't* be a problem for pure python modules. The interpreter will recognise that the bytecode has the wrong 'magic number' and recompile. Seeing as a new major version of python will probably be installed in a new directory at the very least you will have to copy the modules across. If they have install files (or a setup.py) wouldn't it be better to use that *anyway* ? > My problem is not about pure python modules or libraries but the problem > is with 3rd party libraries with C bindings (not python pure). It means > that with every upgrade of python, I have to reinstall all my 3rd party > libraries which can be quite a bit of work... > It is a nuisance. It's more of a nuisance when third part modules with 'c' components are compiled for the new version of python (a windows specific problem). I did find that the last upgrade forced me to evaluate which extensions I actually used. The answer was 'a few less than I thought'. It became a good opportunity to spring clean my 'site-packages' folder. Best Regards, Fuzzy http://www.voidspace.org.uk/python > I do hope this problem will be sorted out some day. > > Cheers > Maurice From Domenique.Tilleuil at gmail.com Wed Apr 20 17:31:33 2005 From: Domenique.Tilleuil at gmail.com (Domenique.Tilleuil at gmail.com) Date: 20 Apr 2005 14:31:33 -0700 Subject: pyGTK on Mouse over event ? In-Reply-To: <4266c798$0$18013$636a15ce@news.free.fr> References: <1114022408.677746.287630@f14g2000cwb.googlegroups.com> <4266af16$0$31058$626a14ce@news.free.fr> <1114027819.338892.278590@z14g2000cwz.googlegroups.com> <4266baf3$0$7208$626a14ce@news.free.fr> <1114029300.082094.293410@g14g2000cwa.googlegroups.com> <4266c798$0$18013$636a15ce@news.free.fr> Message-ID: <1114032693.816847.193380@z14g2000cwz.googlegroups.com> no problem i'll just keep using the eventbox but is there an event wich is triggert when the mouse moves over the eventbox ? From notsew-reversePreceedingAndRemoveThis at canncentral.org Tue Apr 19 03:18:26 2005 From: notsew-reversePreceedingAndRemoveThis at canncentral.org (weston) Date: 19 Apr 2005 00:18:26 -0700 Subject: Trouble Installing TTX/FontTools (asks for .NET Framework Packages) In-Reply-To: <1113874162.678930.249700@g14g2000cwa.googlegroups.com> References: <1113874162.678930.249700@g14g2000cwa.googlegroups.com> Message-ID: <1113895106.385196.310650@g14g2000cwa.googlegroups.com> This problem may be addressed here: http://sourceforge.net/mailarchive/message.php?msg_id=1702374 Apparently setup.py tries to compile a c file, which of course doesn't work if there's no compiler. From pgmoscatt at optushome.com.au Mon Apr 4 02:51:15 2005 From: pgmoscatt at optushome.com.au (Pete Moscatt) Date: Mon, 04 Apr 2005 16:51:15 +1000 Subject: Makeing TopLevel Modal ? Message-ID: <4250e32a$0$5821$9a6e19ea@news.newshosting.com> Hi all, I want to make a dialog (using Tk Toplevel) but need it to be modal. Is this possible using Tk ? Show below is an example how I am calling the custom dialog: class main: def __init__(self,parent): top = self.top = Toplevel(parent) top.title("Server Settings") top.minsize(width=230,height=270) top.maxsize(width=230,height=270) Pete From fredrik at pythonware.com Thu Apr 21 11:35:02 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 21 Apr 2005 17:35:02 +0200 Subject: A smallish Tkinter question References: <1114096464.111138.262750@o13g2000cwo.googlegroups.com> Message-ID: Mediocre Person wrote: > What I want: A little window to open with a 0 in it. Every second, the > 0 should increment by 1. > What I get: A one second delay, see the window with a 1 in it, and then > nothing appears to happen. Never see the 0, never see a 2. Any quick > clues? Thanks. Nick. (Python 2.4, Win98). simple solution: def run(self): #also tried self,parent sleep(1.0) self.time = self.time + 1 self.display["text"] = str(self.time) self.update() # make sure to process all outstanding events smarter solution: def run(self): self.display["text"] = str(self.time) self.time = self.time + 1 self.after(1000, self.run) # no need to use update in this case even smarter solution: import time TICK = 1.0 # time between updates, in seconds def run(self): self.display["text"] = str(self.time) self.time = self.time + 1 delay = TICK - (time.time() % TICK) self.after(int(delay*1000), self.run) # no need to use update in this case also see: http://tkinter.unpythonic.net/wiki/TkinterDiscuss From stewart.midwinter at gmail.com Tue Apr 26 18:18:21 2005 From: stewart.midwinter at gmail.com (Stewart Midwinter) Date: Tue, 26 Apr 2005 16:18:21 -0600 Subject: App suggestion please: blog / forum software in Python Message-ID: I'm starting up a new website for a small community of local sports enthusiasts. I want to be able to create pages of information easily (i.e. a content management system), but also allow for discussion on multiple topics (i.e. a forum). Numerous people should be able to log in and create or update content, under the guidance of an admin naturally. Call me perverse, but I don't want to use phpBB for the forum. I'm not seeing anything available in Python though - except for Karrigell. is that the only option, or am I missing something? For the blog / CMS portion, I'm looking for something lightweight, i.e. not Plone or Zope. I've looked at them before and they're total overkill outside of an enterprise.Have any other suggestions? I'm using CherryPy for a web application I'm building; it occurs to me it could be used to build a discussion forum, but maybe someone's already done that? I currently use mySQL with CherryPy, but I'll add another db if necessary. cheers, -- Stewart Midwinter stewart at midwinter.ca stewart.midwinter at gmail.com Skype: midtoad From simon.brunning at gmail.com Fri Apr 15 09:19:14 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Fri, 15 Apr 2005 14:19:14 +0100 Subject: Determine ip address In-Reply-To: <1113570186.181016.249140@f14g2000cwb.googlegroups.com> References: <1113570186.181016.249140@f14g2000cwb.googlegroups.com> Message-ID: <8c7f10c605041506198edc8de@mail.gmail.com> On 15 Apr 2005 06:03:06 -0700, codecraig wrote: > hi, > how can i use python to figure the ip address of the machine which > the python script is running on? I dont mean like 127.0.0.1....but i > want the external IP address (such as ipconfig on windows displays). On Windows, this works: socket.gethostbyname(socket.gethostname()) Is that OK on real operating systems too? -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From kay.schluehr at gmx.net Fri Apr 1 00:11:06 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 31 Mar 2005 21:11:06 -0800 Subject: assignments - want a PEP In-Reply-To: <424c9401.194965575@news.oz.net> References: <1112309280.565299.314250@f14g2000cwb.googlegroups.com> <424c9401.194965575@news.oz.net> Message-ID: <1112332266.368605.255330@g14g2000cwa.googlegroups.com> Bengt Richter wrote: > you can do what you like, pretty much. I.e., > > cas = CAS() > cas.a # like your plain a, where you said "that's it" > > > cas.a, cas.b = cas.Expr(), cas.Expr() > (cas.a + cas.b)/cas.c > > Etc. Hmmm... feels like a good idea if extended to use properties as special constructors: >>> expr = CAS(Expr) >>> expr.a a >>> type(expr.a) >>> expr.a+expr.b a+b or a bit shorter if Expr becomes the "master algebra": >>> _ = CAS(Expr) >>> _.a + _.b a+b Regarding that an object oriented CAS will mix an arbitray number of algebras/namespaces that use algebraic operators homogenously referencing namespaces is a reasonable for providing clarity. A helpfull suggestion. Thanks Bengt! Regards, Kay Regards, Kay From rajarshi at presidency.com Mon Apr 18 10:20:35 2005 From: rajarshi at presidency.com (Rajarshi Guha) Date: Mon, 18 Apr 2005 10:20:35 -0400 Subject: accesing pages (or ranges of pages) via Reportlab Message-ID: Hi, I've been using pdflatex to dump ranges of pages from a PDF file via Python. However, I was looking at the Reportlab toolkit and was wondering if this operation would be possible using this toolkit as well. Admittedly, I have'nt read the documentation in detail, but I was wondering if anybody could provide any pointers to extracting pages from a PDF via Python without using pdflatex Thanks, Rajarshi From mynews44 at yahoo.com Mon Apr 25 23:46:13 2005 From: mynews44 at yahoo.com (googleboy) Date: 25 Apr 2005 20:46:13 -0700 Subject: what is the best way to determine system OS? In-Reply-To: <86y8b6o8pw.fsf@guru.mired.org> References: <1114436211.942212.203790@f14g2000cwb.googlegroups.com> <868y37osc7.fsf@guru.mired.org> <86y8b6o8pw.fsf@guru.mired.org> Message-ID: <1114487173.272526.13670@o13g2000cwo.googlegroups.com> Thanks for the edifying responses. I will try out these things and figure out if I have enough to solve my problem. What this script does is use take the output of vmstat to report idle cpu cycles (or memory stuff, etc.) over a period specified by a parameter, all the better to be a plugin for a monitoring service. Basically it parses the output of the command, runs through a whole bunch of regex to discard everything not required and then reports the info. Everything I had checked out that responded "Linux" to a uname command had identical output for vmstat until FC3. FC3 seems to use similar output to BSD. I wrote a simple if-then loop to try to determine which regex function to use, but it obivously isn't working under fc3. I could post the script if you'd like to look at it, but I was a little bit afraid of looking like a total newbie. I don't get an excuse to write code very often so it is probably quite lame. B) I will have a look at platform and see what I can come up with. Delving into libraries seems a little bit much for my current level (though lots of fun). Thanks for the responses! googleboy From enleverlesO.OmcO at OmclaveauO.com Mon Apr 11 16:37:34 2005 From: enleverlesO.OmcO at OmclaveauO.com (Do Re Mi chel La Si Do) Date: Mon, 11 Apr 2005 22:37:34 +0200 Subject: Python 2.4 killing commercial Windows Python development ? References: <425a9869$0$38039$bed64819@news.gradwell.net> <425ad806$0$3146$8fcfb975@news.wanadoo.fr> Message-ID: <425b61d6$0$19351$8fcfb975@news.wanadoo.fr> And, also, with dotNET-framework From fredrik at pythonware.com Sun Apr 24 03:22:21 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 24 Apr 2005 09:22:21 +0200 Subject: Python or PHP? References: <1114254894.512656.297040@l41g2000cwc.googlegroups.com> <3d04e3F6pjhi5U1@individual.net> Message-ID: Leif Biberg Kristensen wrote: > So. I've been writing SQL queries in Python like this, using PostgreSQL > and psycopg: > > cursor.execute("select * from foo where bar=%s" % baz) > > Is that wrong, and how should I have been supposed to know that this is > bad syntax? do you get paid to write security sensitive applications? if so, you should know why that is bad, and what to do instead. > No doc I have seen actually has told me so. well, the DB-API specification spends enough time talking about para- meters for you to figure out that maybe, just maybe, you should learn what they are. From harlinseritt at yahoo.com Fri Apr 1 06:36:38 2005 From: harlinseritt at yahoo.com (Harlin Seritt) Date: 1 Apr 2005 03:36:38 -0800 Subject: Combining digit in a list to make an integer In-Reply-To: <1112355049.196021.182720@g14g2000cwa.googlegroups.com> References: <1112354472.859466.273480@f14g2000cwb.googlegroups.com> <1112355049.196021.182720@g14g2000cwa.googlegroups.com> Message-ID: <1112355398.158653.109790@g14g2000cwa.googlegroups.com> If anyone has time, would you mind explaining the code that Dan Bishop was so kind as to point out to me: int(''.join(num1)) This worked perfectly for me, however, I'm not sure that I understand it very well. Thanks, Harlin Seritt From spencermah at comcast.net Thu Apr 28 13:17:38 2005 From: spencermah at comcast.net (Michael Spencer) Date: Thu, 28 Apr 2005 10:17:38 -0700 Subject: split question In-Reply-To: <1114707749.969274.293560@l41g2000cwc.googlegroups.com> References: <1114707749.969274.293560@l41g2000cwc.googlegroups.com> Message-ID: <3sudncKb35gWh-zfRVn-vA@comcast.com> alexk wrote: > I've a simple question. Why the following: > > words = "123#@$#$@^%[wordA] wordB#@$".split('~`!@#$%^&*()_+-=[]{},./') > > doesn't work? The length of the result vector is 1. > > I'm using ActivePython 2.4 > > Alex > Do you mean, why doesn't it split on every character in '~`!@#$%^&*()_+-=[]{},./' ? Help on built-in function split: split(...) S.split([sep [,maxsplit]]) -> list of strings Return a list of the words in the string S, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done. If sep is not specified or is None, any whitespace string is a separator. sep as a whole is the delimeter string If you want to split on any of the characters in your sep string, use a regexp: Perhaps: >>> import re >>> splitter = re.compile("[\[\]~`!@#$%^&*()_+-= ]+") #note escapes for [] >>> splitter.split("123#@$#$@^%[wordA] wordB#@$") ['', 'wordA', 'wordB', ''] >>> is closer to what you had in mind Michael From neuhauser+python-list#python.org at sigpipe.cz Thu Apr 14 11:14:58 2005 From: neuhauser+python-list#python.org at sigpipe.cz (Roman Neuhauser) Date: Thu, 14 Apr 2005 17:14:58 +0200 Subject: A little request about spam In-Reply-To: <425E86E0.1F4207AE@pauahtun.org> References: <1113416856.914310.63930@l41g2000cwc.googlegroups.com> <740c3aec05041405157cb90625@mail.gmail.com> <7ee3dcd80504140551385ce25e@mail.gmail.com> <425E7CB8.85DD2BA4@pauahtun.org> <20050414143640.GA94191@isis.sigpipe.cz> <425E86E0.1F4207AE@pauahtun.org> Message-ID: <20050414151458.GA94555@isis.sigpipe.cz> # ivanlan at pauahtun.org / 2005-04-14 09:06:08 -0600: > Roman Neuhauser wrote: > > > > # ivanlan at pauahtun.org / 2005-04-14 08:22:48 -0600: > > > The listowner could turn on the [PYTHON] headers. > > > > I hope they don't. > > > > What's your reasoning? It's 9 characters ("[PYTHON] ") of screen real estate wasted. Of course it's mail from the python-list, it has the appropriate List-Id header! > > > As it stands now, it's too easy to decide incorrectly that > > > "Subject: Inelegant" is a spamdunk. > > > > Don't base your decisions (only) on subject then. Oh, and spam sent > > through the list would have the [PYTHON] space eater too, so what > > would it buy you? > > Of course I wouldn't base decisions _only_ on whether or not [PYTHON] > appears in the subject. But I ordinarily do base decisions on the whole > subject line, and I think that's perfectly reasonable. There's nothing > else to go on without opening the message, and for HTML-based mail > there's no surer way to let spammers know they've found a live email > addres than to open it. You know that. I have no problem opening HTML emails: I (intentionally) don't have a viewer for them configured in mutt which means I see their source. And I delete them all without reading. For Content-Type: multipart/alternative emails, the text/plain part is displayed, and I mostly don't even get to notice there's a html part. If the text/plain part says something hilarious, like "This is a MIME email, get a better email client" which I've seen in a spam, I get to laugh as well. -- How many Vietnam vets does it take to screw in a light bulb? You don't know, man. You don't KNOW. Cause you weren't THERE. http://bash.org/?255991 From mauriceling at acm.org Sat Apr 9 10:29:19 2005 From: mauriceling at acm.org (Maurice LING) Date: Sun, 10 Apr 2005 00:29:19 +1000 Subject: PPC OSX vs. x86 Linux References: Message-ID: Sells, Fred wrote: > I'm no expert on internals, but I seem to recall that in the past, the > string module could be implemented in either C or Python and I think there > is a strop module that is related to all this. Could it be that on the Mac, > your string processing is using interpreted Python byte code while linux > uses c? > I have a suspicion towards Apple-installed Python, although this suspicion may be groundless. I've heard that OSX actually uses the installed Python for some of its work. Once I've deleted the Apple-installed Python totally and it does screw up some of my applications, like I can't click on a doc file and let it fire up OpenOffice to open the doc file. At the same time, I'm not sure of the Apple-installed Python is the same as if you had installed it from Fink, or has it been tweaked... If Apple-installed Python is a problem for you, you might want to install a version of Python using Fink and see how it compares up... Maurice From Shermanfnx at aeroservicios.com Wed Apr 20 04:40:10 2005 From: Shermanfnx at aeroservicios.com (Elbert Delaney) Date: Wed, 20 Apr 2005 03:40:10 -0500 Subject: long time we haven't spoken ;) References: Shermanfnx@aeroservicios.com Message-ID: <20020702003042.A707@execpc.com> Daayuum bro You'll never guess what happened to me last week. Basically found a 18 + date site that doesn't charge anything. So many couples, guys and girls are there messaging and meeting eachother. And I'm certain there is someone (or more than one) for you. Although most of them want one-nighters, there are also those who like it serious. Whatever you feel like pretty much ;-) http://www.fernirr.com/a5/ PS:no.more? http://www.fernirr.com/rmv/ From news at NOwillmcguganSPAM.com Tue Apr 12 05:30:10 2005 From: news at NOwillmcguganSPAM.com (Will McGugan) Date: Tue, 12 Apr 2005 10:30:10 +0100 Subject: World First Cancer Immune Booster In-Reply-To: <425b5ebf$1$10822$afc38c87@news.optusnet.com.au> References: <425b5ebf$1$10822$afc38c87@news.optusnet.com.au> Message-ID: <425b9523$0$2589$da0feed9@news.zen.co.uk> Health wrote: > Most people with Cancer or AIDS have no immune system left. > > We've developed a world first "natural immune booster" which helps > people fight their disease. > > Our totally natural product comes from the fresh Arctic Ocean. > > www.protecura.com Spam rarely offends me, but this is really low. Scamming money out of people with potentially fatal illnesses. I hope there's a level of hell devoted to spammers like this! Will McGugan -- http://www.willmcgugan.com "".join( [ {'*':'@','^':'.'}.get(c,None) or chr(97+(ord(c)-84)%26) for c in "jvyy*jvyyzpthtna^pbz" ] ) From flupke at nonexistingdomain.com Thu Apr 21 17:22:42 2005 From: flupke at nonexistingdomain.com (flupke) Date: Thu, 21 Apr 2005 21:22:42 GMT Subject: __del__ and reference count problem In-Reply-To: <1114116099.446355.13610@z14g2000cwz.googlegroups.com> References: <97O9e.70365$mL3.4834342@phobos.telenet-ops.be> <1114107504.036833.109360@z14g2000cwz.googlegroups.com> <4267f1e0$0$8871$636a15ce@news.free.fr> <1114116099.446355.13610@z14g2000cwz.googlegroups.com> Message-ID: ajikoe at gmail.com wrote: > look at this discussion: > http://www.dbforums.com/archive/index.php/t-1100372.html > > it looks like we have to use other way, hold the data we want to > preseve in an object, because it is possible the class is removed > before the instance cleaned, and we can not expect __del__ 100% in > handling finalizing process. > > Pujo > That forum helped. I changed this in my code and it worked def __del__(self): self.__class__.refcount -= 1 if (self.__class__.refcount == 0): print "Last table standing" else: print "There is/are still %d table(s) left." % self.__class__.refcount Output: table <__main__.Table instance at 0x009D5B98> refcount = 1 table <__main__.Table instance at 0x009D5BC0> refcount = 2 Supplier returned from a 1: not implemented Supplier returned from b 2: not implemented There are 2 tables active. There are 2 tables active. There is/are still 1 table(s) left. Last table standing Seems to work allright ! Thanks ! :) Benedict From kent37 at tds.net Sat Apr 23 12:16:23 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat, 23 Apr 2005 12:16:23 -0400 Subject: XML parsing per record In-Reply-To: References: Message-ID: <426a7086$1_1@newspeer2.tds.net> Willem Ligtenberg wrote: > Is there an easy way, to couple data together. Because I have discoverd an > irritating feature in the xml file. > Sometimes this is a database reference: > > UCSC > > > 1234 > > > > > And sometimes: > > > UCSC > > > 1234 > > > > > So I get a list database names and two! lists of ID's > And those two are in no way related. Is there an easy way to create a > dictionary like this DBname --> ID > If not, I still might need to revert to SAX... :( None of your requirements sound particularly difficult to implement. If you would post a complete example of the data you want to parse and the data you would like to end up it would be easier to help you. The sample data you posted originally does not have many of the fields you want to extract and your example of what you want to end up with is not too clear either. If you are having trouble with ElementTree I expect you will be completely lost with SAX, ElementTree is much easier to work with and cElementTree is very fast. Kent From joeyjwc at gmail.com Tue Apr 5 05:45:25 2005 From: joeyjwc at gmail.com (Joey C.) Date: 5 Apr 2005 02:45:25 -0700 Subject: Super Newbie Question In-Reply-To: <3be704F6gh9p1U1@individual.net> References: <1112657967.156094.75040@f14g2000cwb.googlegroups.com> <3be704F6gh9p1U1@individual.net> Message-ID: <1112694325.360762.53260@z14g2000cwz.googlegroups.com> To reply to many of your messages (I'm using Google right now due to lack of a better newsreader at the moment), the issue with the temporary file is that when I write something new to it, if the old contents of the file was larger, not all of it will be overwritten. So, the truncate() method will work very well. Thank you Mr. Neuhauser, Mr. Ewing, and all others. From look.at.signature at somewhere Fri Apr 8 10:31:58 2005 From: look.at.signature at somewhere (Ruud de Jong) Date: Fri, 08 Apr 2005 16:31:58 +0200 Subject: Interpreter problem In-Reply-To: References: Message-ID: <425695dc$0$44108$5fc3050@dreader2.news.tiscali.nl> Greg Lindstrom schreef: > I am using python 2.3.5 on a Linux system and have an odd problem > dealing with the 'sha-bang' line. I have a file, driver.py which starts > with > > #!/usr/bin/python > > and works fine (that is, when I type in ./driver.py at the command > prompt the file runs as expected). I have another file, myotherfile.py > which starts with the exact same line (#!/usr/bin/python) but I get > > : bad interpreter: No such file or directory > I remember encountering a similar problem once. It turned out that the python interpreter, when invoked through the #! line, will only work properly if the line ends in a Unix newline (only a LF: '\n'). When you create the line on a Windows or Mac platform the line ending will typically be different: CR/LF (\r\n) for Windows, CR (\r) for Mac. For the body of the python script this doesn't matter, but it does matter for the #! line. Not sure if this applies here, but who knows. Good luck, Ruud -- Ruud de Jong '@'.join('.'.join(s) for s in (['ruud','de','jong'],['tiscali','nl'])) From jason.massey at gmail.com Tue Apr 5 10:39:26 2005 From: jason.massey at gmail.com (jason.massey at gmail.com) Date: 5 Apr 2005 07:39:26 -0700 Subject: Python & MySQL Message-ID: <1112711966.414550.38680@z14g2000cwz.googlegroups.com> Hi all, I've got a weird problem. I was running Python 2.3 and MySQLdb and had everything running fine. Cutting to the chase: After upgrading to 2.4 (and latest modules) the MySQLdb functions in Python can connect to the database, do queries and do inserts. Or rather, it seems to do inserts. If I just run in the Python command line and manually connect to the database and do an insert and then a query on what I just inserted the info is there. However when I use SQLyog to look at the database the info isn't there. When I close down Python, restart, reconnect and query the info isn't there. Info inserted from SQLyog is persistant. Has anyone had any problems like this before? thanks, jason From kay.schluehr at gmx.net Sun Apr 10 16:37:22 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 10 Apr 2005 13:37:22 -0700 Subject: Behavioural identity - a short discussion Message-ID: <1113165441.978711.64860@z14g2000cwz.googlegroups.com> In mathematics two functions can be considered equal when they represent the same function graph. This is nothing but a set-theoretical identity. It is a nice criterion in theory bad a bad one in practice because it is impossible to calculate all values of an arbitrary function and this is true not only in practice but also in theory. So mathematicians start to distinguish certain classes of functions e.q. polynomials or power-series and prove identity theorems about objects in those classes. But what can be said about the equality of two arbitrary Python-functions f and g? First of all not very much. If we define the trivial functions def f():pass def g():pass and we ask for equality the hash values will be compared and show us that f and g are different. On the other hand if we disassemble f and g we receive a completely different picture: >>> dis.dis(f) 1 0 LOAD_CONST 0 (None) 3 RETURN_VALUE >>> dis.dis(g) 1 0 LOAD_CONST 0 (None) 3 RETURN_VALUE This remains true if we add arguments to f: def f(x):pass >>> dis.dis(f) 1 0 LOAD_CONST 0 (None) 3 RETURN_VALUE Inspecting a function using dis.dis() enables us to speak about it's "behavioural idenity". What is it good for? Answer: for using implementations as interfaces. Let's consider following classes: class NotImplemented(Exception): pass class A(object): def __init__(self): raise NotImplemented We can regard class A as a "pure abstract" class. It is impossible to create instances of A. Each subclass of A that wants to be instantiated must override __init__. This is clearly a property of A. But a client object that inspects A by checking the availability of methods and scanning argument signatures will remain insensitive to this simple fact. Thinking in Python makes live easier because we can not only check interfaces superficially but we can inspect the code and we can compare two code-objects on the behavioural level with a certain accuracy. We start with a function def not_implemented(): raise NotImplemented and we are not interested in the name or in the argument-signature that remains empty but in the implementation of not_implemented() as being prototypical for other functions. A variant of the dis.disassemble() function ( see [1]) deliveres: ['LOAD_GLOBAL', 'NotImplemented', 'RAISE_VARARGS', 'LOAD_CONST', None, 'RETURN_VALUE'] Analyzing A.__init__ will create exactly the same token stream. A client object that compares the token streams of __init__ and not_implemented holds a sufficient criterion for the abstractness of A. [1] Implementation of a stripped down variant of the dis.disassemble() function: def distrace(co): "trace a code object" code = co.co_code n = len(code) i = 0 extended_arg = 0 free = None while i < n: c = code[i] op = ord(c) yield opname[op] i = i+1 if op >= HAVE_ARGUMENT: oparg = ord(code[i]) + ord(code[i+1])*256 + extended_arg extended_arg = 0 i = i+2 if op == EXTENDED_ARG: extended_arg = oparg*65536L if op in hasconst: yield co.co_consts[oparg] elif op in hasname: yield co.co_names[oparg] elif op in hasjrel: yield (i,oparg) elif op in haslocal: yield co.co_varnames[oparg] elif op in hascompare: yield cmp_op[oparg] elif op in hasfree: if free is None: free = co.co_cellvars + co.co_freevars yield free[oparg] >>> list(distrace(A.__init__.func_code)) ['LOAD_GLOBAL', 'NotImplemented', 'RAISE_VARARGS', 'LOAD_CONST', None, 'RETURN_VALUE'] Ciao, Kay From gandalf at geochemsource.com Thu Apr 7 05:27:34 2005 From: gandalf at geochemsource.com (Laszlo Zsolt Nagy) Date: Thu, 07 Apr 2005 11:27:34 +0200 Subject: client-client connection using socket In-Reply-To: <1112859364.203394.34100@g14g2000cwa.googlegroups.com> References: <1112859364.203394.34100@g14g2000cwa.googlegroups.com> Message-ID: <4254FD06.6090107@geochemsource.com> ajikoe at gmail.com wrote: >Hello, > >I have two client computers, each has its own host name. > > Hello, I did not understand your problem. I do not see cleary what you want to do? When you say "client", do you mean a client in a client-server architecture? Maybe you want to create a peer-to-peer connection -- that is not the same. > #Server program. Could we use client hostname here ? > > Of course you can use the client's hostname. But for what purpose? > print "connected from:",addr > > You can do a reverse DNS lookup here to get the hostname of the client. > > #Client program > > Ok, it seems to me that you have one client and one server. Am I wrong? Do you want to create a connection socket between the two clients? Is it your problem? -- _________________________________________________________________ Laszlo Nagy web: http://designasign.biz IT Consultant mail: gandalf at geochemsource.com Python forever! From sjmachin at lexicon.net Fri Apr 8 09:48:27 2005 From: sjmachin at lexicon.net (John Machin) Date: Fri, 08 Apr 2005 23:48:27 +1000 Subject: Positions of regexp groups References: Message-ID: On Fri, 8 Apr 2005 13:18:27 +0000 (UTC), mlh at selje.idi.ntnu.no (Magnus Lie Hetland) wrote: >Just a quick question: Does anyone have a simple way of finding the >positions (start, end) of the groups in a regexp match? AFAICS, the re >API can only return the contents...? These documented methods of the match object aren't simple enough??? """ start( [group]) end( [group]) Return the indices of the start and end of the substring matched by group """ and there's span() which returns a tuple (start, end) ... what simpler could you ask for, Mr Occam? From codecraig at gmail.com Thu Apr 21 22:19:43 2005 From: codecraig at gmail.com (codecraig) Date: 21 Apr 2005 19:19:43 -0700 Subject: Regular Expressions - Python vs Perl In-Reply-To: References: <1114092105.964664.211430@l41g2000cwc.googlegroups.com> Message-ID: <1114136383.310295.306150@l41g2000cwc.googlegroups.com> Thanks for the input. I was just looking for some feedback about which was better and faster, if an answer exists. However, I am not choosing Perl or Python b/c of it's RegEx engine as someone mentioned. The question was just because I was curious, sorry if I misled you to think I was choosing which language to program with based on the RegEx performance. Also, I was not choosing based on performance...I just wanted to know how they compared. From rkern at ucsd.edu Mon Apr 18 22:02:36 2005 From: rkern at ucsd.edu (Robert Kern) Date: Mon, 18 Apr 2005 19:02:36 -0700 Subject: Can't compile with --enable-shared on MacOSX In-Reply-To: <6ee58e07.0504181752.c83afcf@posting.google.com> References: <6ee58e07.0504180620.4b157ebf@posting.google.com> <4263d20e$0$149$e4fe514c@news.xs4all.nl> <6ee58e07.0504181752.c83afcf@posting.google.com> Message-ID: Lothar Scholz wrote: > Maarten Sneep wrote in message news:<4263d20e$0$149$e4fe514c at news.xs4all.nl>... > > >>On Mac OS X the shared library functionality is obtained through >>frameworks. It may detect this by default, but I'm not sure about > > > Not good. I don't want frameworks. I must embedd python into my > application. > Setting up a framework and installing/maintaining it is much more work > especially when i'm already doing my own maintainance for the > Linux/Windows port. > > No ther way then stealing the dylib from the framework directory ? Umm, the framework gets embedded into the app bundle when you build it. I think you do want frameworks. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From bj_666 at gmx.net Wed Apr 6 17:11:57 2005 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 06 Apr 2005 23:11:57 +0200 Subject: Overwrite just one line? Am I a n00b or is this impossible? Both? :D References: <1112821286.411004.225400@f14g2000cwb.googlegroups.com> Message-ID: In <1112821286.411004.225400 at f14g2000cwb.googlegroups.com>, Matt at revera wrote: > I'd like to overwrite just one line of a binary file, based on a > position set by seek(). Is there no way to do this? As far as I can > tell I need to read the whole file, change the line, and write it all > back out. Not exactly easy on the memory, but I see no other solution. > > so far: > > patchme.seek(offset) > patchme.write(a2b_hex(edit)) # the data is in hex first > patchme.close > print "Patching complete" > > This writes the data at the given offset, but _everything_ before it is > filled with 0's. Are you sure that you haven't opened the file with the wrong mode? :: In [69]: f = open('test.dat', 'w') In [70]: f.seek(1000) In [71]: f.write('hello') In [72]: f.close() In [73]: f = open('test.dat') In [74]: a = f.read() In [75]: f.close() In [76]: a Out[76]: '\x00\x00\x00\x00\x00\x00\x00\00<...>hello If you want to open an existing file without overwriting it you have to use mode "w+" or "a". Ciao, Marc 'BlackJack' Rintsch From ivanlan at pauahtun.org Sat Apr 30 10:44:55 2005 From: ivanlan at pauahtun.org (Ivan Van Laningham) Date: Sat, 30 Apr 2005 08:44:55 -0600 Subject: Fwd: how to find the drive in python/cygwin? References: <1114540166.625601.50420@g14g2000cwa.googlegroups.com> <3511dc75050426113375a904e@mail.gmail.com> <426E9E0E.1020905@little-lisper.org> <3511dc7505042617524edd244a@mail.gmail.com> <426EE4B8.6910F6DD@pauahtun.org> <20050430132423.GA2824@tishler.net> <4273883C.B25B19B0@pauahtun.org> <20050430143928.GB2824@tishler.net> Message-ID: <427399E7.49228F17@pauahtun.org> Hi All-- Jason Tishler wrote: > > Ivan, > > It depends on your needs. If you are looking for a more Unix-like > Python, then the Cygwin version would probably be better. If > Windows-like, then the native Windows version would probably be better. > > The OP seem to be interested in a Cygwin Python solution -- not a > Windows one. So, I was just clarifying that the win32api module is not > supported under Cygwin Python. > Could you clarify? I always thought that the only thing really different were the default path assumptions--/ instead of \, and so on--rather than anything substantive. I try to use os.path.sep() and os.path.join(), etc. What else could bite me? ;-) Metta, Ivan ---------------------------------------------- Ivan Van Laningham God N Locomotive Works http://www.andi-holmes.com/ http://www.foretec.com/python/workshops/1998-11/proceedings.html Army Signal Corps: Cu Chi, Class of '70 Author: Teach Yourself Python in 24 Hours From sjmachin at lexicon.net Wed Apr 13 21:05:17 2005 From: sjmachin at lexicon.net (John Machin) Date: Thu, 14 Apr 2005 11:05:17 +1000 Subject: Compute pi to base 12 using Python? References: <1113390479.738210.49530@z14g2000cwz.googlegroups.com> Message-ID: <16gr511c2ckc5q4crj5o0tfloicfpne4mt@4ax.com> On Wed, 13 Apr 2005 08:28:29 -0400, Roy Smith wrote: >In article <1113390479.738210.49530 at z14g2000cwz.googlegroups.com>, > "Dan Bishop" wrote: > >> But there's no reason other than tradition why you should arrange them >> into groups of 10. > >Well, it is traditional for people to have 10 fingers :-) According to anthropology archives, there was once a tribe called "OS/360 system programmers" who would cut off their thumbs and great toes in order that they might better count in hexadecimal. From skip at pobox.com Tue Apr 19 00:04:14 2005 From: skip at pobox.com (Skip Montanaro) Date: Mon, 18 Apr 2005 23:04:14 -0500 Subject: Proposal: an unchanging URL for Python documentation In-Reply-To: References: <1113878396.500420.256230@g14g2000cwa.googlegroups.com> <16996.30734.778261.632448@montanaro.dyndns.org> Message-ID: <16996.33598.348086.859328@montanaro.dyndns.org> Skip> But appears to be firefox-specific. Michael> Works for me with both Firefox and IE6 under WinXP The wikalong.org thing is firefox-specific. You trimmed too much from my reply. Skip From hello at spamm.er Sun Apr 3 01:39:01 2005 From: hello at spamm.er (alex goldman) Date: Sat, 02 Apr 2005 22:39:01 -0800 Subject: Lambda: the Ultimate Design Flaw References: <87is3663cn.fsf@wilson.rwth-aachen.de> <3b99ncF6fd2apU1@individual.net> Message-ID: <6638350.99U9CtKfoi@yahoo.com> Artie Gold wrote: > Torsten Bronger wrote: >> Hall?chen! >> >> Daniel Silva writes: >> >> >>>Shriram Krishnamurthi has just announced the following elsewhere; it >>>might be of interest to c.l.s, c.l.f, and c.l.p: >>>http://list.cs.brown.edu/pipermail/plt-scheme/2005-April/008382.html >>> >>> >>> The Fate Of LAMBDA in PLT Scheme v300 >>> or >>> Lambda the Ultimate Design Flaw >>> >>>About 30 years ago, Scheme had FILTER and MAP courtesy of Lisp >>>hackers who missed them from their past experience. To this >>>collection, Scheme added a lexically-scoped, properly-functioning >>>LAMBDA. But, despite of the PR value of anything with Guy >>>Steele's name associated with it, we think these features should >>>be cut from PLT Scheme v300. >>> >>>[...] >> >> >> The whole text seems to be a variant of >> . >> >> Tsch?, >> Torsten. >> > Ya think? ;-) > > --ag > Wow, the original is much funnier than the "joke"! (Because it's meant seriously) "plus the lambda is slower than the list comprehension" - ROTFL! From jtr at ofb.net Wed Apr 20 21:06:49 2005 From: jtr at ofb.net (John Reese) Date: Thu, 21 Apr 2005 01:06:49 +0000 (UTC) Subject: memory profiler? Message-ID: Good afternoon, ha ha ha! Is there a memory or heap profiler for python programs? So that, for example, if a program was bloating over time I could see how many of each object there were and maybe even where the references were? From postmaster at castleamber.com Sat Apr 23 18:04:48 2005 From: postmaster at castleamber.com (John Bokma) Date: 23 Apr 2005 22:04:48 GMT Subject: Python or PHP? References: Message-ID: Leif K-Brooks wrote: > Mage wrote: >> However one of the worst cases is the sql injection attack. And sql >> injections must be handled neither by php nor by python but by the >> programmer. > > But Python's DB-API (the standard way to connect to an SQL database > from Python) makes escaping SQL strings automatic. You can do this: > > cursor.execute('UPDATE foo SET bar=%s WHERE id=%s', ["foo'bar", 123]) > > And "foo'bar" will be implicitly escaped to whatever is appropriate > for your database. How's that for Python handling SQL injection > automatically? Not. Perl and Java use similar methods where one can specify place holders, and pass on the data unescaped. But still injection is possible. Moreover, a programmer still has to check if the values are acceptable or not. AFAIK PHP is not able to do this, but goes at great length to "protect" newbie programmers at great length, and hence give them a false feeling of security. Defensive programming or a defensive programming language is wrong. -- John MexIT: http://johnbokma.com/mexit/ personal page: http://johnbokma.com/ Experienced programmer available: http://castleamber.com/ Happy Customers: http://castleamber.com/testimonials.html From mwakabayashi at gmail.com Wed Apr 20 05:42:50 2005 From: mwakabayashi at gmail.com (Mike) Date: 20 Apr 2005 02:42:50 -0700 Subject: Writing to stdout and a log file In-Reply-To: References: <1113956275.697789.324730@o13g2000cwo.googlegroups.com> Message-ID: <1113990170.781940.201270@f14g2000cwb.googlegroups.com> flushing stdout has no effect. I've got an implementation that does not subclass file. It's not as nice but it works. From news2 at mystrobl.de Sat Apr 30 15:25:46 2005 From: news2 at mystrobl.de (Wolfgang Strobl) Date: Sat, 30 Apr 2005 21:25:46 +0200 Subject: [Py Windows] User Directory Path References: Message-ID: "Zoool" : >Is there a way to know the main directory path of a user session? >I mean the "C:\Documents and Settings\username" Directory of the user logged >into a windows session. >>> from win32com.shell.shell import SHGetSpecialFolderPath >>> from win32com.shell.shellcon import CSIDL_PROFILE >>> SHGetSpecialFolderPath(0,shellcon.CSIDL_PROFILE) u'C:\\Dokumente und Einstellungen\\wolfgang' -- Wir danken f?r die Beachtung aller Sicherheitsbestimmungen From fraca7 at free.fr Mon Apr 18 14:35:12 2005 From: fraca7 at free.fr (Fraca7) Date: Mon, 18 Apr 2005 20:35:12 +0200 Subject: ANN: Python 2.3.2 for PalmOS available References: <1113608405.558884.235890@f14g2000cwb.googlegroups.com> Message-ID: On Fri, 15 Apr 2005 16:40:05 -0700, lucio.torre at gmail.com wrote: > Hello, > While talking with Facundo while in a PyAr meeting (python-argentina, > http://www.python.org/ar ) he told me that there is some interest in > this platform. You bet there is. i almost bought a Pocket PC instead of my Cli? TH55 because I thought Python would be available sooner on it... > So, ive made an initial release that has no documentation on how to use > it or compile it (it requires codewarrior). If there is any interest on > this, please let me know so we can work on getting this as a real port. I'm a beginner at PalmOS programming (actually, I've read a book about it, and that's it) but I'd be glad to help... From fredrik at pythonware.com Sat Apr 9 06:10:35 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 9 Apr 2005 12:10:35 +0200 Subject: change the date string into timestamp References: <20050409095116.4371.qmail@web8409.mail.in.yahoo.com> Message-ID: "praba kar" wrote: > In Php strtotime() will change a date > string into timestamp. I want to know which > python function will change a date string > into timestamp. you might save yourself (and everyone else) some time by looking for things in the documentation before you post... > Time stamp means datestring will converted as seconds > > example is below > > Fri, 8 Apr 2005 09:22:14 +0900 this date value > > time stamp is 1112962934 the quickest way to convert a time value to a string is to use the time.ctime() function: >>> x = 1112962934 >>> time.ctime(x) 'Fri Apr 08 14:22:14 2005' to specify a non-standard format, use a format string with the time.strftime function (or the corresponding datetime functions). an example: >>> x = 1112962934 >>> time.strftime("%Y%m%d %H%M%S", time.localtime(x)) '20050408 142214' see the "time" and "datetime" documentation for details. the timestamp format you're using is also known as the RFC(2)822 format. the "email" package contains several functions to deal with this format: >>> x = 1112962934 >>> from email.Utils import formatdate >>> formatdate(x) # default is utc 'Fri, 08 Apr 2005 12:22:14 -0000' >>> formatdate(x, localtime=1) 'Fri, 08 Apr 2005 14:22:14 +0200' >>> from email.Utils import parsedate_tz >>> parsedate_tz(formatdate(x, localtime=1)) (2005, 4, 8, 14, 22, 14, 0, 1, 0, 7200) for the full story, see: http://docs.python.org/lib/module-email.Utils.html From grante at visi.com Wed Apr 27 10:27:12 2005 From: grante at visi.com (Grant Edwards) Date: Wed, 27 Apr 2005 14:27:12 -0000 Subject: PyGTK vs. wxPython References: <1114444582.909431.245450@f14g2000cwb.googlegroups.com> <1114551965.718056.197480@g14g2000cwa.googlegroups.com> <116tf7lm0ivnl6c@corp.supernews.com> <1114600793.617469.81200@z14g2000cwz.googlegroups.com> Message-ID: <116v8a0kj2ba2e3@corp.supernews.com> On 2005-04-27, dcrespo wrote: > Aaaaaaand: which do you prefer? Neither particularly. I'm using wxPython because GTK for windows wasn't ready three years ago when I initially had to write my first Windows application. If I evaluated both of them again today, I might choose GTK, and I might not. -- Grant Edwards grante Yow! INSIDE, I have the at same personality disorder visi.com as LUCY RICARDO!! From artur_spruce at yahoo.com Mon Apr 18 16:05:57 2005 From: artur_spruce at yahoo.com (AdSR) Date: 18 Apr 2005 13:05:57 -0700 Subject: def a((b,c,d),e): Message-ID: <1113854757.229118.137260@g14g2000cwa.googlegroups.com> Fellow Pythonistas, Please check out http://spyced.blogspot.com/2005/04/how-well-do-you-know-python-part-3.html if you haven't done so yet. It appears that you can specify a function explicitly to take n-tuples as arguments. It actually works, checked this myself. If you read the reference manual at http://docs.python.org/ref/function.html really carefully, you will find that it is indeed part of the language spec, but it's a likely candidate for the least advertised Python feature. Small wonder since it looks like one of those language features that make committing atrocities an order of magnitude easier. Has anyone actually used it in real code? Cheers, AdSR From mwm at mired.org Fri Apr 22 01:43:41 2005 From: mwm at mired.org (Mike Meyer) Date: Fri, 22 Apr 2005 00:43:41 -0500 Subject: Why Python does *SLICING* the way it does?? References: <1113976729.450677.261130@o13g2000cwo.googlegroups.com> <87r7h5lk5a.fsf@wilson.rwth-aachen.de> <3cr2caF6locm6U1@individual.net> Message-ID: <868y3btlgy.fsf@guru.mired.org> Roy Smith writes: > Greg Ewing wrote: >> Also, everyone, please keep in mind that you always have >> the option of using a *dictionary*, in which case your >> indices can start wherever you want. >> >> You can't slice them, true, but you can't have everything. :-) > > Of course you can slice them, you just have to subclass dict! The > following was about 15 minutes work: > > --------------- > import types > > class slicableDict (dict): > def __getitem__ (self, index): > if type (index) == types.SliceType: > d2 = slicableDict() > for key in self.keys(): > if key >= index.start and key < index.stop: > d2[key] = self[key] > return d2 > else: > return dict.__getitem__ (self, index) > > d = slicableDict() > d['hen'] = 1 > d['ducks'] = 2 > d['geese'] = 3 > d['oysters'] = 4 > d['porpoises'] = 5 > > print d > print d['a':'m'] > --------------- I couldn't resist: py> d = slicableDict() py> d[3j] = 1 py> d[4j] = 2 py> d[5j] = 3 py> d[6j] = 4 py> d[4j:5j] Traceback (most recent call last): File "", line 1, in ? File "", line 6, in __getitem__ TypeError: cannot compare complex numbers using <, <=, >, >= Somehow, that seems like a wart. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From richardblackwood at cloudthunder.com Mon Apr 25 01:18:52 2005 From: richardblackwood at cloudthunder.com (Richard Blackwood) Date: Mon, 25 Apr 2005 01:18:52 -0400 Subject: Variables Message-ID: <426C7DBC.9080604@cloudthunder.com> I thought I'd share a piece of the discussion a friend of mine is having with a mathematician/programmer on this issue of variables: > int foo = 5; > > Is foo not a variable? Within the scope of that statement, foo can be > no other value but 5. Is foo not a constant? Are constants and > variables not mutually exclusive? But wait, what if I write: > Yes, foo, here, is a variable in the program. In this case, it is a variable that has been given a value at the same time that it is declared. It can, within the program, be changed at any time, as you illustrate with the following example: Yet what if my program is a mere two lines where foo does not change (the following code is in Python): foo = 5 print foo Does the fact that foo fails to change in the execution of the /entire/ program invalidate its status as a variable? Or is it merely the potential to change (as enforced by the respective compiler) that defines foo as a variable? In a program where my name-value-couple (foo) does not change values, am I to consider foo a constant? What are the consequences of doing otherwise? In programming (i.e. versus math) is the concept of variable and constant dependent on how a compiler processes identifiers and values in a program, and the various restrictions imposed on programmers regarding how they can manipulate those identifiers and values? For example, in C/C++ one can actually define constants, but this has a strict meaning in the sense that the compiler forces you to give constants known (?) values within the code which are then immutable. if I write the following program (pseudo-code): const X = 5 print X Y = 5 print Y The only thing that makes X any more of a constant than Y is the fact that X is treated by the compiler as a constant--- I cannot change X's value with additional code, but I can change Y's, I merely happened to chose not to. From this standpoint, the notion of variable and constant in programming is very much bound to the way the language treats each, the "can"s and "cannot"s imposed on the programmer by the respective language. In Python, the interpreter unambiguously knows nothing about constants, and as many would argue, nothing about variables either (only names and values/data/objects). > > ... > >> ... > >> Is the definition of variable actually different between math and >> programming? And regardless, is the notion of variable so very >> ambiguous, even within each respective field? > > > Variable is the same in both contexts. In a computer *program*, > however, you can have statements such as "x = x+1" which is not > appropriate in mathematics. You need there to be understanding that > within a computer a variable is treated as a place in the memory. The > statement "x=x+1" refers to the process of looking at what is in x, > adding 1 to that value, and substituting that value back into the > location in memory. ... Many would argue a more general definition of variable: variables are symbolic references to data/values which can change. One math text in my possession concurs with this programming definition by stating a variable to be a symbol replaceable by a value which can change. Another (Scott Foresman, UCSMP, 1993) writes that a variable is "a letter or other symbol that can be replaced by any numbers (or other objects)." Is the definition of a variable, particularly in math, so simple? Your definition (identical to Raphael A. Finkel's [1996]) implies that, in such languages such as Python where names (i.e. foo) are mapped to values, there are no variables. For example, when I write foo = 5 in Python, the interpreter will create an integer 5 in memory, a name foo (unless it already exists), and then bound the name foo to the value int(5). Foo is not a place in memory in this sense, but instead a reference, a pointer that can direct us to values/data stored in various memory locations. Where foo points to (and hence what value foo provides us) can change. This is not like in C where foo would be a place in memory. In C, if I write int foo = 5, a block of memory is allocated for values of foo and 5 is stored there. If I later write foo = 6, the contents of foo's memory block are overwritten with the integer 6. In this memory based sense, values in C are bound to names, whereas in Python names are bound to values. Is it only the former case which defines a variable? Many would argue yes. Foo in Python is merely a name which can be mapped to a value they would say. On the other hand, many would argue no. They would say that a variable is simply an abstract or concrete "place" to store data. In the case of Python and the foo example, they would argue that foo is a variable in an abstract sense, though indeed not so semantically. But what functional good does focus on such details provide? I agree with both camps. However, I posit that perhaps foo *is* semantically a variable in the practical sense that it exists in memory as a store of a value--- not 5 as in foo = 5, but the *reference* to the so-called anonymous object (the integer 5 in this case). The "value" of foo in Python is its reference to whatever value it is destine to return to us (as if that value was it's own). Would you agree that the concept of variables differs in very important ways between the domains of math and programming? From michael.kearns at REMOVEsaaconsultants.com Mon Apr 11 12:09:01 2005 From: michael.kearns at REMOVEsaaconsultants.com (Michael Kearns) Date: Mon, 11 Apr 2005 17:09:01 +0100 Subject: Python 2.4 killing commercial Windows Python development ? In-Reply-To: References: <425a9869$0$38039$bed64819@news.gradwell.net> Message-ID: <425aa0fb$0$38041$bed64819@news.gradwell.net> Thomas Heller wrote: > For commercial development, it should not be a problem to buy a license > for MSVC 7.1, which gives you the right to distribute msvcrt71.dll. > > And maybe that's the reason that few people care about this issue? Hi Thomas, There are a few problems with this as I see it. In theory, the 'cost' of MSVC 7.1 shouldn't be a problem for a big organisation. However, I wouldn't expect to have to go and buy it purely because I'm developing (perhaps) a shareware application using python - this isn't my case, but I wasn't looking at it from just a big organisation perspective. Also, I don't believe that just 'owning' MSVC 7.1 is enough. From cursory glances at the various redist files, I would also have to ship the EULA, and as an end-user (of python) I can't just redistribute the files - perhaps I could write a place holder application in MSVC to suggest that I was no longer an end-user, but this seems ridiculous as a workaround. There even seem to be 'exclude' clauses to redistribution concerning open-source material, but IANAL and ran from the various paragraphs. I would like to think that python would encourage as many folk as possible to use the language wherever it fits best (and perhaps even beyond) and yet this is going in the opposite direction. Would it be so difficult for a 'no legalese attached' version to be provided on windows, or at the very least, some kind of statement regarding what is and isn't allowed ? There seems nothing within the python distribution stating the redistribution rights of the dll (correct me if I'm wrong) which already seems contrary to the MS requirements. As much as I'd like to continue using it, because of the vague legal situation, I can't, and that's unfortunate. Michael. From me at nowhere.invalid Wed Apr 6 00:52:50 2005 From: me at nowhere.invalid (Mike L.G.) Date: Wed, 06 Apr 2005 04:52:50 GMT Subject: Best editor? References: <1112725379.514651.66540@l41g2000cwc.googlegroups.com> Message-ID: "ChinStrap" writes: > Opinions on what the best is? Or reading I could get to maybe sway me > to Emacs (which has the major advantage of being on everyone's system). When I first started using emacs, progress was slow, but through my persistence, I was able to harness the power of a very powerful editor. I find that with emacs I rarely touch the mouse when editing code. I just love the idea of splitting emacs into multiple windows, one with my current projects source code, another one with py-shell loaded up (which makes for a wonderful interactive python session with all of your emacs key bindings), a third window with GNUS (emacs news-reader) and lastly chatting in a 4th window with ERC, an emacs IRC chat client. Doing all these activities from within one editor just gives one an enormous sense of satisfaction. A one stop shop editing tool-box at your disposal. For me, maximum comfort working within emacs included swapping the CTRL key with the CAPS lock key. It's just so much more comfortable on the pinky finger! In windows this meant changing a registry key and on linux, altering a keymap config. file. Emacs may seem awkward at first, but the payoff was amazing for me. This is comparable to my first experiences with python. Now, one of my greatest joys is writing python code using emacs. -- Mike L.G. http://www.mahalosoft.com From news at grauer-online.de Wed Apr 13 07:21:21 2005 From: news at grauer-online.de (Uwe Grauer) Date: Wed, 13 Apr 2005 13:21:21 +0200 Subject: Programming Language for Systems Administrator In-Reply-To: <1113311618.838281.205380@l41g2000cwc.googlegroups.com> References: <1113253691.821235.9750@o13g2000cwo.googlegroups.com> <1113311618.838281.205380@l41g2000cwc.googlegroups.com> Message-ID: Kanthi Kiran Narisetti wrote: > Hi All, > > Thank You for your suggestions....I request you all to eloborate the > Uses(In Practical) for systems administrator.Some of my questions > regarding the same follows. > > 1)Can i build web applications in Python ? If so how. I am planning to > build a web application for intranet use which deals with workflow of > Internal office communication. > Look here: http://www.python.org/moin/WebProgramming > 2)Which is best opensource database to be used with Python ? > I personally think that Firebird is a very good Database: http://www.firebirdsql.org/ http://kinterbasdb.sourceforge.net/ > 3)When i write a remote execution script in python is it required that > python should be installed in remote system. > > 4)I heard about Perl/CGI and that CGI application done by python > too.....Is CGI still valid when PHP has taken over the WebApplication > Development, Dominating. > > Sorry if these questions are out of this group , but answers to these ? > will help me a lot. > > Thanks in Advance > > Kanthi. > From bob_then at yahoo.com.au Tue Apr 12 23:00:42 2005 From: bob_then at yahoo.com.au (James) Date: Wed, 13 Apr 2005 13:00:42 +1000 Subject: permission Message-ID: <425c8b44$1@dnews.tpgi.com.au> Is it possible to check if you have permission to access and or change a directory or file? From ivoras at _-_fer.hr Sun Apr 24 05:26:20 2005 From: ivoras at _-_fer.hr (Ivan Voras) Date: Sun, 24 Apr 2005 11:26:20 +0200 Subject: Unicode problems, yet again In-Reply-To: References: Message-ID: Jp Calderone wrote: > You don't have a string fetched from a database, in iso-8859-2, alas. > That is the root of the problem you're having. What you have is a > unicode string. Yes, you're right :) I actually did have iso-8859-2 data, but, as I found out late last night, the data got converted to unicode along the way. Thanks to all who replied so quickly :) >> (Does anyone else feel that python's unicode handling is, well... >> suboptimal at least?) > > Hmm. Not really. The only problem I've found with it is misguided > attempt to "do the right thing" by implicitly encoding unicode strings, > and this isn't so much of a problem once you figure things out, because > you can always do things explicitly and avoid invoking the implicit > behavior. I'm learning that, the hard way :) One thing that I always wanted to do (but probably can't be done?) is to set the default/implicit encoding to the one I'm using... I often have to deal with 8-bit encodings and rarely with unicode. Can it be done per-program? From siona at chiark.greenend.org.uk Mon Apr 25 10:38:42 2005 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 25 Apr 2005 15:38:42 +0100 (BST) Subject: what is the best way to determine system OS? References: <1114436211.942212.203790@f14g2000cwb.googlegroups.com> Message-ID: Philippe C. Martin wrote: >How about popen of 'uname -r' ? os.uname()[2] is probably a better way (ie it doesn't spawning another process) of getting this information. I don't think it will help the original poster though (depending on *what* it is about FC3 which is breaking things) since it only provides the kernel version. -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From exogen at gmail.com Wed Apr 27 11:28:04 2005 From: exogen at gmail.com (Brian Beck) Date: Wed, 27 Apr 2005 11:28:04 -0400 Subject: Which IDE is recommended? In-Reply-To: <426f90ac$1_2@rain.i-cable.com> References: <426f90ac$1_2@rain.i-cable.com> Message-ID: monkey wrote: > Read through python site for programming tool, really plenty of choices :-) > (For c++, I just can't breath with very very limited choices) > > Tried Spe, it come with wxGlade built-in very nice(is Spe still actively > develop?). But seem that Boa Constructor and PyDev(the plug-in for Eclipse) > also worth looking. Actually which one are you guys using? and why? I think > it is also valuable for those who are new to python as me. Here's been my experience: * Don't underestimate IDLE, it's surprisingly capable considering it's just a dinky little thing * PyDev isn't yet mature enough to make it practical for me * SPE has great features, but the pure-Python-ness makes it slow! Even just typing at a steady pace is slowed down due to all the name lookups. Plus, I still haven't found a way to reset the built-in Python shell, so if you run/import your module into it, you have to reload the entire app to reuse the shell. del doesn't help because the classes will still be in the registry * WingIDE is the most advanced by far, but isn't free. Its built-in Python shell also suffers from not easily being able to test _the module you're writing_ without a bunch of path switching. I remember the interface feeling slow on Windows, but on Linux everything is snappy. The quickness of the autocompletion for even seperate module members amazes me * If you're running KDE, KDevelop is very capable. The autocompletion is very generic though, it'll happily complete any word you've typed before. The auto-indentation isn't nearly as spot-on as WingIDE's * I hate PythonWin or whatever it's called. Dunno what more to say -- Brian Beck Adventurer of the First Order From rupole at hotmail.com Fri Apr 29 21:24:32 2005 From: rupole at hotmail.com (Roger Upole) Date: Fri, 29 Apr 2005 21:24:32 -0400 Subject: Killing process References: <1114823011.063614.27150@l41g2000cwc.googlegroups.com> Message-ID: <4272df20$1_2@127.0.0.1> TerminateProcess takes a process handle, not a pid. win32api.OpenProcess will give you a handle. Roger "Harlin Seritt" wrote in message news:1114823011.063614.27150 at l41g2000cwc.googlegroups.com... >I am using os.getpid() to get the pid value for a script running. I > store that value (as a string) to a file. Later when I try to kill that > pid (i pull this from the file as a string value) I get errors. > > Using the following lines I get the subsequent error. > > (pid is a string value) > win32api.TerminateProcess(int(pid), 0) > > OR > > ctypes.windll.kernel32.TerminateProcess(int(pid), 0) > > Errors: > > Exception in Tkinter callback > Traceback (most recent call last): > File "C:\Python23\lib\lib-tk\Tkinter.py", line 1345, i > return self.func(*args) > File "vngconsole.py", line 27, in StopVngSvc > win32api.TerminateProcess(int(pid), 0) > error: (6, 'TerminateProcess', 'The handle is invalid.') > > How exactly do I kill a pid using a string value? > ----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! >100,000 Newsgroups ---= East/West-Coast Server Farms - Total Privacy via Encryption =--- From http Sat Apr 2 15:28:13 2005 From: http (Paul Rubin) Date: 02 Apr 2005 12:28:13 -0800 Subject: Simple thread-safe counter? References: <7x3bu9ss22.fsf_-_@ruckus.brouhaha.com> Message-ID: <7xmzsg3ov6.fsf@ruckus.brouhaha.com> aahz at pythoncraft.com (Aahz) writes: > This is one case where'd recommend using a plan RLock() instead of using > Queue -- the RLock() will be more efficient... I'm starting to believe the GIL covers up an awful lot of sloppiness in Python. I wonder if there could be a decorator approach: @synchronized def counter(): t = itertools.count() while True: yield t.next() or better yet, counter = synchronized(itertools.count()) From fredrik at pythonware.com Sun Apr 24 11:52:36 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 24 Apr 2005 17:52:36 +0200 Subject: Is this a bug? References: <426bb3e9$0$83084$ed2619ec@ptn-nntp-reader01.plus.net> Message-ID: Robert Kern wrote: > It's consistent with using a.extend("world") which is what the += is > sugar for. > > In [1]:a = ['hello'] > > In [2]:a.extend("world") > > In [3]:a > Out[3]:['hello', 'w', 'o', 'r', 'l', 'd'] > > It's a *good* thing that .extend() takes any iterable without explicit > conversion to a list. I think that it's just a minor annoyance that the > behavior passes on to +=. mapping += to extend is a design mistake (I guess someone got a little carried away). From ckwiguno at gmail.com Tue Apr 19 20:24:41 2005 From: ckwiguno at gmail.com (Clara) Date: 19 Apr 2005 17:24:41 -0700 Subject: Thanks Message-ID: <1113956681.662566.25360@g14g2000cwa.googlegroups.com> Yes that solves my problem all right...THanks a bunch to both of you From mahs at telcopartners.com Thu Apr 7 13:51:02 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Thu, 07 Apr 2005 10:51:02 -0700 Subject: Lambda: the Ultimate Design Flaw In-Reply-To: References: <4253fe0c$1@nntp0.pdx.net> <3bjtvuF6d00nnU2@individual.net> <42556347.9030901@chamonix.reportlab.co.uk> Message-ID: Steve Holden wrote: >> > Not at all - we just apply the same division techniques to the buffer > space until we can map the pieces of cake one-to-one onto the buffers. > That technique can be applied to layer cakes, but not all real cakes. Michael From robin at reportlab.com Tue Apr 26 14:32:29 2005 From: robin at reportlab.com (Robin Becker) Date: Tue, 26 Apr 2005 19:32:29 +0100 Subject: regex over files In-Reply-To: <17006.31984.182979.430076@montanaro.dyndns.org> References: <426D0659.7080307@chamonix.reportlab.co.uk> <426D08BC.1040703@klix.ch> <426E021E.8000809@jessikat.fsnet.co.uk> <17006.31984.182979.430076@montanaro.dyndns.org> Message-ID: <426E893D.2070905@chamonix.reportlab.co.uk> Skip Montanaro wrote: > Robin> So we avoid dirty page writes etc etc. However, I still think I > Robin> could get away with a small window into the file which would be > Robin> more efficient. > > It's hard to imagine how sliding a small window onto a file within Python > would be more efficient than the operating system's paging system. ;-) > > Skip well it might be if I only want to scan forward through the file (think lexical analysis). Most lexical analyzers use a buffer and produce a stream of tokens ie a compressed version of the input. There are problems crossing buffers etc, but we never normally need the whole file in memory. If the lexical analyzer reads the whole file into memory then we need more pages. The mmap thing might help as we need only read pages (for a lexical scanner). Scanners work by detecting the transitions between tokens so even if the tokens are very long we don't need to store them twice (in the input stream and token accumulator); I suppose that could be true of regex pattern matchers, but it doesn't seem to be for re ie we need the entire pattern in the input before we can match and extract to an accumulator. -- Robin Becker From tchur at optushome.com.au Mon Apr 4 06:43:12 2005 From: tchur at optushome.com.au (Tim Churches) Date: Mon, 04 Apr 2005 20:43:12 +1000 Subject: DIY Spam Filter in Python In-Reply-To: <9d5509fa.0504040039.526c93b6@posting.google.com> References: <9d5509fa.0504040039.526c93b6@posting.google.com> Message-ID: <42511A40.7070702@optushome.com.au> Peter Ballard wrote: > I've no idea if this will be of any use to anyone. But since I've gone > to the effort of writing it, I might as well make it publicly > available... > > Until last year, spam filtering was a source of frustration for me. > Freeware packages I tried (specifically, spamassassin and dspam) were > difficult to use. Custom rules using procmail were a pain. > > Then I noticed that python came with email parsing capabilities in the > email module. So I thought that maybe custom rules in python would be > easier than (a) custom rules in procmail, or (b) deciphering the > documentation of a package. And a lot more fun. > > It turned out to be very easy. I got the filter up in a few evenings, > and I've been using it successfully, and slowly enhancing it, over a > number of months. > > In short: a success story for "using the batteries" - at least in my > opinion. > > Source code, and a bit of documentation, is at: > http://members.ozemail.com.au/~pballard/diyspamfilter.html > > -- > Regards, > > Peter Ballard > Adelaide, AUSTRALIA > http://members.ozemail.com.au/~pballard/ Pete mate, Nice work, but your Web page on your DIY Spam Filter doesn't mention SpamBayes, which is surely the definitive Pythonic spam filter, as well as being eerily effective - see http://spambayes.sourceforge.net Not sure that the Reverend Bayes would have agreed with your theology - a bit too post-modern for him, no doubt, but he was nevertheless a lovely little thinker. Tim C From peter at engcorp.com Mon Apr 4 09:33:11 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 04 Apr 2005 09:33:11 -0400 Subject: unittest vs py.test? In-Reply-To: <6oQ3e.10378$db.6219@trndny07> References: <114pqf31isr8k4d@news.supernews.com> <1112372685.034751.99410@o13g2000cwo.googlegroups.com> <1I2dnUmAu5ZPSdDfRVn-rA@powergate.ca> <%Fl3e.1804$7b.990@trndny01> <_4-dnaRR8dv8dNDfRVn-tg@powergate.ca> <6I-dnbpiIZJNJNPfRVn-hA@powergate.ca> <6oQ3e.10378$db.6219@trndny07> Message-ID: Raymond Hettinger wrote: > [Peter Hansen] >>(I'm not dissing py.test, and intend to check it >>out. > > Not to be disrepectful, but objections raised by someone > who hasn't worked with both tools equate to hot air. Not to be disrespectful either, but criticism by someone who has completely missed my point (and apparently not read my posts) doesn't seem entirely fair. At no time in this thread have I objected to py.test. The sole point of my posts has been to object to those claiming unittest as "heavy" when in the same breath they seem to think you have to know all kinds of details about TestSuite, TestRunner, and TestResult objects just to use it. I tried to demonstrate that my way of using it appears to be on the same order of "lightness" as some of the samples that were being used to show how much lighter py.test was. > Until you've exercised both packages, you haven't helped the OP > whose original request was: "Is there anybody out there who has > used both packages and can give a comparative review?" It seems possible to me that I might have helped him solely by pointing out that unittest might not be so "heavy" as some people claimed. I got the impression that he might be swayed by some unfounded claims not even to look further at unittest, which I felt would be a bad thing. (Not to say your comments are unfounded, as clearly they are valid... I happen to believe mine have been, in this thread, as well. I guess you're free to believe otherwise. Cheers.) -Peter From tganss_at_t_dash_online_dot_de-remove-all-after-first-real-dash at yahoo.com Fri Apr 29 01:08:16 2005 From: tganss_at_t_dash_online_dot_de-remove-all-after-first-real-dash at yahoo.com (Thomas Ganss) Date: Fri, 29 Apr 2005 07:08:16 +0200 Subject: win32ui CreateFileDialog SLOW (since the SP2 Windows XP patch?) In-Reply-To: <1114660828.584660.126820@f14g2000cwb.googlegroups.com> References: <1114644362.619393.317800@l41g2000cwc.googlegroups.com> <1114660828.584660.126820@f14g2000cwb.googlegroups.com> Message-ID: MsKitty schrieb: > Neil - > Interesting theory, but I installed brand new versions of Python > (2.4.1) and the win32 extensions on a machine that had no Python and > got the the same 4 minute response time, so that does not seem a likely > explanation, although its possible. > - Kitty > Standalone machine or connected to a network ? By any chance an older server (W2K,NT4) there ? There were some issues... HTH thomas From kristian.zoerhoff at gmail.com Thu Apr 7 16:55:29 2005 From: kristian.zoerhoff at gmail.com (Kristian Zoerhoff) Date: Thu, 7 Apr 2005 15:55:29 -0500 Subject: curious problem with large numbers In-Reply-To: References: Message-ID: <3511dc7505040713552349b49@mail.gmail.com> On Apr 7, 2005 3:34 PM, David M. Cooke > > I don't do Windows, so I can't say this will work, but try > > >>> inf = 1e308*2 I *do* do Windows, and that does work. The value of inf then becomes '1.#INF' as expected. Strangely, doing float('1.#INF') still fails on Windows. Weird, weird. -- Kristian kristian.zoerhoff(AT)gmail.com zoerhoff(AT)freeshell.org From RonGrossi382576 at yahoo.com Fri Apr 15 21:06:48 2005 From: RonGrossi382576 at yahoo.com (RonGrossi382576 at yahoo.com) Date: 15 Apr 2005 18:06:48 -0700 Subject: Do You Want To Know For Sure That You Are Going To Heaven? The reason some people don't know for sure if they are going to Heaven when they die is because they just don't know. The good news is that you can know for sure that you are going to Heaven which is described in the Holy Bible as a beautiful place with no death, sorrow, sickness or pain. (newsgroup-post 140) Message-ID: <1113613608.511723.298610@o13g2000cwo.googlegroups.com> The reason some people don't know for sure if they are going to Heaven when they die is because they just don't know. The good news is that you can know for sure that you are going to Heaven which is described in the Holy Bible as a beautiful place with no death, sorrow, sickness or pain. God tells us in the Holy Bible how simple it is to be saved so that we can live forever with Him in Heaven. "For if you confess with your mouth Jesus is Lord and believe in your heart that God raised Him from the dead, you WILL BE SAVED." (Romans 10:9) Over 2000 years ago God came from Heaven to earth in the person of Jesus Christ to shed His blood and die on a cross to pay our sin debt in full. Jesus Christ was born in Israel supernaturally to a virgin Jewish woman named Mary and lived a sinless life for thirty-three years. At the age of thirty-three Jesus was scourged and had a crown of thorns pressed onto His head then Jesus was crucified. Three days after Jesus died on a cross and was placed in a grave Jesus rose from the dead as Jesus said would happen before Jesus died. If someone tells you that they are going to die and in three days come back to life again and it happens then this person must be the real deal. Jesus Christ is the only person that ever lived a perfect sinless life. This is why Jesus is able to cover our sins(misdeeds) with His own blood because Jesus is sinless. The Holy Bible says, "In Him(Jesus) we have redemption through His blood, the forgiveness of sins..." (Ephesians 1:7) If you would like God to forgive you of your past, present and future sins just ask Jesus Christ to be your Lord and Saviour. It doesn't matter how old you are or how many bad things that you have done in your life including lying and stealing all the way up to murder. Just pray the prayer below with your mouth and mean it from your heart and God will hear you and save you. Dear Jesus Christ, I want to be saved so that I can have a home in Heaven with You when I die. I agree with You that I am a sinner. I believe that You love me and want to save me. I believe that You bled and died on the cross to pay the penalty for my sins and that You rose from the dead. Please forgive my sins and come into my heart and be my Lord and Saviour. Thanks Lord Jesus Christ for forgiving me and saving me through Your merciful grace. Amen. Welcome to the family of God if you just allowed God to save you. Now you are a real Christian and you can know for sure that you will live in Heaven forever when this life comes to an end. As a child of God we are to avoid sin(wrongdoing), but if you do sin the Holy Bible says, "My dear children, I write this to you so that you will not sin. But if anybody does sin, we have one who speaks to the Father in our defense Jesus Christ, the Righteous One." Those of you that have not yet decided to place your trust in the Lord Jesus Christ may never get another chance to do so because you do not know when you will die. This means that if you die without trusting in Jesus Christ as your Lord and Saviour you will be forever separated from the love of God in a place called Hell. The Holy Bible descibes Hell as a place of eternal torment, suffering, pain and agony for all those who have rejected Jesus Christ. The good news is that you can avoid Hell by allowing Jesus Christ to save you today. Only then will you have true peace in your life knowing that no matter what happens you are on your way to Heaven. Praise the Lord! Servant of the Lord Jesus Christ Ronald L. Grossi *Show this to your family and friends so they can know that they have a choice where they will spend eternity. Thanks! ____________________________________________________ Got Questions? http://www.gotquestions.org/archive.html Other Languages http://www.godssimpleplan.org/gsps.html Free Movie: To Hell and Back http://www.tbn.org/index.php/8/1.html Animation http://www.browser.to/jesus-animation The Passion Of The Christ http://www.thepassionofthechrist.com Beware Of Cults http://www.carm.org/cults/cultlist.htm About Hell http://www.equip.org/free/DH198.htm Is Jesus God? http://www.powertochange.com/questions/qna2.html Free Online Bible http://www.bibledatabase.net ____________________________________________________ The Death of John Paul II John Paul II gained the whole world but forfeited his soul. Year after year he was the most loved and admired man in the world. The idolatrous veneration and adoration of this man was unprecedented. His devotees, who are now singing his praises, are probably ignorant of the strong rebuke of Jesus who said, "Woe to you when all men speak well of you" (Luke 6:26). Had the pope been devoted to Jesus Christ and His Gospel of grace, he would have been hated and persecuted by the world. No one can judge John Paul's heart but we are all called to judge the fruit of our spiritual leaders. Clearly this man was blinded by the prince of this world and never saw the light of the gospel or the glory of Christ. I mourn the death of this man, not for the reason the world mourns, but because he rejected Jesus as God's only provision for his sins. I also have a solemn compassion for those who blindly followed this pope and his man-centered religion. My heart is painfully burdened to see so many "professing" Christians unable to discern truth from error and genuine Christianity from its counterfeit. The rest of this article that was written by Mike Gendron can be found at >> http://www.pro-gospel.org/main/Topics/topic-027.php ____________________________________________________ From radam2 at tampabay.rr.com Sun Apr 3 16:20:56 2005 From: radam2 at tampabay.rr.com (Ron_Adam) Date: Sun, 03 Apr 2005 20:20:56 GMT Subject: Decorater inside a function? Is there a way? References: <1112466233.403989.125810@l41g2000cwc.googlegroups.com> <1112516432.638697.193840@o13g2000cwo.googlegroups.com> <2erv41d8ilujl0vmformr26vm0tvhf689o@4ax.com> <1112552255.356217.81640@f14g2000cwb.googlegroups.com> Message-ID: On 3 Apr 2005 11:17:35 -0700, "George Sakkis" wrote: >>def define(func): >> if not ENABLE_TYPECHECKING: >> return lambda func: func >> # else decorate func > >A small correction: The argument of the decorator is not 'func' but the >parameter checks you want to enforce. A template for define would be: > >def define(inputTypes, outputType): > if not ENABLE_TYPECHECKING: > return lambda func: func > def decorate(func): > def typecheckedFunc(*args,**kwds): > ##### TYPECHECK *args, **kwds HERE ##### > r = func(*args,**kwds) > ##### TYPECHECK r HERE ##### > return r > return typecheckedFunc > return decorate This is the same pattern I used except without the enable/disable at the top. The inline type check function also checks for TYPECHECK == True, and TYPESTRICT == False, as default to determine the strictness of the type checking wanted. Where TYPESTRICT == True, causes it to give an error if they are not the correct type, even if they are the exact value. TYPESTRICT == False, result in it trying to convert the object, then checks it, by converting it back to the original type. If it's still equal it returns the converted object in the specified type. >Depending on how much flexibility you allow in inputTypes, filling in >the typechecking logic can be from easy to challenging. For example, >does typechecking have to be applied in all arguments or you allow >non-typechecked aruments ? Can it handle *varargs and **kwdargs in the >original function ? An orthogonal extension is to support 'templated >types' (ala C++), so that you can check if something is 'a dict with >string keys and lists of integers for values'. I would post my module >here or the cookbook but at 560 (commented) lines it's a bit long to >qualify for a recipe :-) > >George Sounds like your version does quite a bit more than my little test functions. :) I question how far type checking should go before you are better off with a confirmtypes() function that can do a deep type check. And then how much flexibility should that have? My view point is that type checking should be available to the singleton types, with conversions only if data integrity can be insured. ie.. the conversion is reversible with an "identical" result returned. def type_convert( a, t): b = t(a) aa = type(a)(b) if a == aa: return b else: raise TypeError In cases where a conversion is wanted, but type checking gives an error, an explicit conversion function or method should be used. In containers, and more complex objects, deep type checking should be available through a general function which can compare an object to a template of types, specific to that object. It's important to use a template instead of a sample, because a sample could have been changed. It's all about protecting the data content with a high degree of confidence. In general, 98% of the time the current python way would be adequate, but those remaining 2% are important enough to warrant the additional effort that type checking takes. On another note, there's the possibility that type checking in python source code could make writing a compiler easier. Another idea is that of assigning a name a type preference. And then overload the assign operators to check for that first before changing a name to point to a new object. It could probably be done with a second name dictionary in name space with {name:type} pairs. With that approach you only need to give key variables a type, then they keep that type preference until it's assigned a new type, or removed from the list. The down side to this is that it could slow things down. Cheers, Ron From mauriceling at acm.org Thu Apr 21 18:08:24 2005 From: mauriceling at acm.org (Maurice LING) Date: Fri, 22 Apr 2005 08:08:24 +1000 Subject: python LEX References: Message-ID: jozo wrote: > I have to work on python lexical definition in Lex. I spent lots of my > time to find regular expresions written for Lex of Python language but > nothing. > Can somebody help me? > > I nEED hELP > > Jython has a Python language lexer written using JavaCC. From steve at holdenweb.com Tue Apr 12 15:18:13 2005 From: steve at holdenweb.com (Steve Holden) Date: Tue, 12 Apr 2005 15:18:13 -0400 Subject: exporting imports to reduce exe size? In-Reply-To: References: Message-ID: Ron_Adam wrote: > In looking at ways to reduce the size of exe's created with py2exe, > I've noticed that it will include a whole library or module even if I > only need one function or value from it. > > What I would like to do is to import individual functions and then > export 'write' them to a common resource file and import that with > just the resources I need in them. > You've been thinking again, Ron ... > Has anyone tried this? > I'd be surprised if they had (see below). > I'm considering using pickle to do it, but was wondering if this is > even a viable idea? > What would you pickle and what not? The reason that a function is stored in a module is often because the module contains other supporting code that it needs. Generally the elements of a module should have a higher-than-random degree of interdependence. > Is it possible to pickle the name space after the imports and then > reload the name space in place of the imports later? > This would be quite a feat of introspection if you could do it. > Cheers, > Ron > As another respondent suggested the savings of this technique would likely not be a reasonable return on the development and support effort. regards Steve -- Steve Holden +1 703 861 4237 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ From jepler at unpythonic.net Sun Apr 3 13:25:11 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Sun, 3 Apr 2005 12:25:11 -0500 Subject: "specialdict" module In-Reply-To: <3bamhhF6j009lU1@individual.net> References: <3bamhhF6j009lU1@individual.net> Message-ID: <20050403172510.GB3398@unpythonic.net> The software you used to post this message wrapped some of the lines of code. For example: > def __delitem__(self, key): > super(keytransformdict, self).__delitem__(self, > self._transformer(key)) In defaultdict, I wonder whether everything should be viewed as a factory: def setdefaultvalue(self, value): def factory(): return value self.setdefaultfactory(factory) and the "no-default" mode would either cease to exist, or def cleardefault(self): def factory(): raise KeyError, "key does not exist and no default defined" self.setdefaultfactory(factory) (too bad that the key isn't available in the factory, this degrades the quality of the error messge) if so, __getitem__ becomes simpler: __slots__ = ['_default'] def __getitem__(self, key): try: return super(defaultdict, self).__getitem__(key) except KeyError: return self.setdefault(key, apply(*self._default)) I don't ever have an itch for sorted dictionaries, as far as I can remember, and I don't immediately understand the use of keytransformdict. Can you give an example of it? Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From trentm at ActiveState.com Mon Apr 18 19:31:17 2005 From: trentm at ActiveState.com (Trent Mick) Date: Mon, 18 Apr 2005 16:31:17 -0700 Subject: Updating Windows File Summary Data In-Reply-To: <1113860278.876481.210270@z14g2000cwz.googlegroups.com> References: <1113860278.876481.210270@z14g2000cwz.googlegroups.com> Message-ID: <20050418233117.GE1979@ActiveState.com> [Denrael wrote] > I am looking for a way in Python to update Windows File Summary > Metadata. By that I mean the data (Title, Subject, Keywords, Comments) > found when you right click a windows file, select properties and then > summary. Can anyone point me in the right direction? I'm not sure if modifying that metadata works the same way as updating version metadata. If so, verstamp.py here might help you get started: http://cvs.sourceforge.net/viewcvs.py/pywin32/pywin32/win32/scripts/VersionStamp/ Cheers, Trent -- Trent Mick TrentM at ActiveState.com From fiedzia at fiedzia.prv.pl Tue Apr 26 06:46:34 2005 From: fiedzia at fiedzia.prv.pl (Maciej Dziardziel) Date: Tue, 26 Apr 2005 12:46:34 +0200 Subject: delete will assure file is deleted? References: <1114510350.912358.21990@f14g2000cwb.googlegroups.com> Message-ID: <20050426104635.2708.0.NOFFLE@fiedzia.homeip.net> ajikoe at gmail.com wrote: > Hello, > > If I use os.remove(fileName), does it always assure that the code will > move to the next code only if the fileName is deleted completely? Yes, it will be deleted, but not necessary completly. Deleting isn't equal to erasing file's content, so it might be possible to recover deleted file, plus on some systems deleted files are kept for those processes (and only for them), who are still using them, and disappear when everyone close them. -- Maciej "Fiedzia" Dziardziel (fiedzia (at) fiedzia (dot) prv (dot) pl) www.fiedzia.prv.pl Giraffiti: Concrete art spray-painted very, very high. From steve at holdenweb.com Wed Apr 6 10:30:47 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 06 Apr 2005 10:30:47 -0400 Subject: formatting file In-Reply-To: <20050406132226.25060.qmail@web50110.mail.yahoo.com> References: <20050406132226.25060.qmail@web50110.mail.yahoo.com> Message-ID: SPJ wrote: > Hi, > > I am new to python hence posing this question. > I have a file with the following format: > > test1 1.1-1 installed > test1 1.1-1 update > test2 2.1-1 installed > test2 2.1-2 update > > I want the file to be formatted in the following way: > > test1 1.1-1 1.1-2 > test2 2.1-1 2.1-2 > > How can I achieve this? I am stuck here. > I suspect you need to a) remove the error in your specification (should there not be a "1.1-2 somewhere in the input) and/or b) explain the exact intent in a little more detail - we aren't psychic, and while the problem may be very obvious to you, we aren't inside your head with it! regards Steve -- Steve Holden +1 703 861 4237 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ From postmaster at castleamber.com Sat Apr 23 23:03:30 2005 From: postmaster at castleamber.com (John Bokma) Date: 24 Apr 2005 03:03:30 GMT Subject: Python or PHP? References: <1114254894.512656.297040@l41g2000cwc.googlegroups.com> <87hdhxwj6s.fsf@debian.kirkjobsluder.is-a-geek.net> <1114274632.128667.281820@l41g2000cwc.googlegroups.com> <86br85rvfw.fsf@guru.mired.org> <863bthrmtg.fsf@guru.mired.org> Message-ID: Mike Meyer wrote: > John Bokma writes: > >> Mike Meyer wrote: >> >>> "Simon John" writes: >>> >>>> I still love Perl, it's a bit of an art form, as "there's more than >>>> one way to do it", whereas Python usually only allows one way to do >>>> it, which may or may not be a better mantra.... >>> >>> The Python mantra leads to 1) less programmer overhead, and 2) faster >>> improvements in the language. >>> >>> To be a Perl expert, you have to know which of the many ways to do >>> various things is the fasted under what conditions. >> >> Why? > > One of the stated conditions for more than one Perl position I've > looked at. That's weird, since some can differ between versions of Perl like for example a map in a void context. And I am sure Python has now and then improvements which make one operation suddenly 10% faster in a new version. So it tells you a lot about the people providing the position ;-) >>> Having only one obvious way >> I doubt that too ;-) > > Try programming in older Python for a while. You'll quit doubting it. Again I doubt that. I doubt that if I give 100 old Python programmers a certain computer science problem I will see 100 exactly the same solutions, which when benchmarked run equally fast. >>> to do things means developers only have to >>> worry about impact on that way when making improvements, which will >>> speed them up. >> Yeah, Perl programmers are extremely slow ;-) > > Nah, they aren't slow. They just have to worry about more things than > the Python developers. Do you have references to this? I would love to see if indeed 100 Python programmers do implement, say 5 CS tasks faster compared to 100 Perl programmers, on average. >> In most cases, why worry? If speed is an issue you should probably have >> picked a different programming language in the first place (for that >> part of the code). > > You apparently haven't been programming in Python very long. Nope. I think I copied 3 examples and had a peek at it. I did read the tutorial (twice) and am rereading Dive into Python. > If speed > is an issue, you should probably pick a different > algorithm. Well-written Python programs use the C-coded parts of > Python for the time-critical part of the code. Why are those time critical parts not written in Python ;-) >> Use the one that is the easiest to read and understand by yourself. >> That's how I program Perl, and that's how I am going to program Python. > > The thing is, in Python there usually is one obvious way to do > things. That's changed in recent years as improvements have been added > without dropping the features they replaced so as not to break old > programs. I know to little about Python, especially about old Python, to have an idea of what you mean. I only saw, quite recently, someones solution to a problem that used 30 lines of Python, and I am sure I could have written it in 3-4. And I doubt that's because he was using, or I was thinking in, new Python :-D. >> An overloaded toolbox doesn't mean that if you have to hang a painting >> on the wall that you have to think for 6 hours which tool you should >> use. You just take the one that does the job in a way you feel >> comfortable with. I know that the Perl mantra is often misunderstood, >> but in my experience only by people who have very little experience with >> the language. > > The problem with using "the way you feel comfortable with" is that it > may not be comfortable for the maintainer - even if that's you six > months from now. After 5 years one gets comfortable with most constructions in a language. I am more often uncomfortable with the way someone translates a problem into code. And there is no way how you can force people with a language that is, to do that the same, not even close. > My Perl evolved from very shell script like (lots of > backticks and passing around the full text of files) I am sure you can do that with Python too. > to one more > C-like as I used the language. That change was largely driven by > performance concerns as my understanding of the language grew. Yup, in Perl one should program Perl, not bash, not C. Same for Python. -- John MexIT: http://johnbokma.com/mexit/ personal page: http://johnbokma.com/ Experienced programmer available: http://castleamber.com/ Happy Customers: http://castleamber.com/testimonials.html From franz.steinhaeusler at utanet.at Tue Apr 5 06:13:59 2005 From: franz.steinhaeusler at utanet.at (Franz Steinhaeusler) Date: Tue, 05 Apr 2005 12:13:59 +0200 Subject: Eric3 under WinXP References: Message-ID: <8to45154ueb3m8gfb0sj1v3ud24j5jnm7d@4ax.com> On Tue, 5 Apr 2005 10:14:48 +0100 (BST), "Phil Thompson" wrote: >> On Tue, 5 Apr 2005 09:17:05 +0100 (BST), "Phil Thompson" >> wrote: >> >> What steps are missing? > >If you are using the evaluation version of Qt then you need the evaluation >version of PyQt. This already includes SIP and QScintilla. > >Phil Hello Phil, Ok, new begin. I installed PyQt 3.14.1 Evaluation now. If I want to start for example aclock.py, I get: ImportError: No module named qt Is there any dll missing? Or doesn't it fit with "Qt 3.3.4 Evaluation" Any hints? -- Franz Steinh?usler http://drpython.sourceforge.net/ http://mitglied.lycos.de/drpython/ From radam2 at tampabay.rr.com Sun Apr 3 14:00:36 2005 From: radam2 at tampabay.rr.com (Ron_Adam) Date: Sun, 03 Apr 2005 18:00:36 GMT Subject: Decorator Dissection References: <4p9t419ockcg8578g6guse3a14t16orebf@4ax.com> <1112455359.773729.92080@l41g2000cwc.googlegroups.com> <6git41doqfbk01h8lsk1gl7u91qgspivrp@4ax.com> <424F8DE9.7070501@v.loewis.de> Message-ID: On Sun, 03 Apr 2005 08:32:09 +0200, "Martin v. L?wis" wrote: >Ron_Adam wrote: >> I wasn't aware that the form: >> >> result = function(args)(args) >> >> Was a legal python statement. >> >> So python has a built in mechanism for passing multiple argument sets >> to nested defined functions! (click) Which means this is a decorator >> without the decorator syntax. > >No. There is no mechanism for passing multiple argument sets to >nested functions. Instead, functions are objects, which can be >assigned to variables, passed as arguments to other functions, >and returned: Yes there is, it's the stack python uses to interpret the byte code. But it's the same mechanism that is used for passing arguments to sequential function calls (objects) also. The only difference is the next function (object) is returned on the stack in the nested case. Then the next argument is then put on to the stack (passed), before the next function is called. How you view this depends on the frame of reference you use, I was using a different frame of reference, which I wasn't sure was correct at the time, but turns out is also valid. So both view points are valid. In any case, I now have a complete picture of how it works. Inside, and out. Which was my goal. :) >> So this isn't a decorator question any more. Each argument gets >> passed to the next inner defined function, via... a stack(?) ;) > >No, functions are objects. Notice that in step 1, the object returned >doesn't have to be a function - other things are callable, too, like >types, classes, and objects implementing __call__. They are objects; which are data structures; containing program code & data; which reside in memory; and get executed by, in this case, a byte code interpreter. The interpreter executes the byte code in a sequential manner, using a *stack* to call functions (objects), along with their arguments. For the record, I never had any trouble understanding the concept of objects. I think I first started programming OOP in the mid '90's with c++. It was the sequence of events in the objects of the nested def functions that I was trying to understand along with where the objects get their arguments, which isn't obvious because of the levels of indirect calling. Thanks for the help Martin, it's always appreciated. :) Cheers, Ron >Regards, >Martin From andreis at stud.cs.uit.no Fri Apr 15 04:15:47 2005 From: andreis at stud.cs.uit.no (=?ISO-8859-1?Q?Andr=E9_S=F8reng?=) Date: Fri, 15 Apr 2005 10:15:47 +0200 Subject: RE Engine error with sub() In-Reply-To: References: Message-ID: Instead of using regular expressions, you could perhaps use a multiple keyword matcher, and then for each match, replace it with the correct string. http://hkn.eecs.berkeley.edu/~dyoo/python/ahocorasick/ contains the Aho-Corasick algorithm written in C with a Python extension. Maurice LING wrote: > Hi, > > I have the following codes: > > from __future__ import nested_scopes > import re > from UserDict import UserDict > > > class Replacer(UserDict): > """ > An all-in-one multiple string substitution class. This class was > contributed by Xavier > Defrang to the ASPN Python Cookbook > (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330) > and alane at sourceforge.net. > > Copyright: The methods _make_regex(), __call__() and substitute() > were the work of Xavier Defrang, > __init__() was the work of alane at sourceforge.net, all others were > the work of Maurice Ling""" > > def __init__(self, dict = None, file = None): > """Constructor. It calls for the compilation of regular > expressions from either > a dictionary object or a replacement rule file. > > @param dict: dictionary object containing replacement rules with > the string to be > replaced as keys. > @param file: file name of replacement rule file > """ > self.re = None > self.regex = None > if file == None: > UserDict.__init__(self, dict) > self._make_regex() > else: > UserDict.__init__(self, self.readDictionaryFile(file)) > self._make_regex() > > def cleanDictionaryFile(self, file): > """ > Method to clean up the replacement rule dictionary file and > write the cleaned > file as the same name as the original file.""" > import os > dict = self.readDictionaryFile(file) > f = open(file, 'w') > for key in dict.keys(): f.write(str(key) + '=' + str(dict[key]) > + os.linesep) > f.close() > > def readDictionaryFile(self, file): > """ > Method to parse a replacement rule file (file) into a dictionary > for regular > expression processing. Each rule in the rule file is in the form: > = > """ > import string > import os > f = open(file, 'r') > data = f.readlines() > f.close() > dict = {} > for rule in data: > rule = rule.split('=') > if rule[1][-1] == os.linesep: rule[1] = rule[1][:-1] > dict[str(rule[0])] = str(rule[1]) > print '%s replacement rule(s) read from %s' % > (str(len(dict.keys())), str(file)) > return dict > > def _make_regex(self): > """ Build a regular expression object based on the keys of the > current dictionary """ > self.re = "(%s)" % "|".join(map(re.escape, self.keys())) > self.regex = re.compile(self.re) > > def __call__(self, mo): > """ This handler will be invoked for each regex match """ > # Count substitutions > self.count += 1 # Look-up string > return self[mo.string[mo.start():mo.end()]] > > def substitute(self, text): > """ Translate text, returns the modified text. """ > # Reset substitution counter > self.count = 0 > # Process text > #return self._make_regex().sub(self, text) > return self.regex.sub(self, text) > > def rmBracketDuplicate(self, text): > """Removes the bracketed text in occurrences of ' > ()'""" > regex = re.compile(r'(\w+)\s*(\(\1\))') > return regex.sub(r'\1', text) > > def substituteMultiple(self, text): > """Similar to substitute() method except that this method loops > round the same text > multiple times until no more substitutions can be made or when > it had looped > 10 times. This is to pre-ampt for cases of recursive > abbreviations.""" > count = 1 # to get into the loop > run = 0 # counter for number of runs thru the text > while count > 0 and run < 10: > count = 0 > text = self.rmBracketDuplicate(self.substitute(text)) > count = count + self.count > run = run + 1 > print "Pass %d: Changed %d things(s)" % (run, count) > return text > > > > > Normally I will use the following to instantiate my module: > > replace = Replacer('', 'rule.mdf') > > rule.mdf is in the format of "= with>\n" > > Then using replace.substituteMultiple('') to carry out multiple > replacements. > > It all works well for rule count up to 800+ but when my replacement > rules swells up to 1800+, it gives me a runtime error that says > "Internal error in regular expression engine"... traceable to "return > self.regex.sub(self, text)" in substitute() method. > > > Any ideas or workarounds? > > Thanks in advance. > > Cheers, > Maurice From sheila at spamcop.net Fri Apr 22 02:45:11 2005 From: sheila at spamcop.net (Sheila King) Date: Fri, 22 Apr 2005 06:45:11 GMT Subject: time.strftime in 2.4.1 claims data out of range when not Message-ID: <0001HW.BE8DEB89000A10E8F02845B0@news.verizon.net> I have a web app that has been running just fine for several months under Python 2.2.2. We are preparing to upgrade the server to run Python 2.4.1. However, part of my web app is throwing an error on this code (that has previously worked without exception): >>> time.strftime("%Y-%m-%d", (Y, M, D, 0,0,0,0,0,0)) Traceback (most recent call last): File "", line 1, in ? ValueError: day of year out of range >>> Y 2005 >>> M 5 >>> D 15L I don't see what parts of the date that I have submitted to strftime are out of range? Also, the phrasing of the error message is a bit odd? "day of year out of range" I'm not sure what the day of a year would be??? Sheila King http://www.thinkspot.net/sheila/ From deetsNOSPAM at web.de Fri Apr 29 09:25:49 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Fri, 29 Apr 2005 15:25:49 +0200 Subject: undefined symbol: PyUnicodeUCS4_AsUTF8String References: <46o9k2-qe4.ln1@nb2.stroeder.com> Message-ID: Michael Str?der wrote: > HI! > > I have the following problem after system upgrade to SuSE Linux 9.3: > > $ python -c "import cPickle" > Traceback (most recent call last): > File "", line 1, in ? > ImportError: /usr/lib/python2.4/lib-dynload/cPickle.so: undefined > symbol: PyUnicodeUCS4_AsUTF8String > > The Python 2.4.1 installation was built from source. > > Anyone having a clue? Thanks in advance. Yes - unfortunately binary extensions have to be rebuilt if you chose a different unicode representation - ucs4 instead of ucs2. Which you most probably didn't do on purpose. So there are two options here: - rebuilt python, with ucs2 as internal representation (configure option) - rebuilt the extensions. -- Regards, Diez B. Roggisch From fredrik at pythonware.com Wed Apr 13 05:07:13 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 13 Apr 2005 11:07:13 +0200 Subject: A command in a String ? References: Message-ID: Peter Moscatt wrote: >> strings = "string1", "string2", "string3" >> fm = OptionMenu(root, xx, *strings) > > Thanks for the help on this. Yea the 'exec' did the trick. > The second example just placed all the strings in one option button. did you include the asterisk? if you remove that, you get one option. if you include it, you get three options. From beliavsky at aol.com Thu Apr 21 22:06:41 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 21 Apr 2005 19:06:41 -0700 Subject: Why Python does *SLICING* the way it does?? References: <1113976729.450677.261130@o13g2000cwo.googlegroups.com> <_Lm9e.23143$Xm3.17864@trndny01> <1114003997.778676.144950@z14g2000cwz.googlegroups.com> <1114109221.149346.64850@z14g2000cwz.googlegroups.com> Message-ID: <1114135601.328421.165760@z14g2000cwz.googlegroups.com> Dan Bishop wrote: > Antoon Pardon wrote: > > Like users have a choice in how long they make a list, they > > should have a choice where the indexes start. (And that > > shouldn't be limited to 0 and 1). > > Suppose you could. Then what should > > ([3, 1, 4] indexbase 0) + ([1, 5, 9] indexbase 4) > > equal? Assuming the + sign means concatenate (as it does for Python lists) rather than add (as it does for Numeric or Numarray arrays), it would be ([3,1,4,1,5,9] indexbase 0) since 0 would still be the default indexbase. If the user wanted a 1-based list as a result, he would use an expression such as (([3, 1, 4] indexbase 0) + ([1, 5, 9] indexbase 4) indexbase 1) If + means add, the result would be ([4,6,13] indexbase 0) . Adding arrays makes sense if they have the same number of elements -- they do not need to have the same indices. I rarely see problems caused by flexible lower array bounds mentioned in comp.lang.fortran . From ml at fgranger.com Thu Apr 21 16:19:11 2005 From: ml at fgranger.com (Fran=?ISO-8859-1?B?5w==?=ois Granger) Date: Thu, 21 Apr 2005 22:19:11 +0200 Subject: recording data between [ and ] In-Reply-To: Message-ID: Le 21/04/05 16:19, ??rbt?? a ?crit?: > Peter Hansen wrote: >> rbt wrote: >> >>> Output from 'netstat -b' on a win2003 server will show what binary is >>> responsible for the connection. For example, it may list something >>> like this along with other connection specific data: >>> >>> [lsass.exe] >>> [System] >>> [firefox.exe] >>> [iexplorer.exe] >>> >>> How might I process the output so that anything within brackets is >>> recorded to a log file of my own making? I know how to parse and >>> record things to a file, I don't know how to look make '[' and ']' >>> appear as special characters so that I can record what's between them. >> >> >> Does this help? >> >>>>> import re >>>>> >>>>> s = '''stuff [lsass.exe] >> ... [System] more stuff >> ... xxxxx [firefox.exe] ...... >> ... ''' >>>>> >>>>> re.findall(r'\[([^]]*)\]', s) >> ['lsass.exe', 'System', 'firefox.exe'] > > Yes, it does... may take me a few minutes to get my head around it > though. Why do re's have to be so arcane and complicated... especially > in Python? Items = s.split('[') For item in items: end = item.find(']') label = item[:end] Not tested, ugly and slow, but may be more understandable -- Convert from markup to markup: http://fgranger.net1.nerim.net/mtom/ From miki.tebeka at zoran.com Wed Apr 6 01:46:11 2005 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Wed, 6 Apr 2005 08:46:11 +0300 Subject: cross platform printing In-Reply-To: <0hx4e.3479$3O2.2184@trnddc01> References: <0hx4e.3479$3O2.2184@trnddc01> Message-ID: <20050406054611.GC876@zoran.com> Hello David, > "Alan Isaac" wrote in message > news:_A34e.2207$1r6.248 at trnddc02... > > I'd like to try personal financial management using Python. > > I just found PyCheckbook, but it does not support check printing. > > Is there a Python check printing application kicking around? wxPython is a cross platfom UI framework which has printing support. Maybe you can cook something. HTH. -- ------------------------------------------------------------------------ Miki Tebeka http://tebeka.bizhat.com The only difference between children and adults is the price of the toys -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 193 bytes Desc: not available URL: From tjreedy at udel.edu Tue Apr 26 13:15:00 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 26 Apr 2005 13:15:00 -0400 Subject: Pythonic way to do static local variables? References: <_xgbe.128633$cg1.54987@bgtnsc04-news.ops.worldnet.att.net> <7Ujbe.647694$w62.444038@bgtnsc05-news.ops.worldnet.att.net> Message-ID: "Charles Krug" wrote in message news:7Ujbe.647694$w62.444038 at bgtnsc05-news.ops.worldnet.att.net... > Both of these techniques look promising here. Here a third, the closure approach (obviously not directly tested): def func_with_static(datalist): def real_func(otherargs): return real_func func1 = func_with_static([.1, 99, 1e-10,...]) If needed, real_func can *modify* (but not *rebind*) datalist. Unlike the attribute approach, but like the class approach, you can simultaneously have have multiple closures with different static data func2 = func_with_static([.2, 152, 1e-9, ...]) Terry J. Reedy From claudio.grondi at freenet.de Tue Apr 19 17:17:08 2005 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Tue, 19 Apr 2005 21:17:08 -0000 Subject: Name/ID of removable Media: how? References: <42650A59.3DF3C6DE@pauahtun.org> Message-ID: <3cl3paF6m7kf4U1@individual.net> Maybe the function below can help? I suppose WMI returns same values as FSO (File System Object): def strDriveHexSerialNumberFromFSOintRetVal(intDriveSerialNumberByFSO): """Supplied with an integer representing a drive serial number returns the number in same format as \>dir command does (i.e. ####-####).""" # The value of axDrive.SerialNumber property (an int or float number) can be # negative, so to get always a positive number as listed by e.g. \>dir # command it is necessary to apply a workaround: if(intDriveSerialNumberByFSO < 0): # dec 4294967295 == hex FFFFFFFF, dec 4294967296 == hex 100000000 intDriveSerialNumber = 4294967296L + intDriveSerialNumberByFSO else: intDriveSerialNumber = intDriveSerialNumberByFSO #:if/else strHexSerialNumber = "%08X"%intDriveSerialNumber strHexSerialNumber = strHexSerialNumber[:4]+"-"+strHexSerialNumber[4:] return strHexSerialNumber #:def strDriveHexSerialNumberFromFSOintRetVal(intDriveSerialNumberByFSO) In your case strDriveHexSerialNumberFromFSOintRetVal(-793919769): gives: D0AD-BEE7 Claudio "Ivan Van Laningham" schrieb im Newsbeitrag news:mailman.2109.1113924702.1799.python-list at python.org... > Hi All-- > Tim's wmi stuff looked interesting, so I tried it out, and now I have a > question. > > > ----- > #!/usr/bin/python > > import wmi > import win32api > > > c=wmi.WMI() > for i in c.Win32_CDROMDrive(): > v=i.VolumeSerialNumber > print "WMI serial",v,long(v,0x10) > > vn,sn,ln,flg,fstype=win32api.GetVolumeInformation("d:\\") > print "win32api serial",sn,long(sn) > ---- > > The output from the above script (drive d contains cd) is: > > WMI serial D0ADBEE7 3501047527 > > win32api serial -793919769 -793919769 > > > What's the difference between the two serial numbers? WMI is returning > a long converted to a hex repr string, while win32api is returning an > int (type(sn) is ), & converting to hex bears no resemblance > to what WMI shows. What am I missing? > > Metta, > Ivan > ---------------------------------------------- > Ivan Van Laningham > God N Locomotive Works > http://www.andi-holmes.com/ > http://www.foretec.com/python/workshops/1998-11/proceedings.html > Army Signal Corps: Cu Chi, Class of '70 > Author: Teach Yourself Python in 24 Hours From m at m.com Wed Apr 27 05:06:51 2005 From: m at m.com (monkey) Date: Wed, 27 Apr 2005 17:06:51 +0800 Subject: Can .py be complied? References: <426ec8f7_2@rain.i-cable.com> Message-ID: <426f562f$1_3@rain.i-cable.com> Thanks all of you guys, I found that python newsgroup is of wealthy knowledge: > If you would like to obfuscate your code (disguise it) without an > executable you can try pyobfuscate as well. > > Harlin Seritt > Yes, I want more options. Since the python doc mentioned py2exe only, and it is difficult to understand how it work.(may be you guys know C and make file, but I am still foolish here...) > It is generally not very easy or straight-forward. > For now, you can use pyfreeze to snap the application..... > If your application does not use any C modules, you can try to use > Jython instead. > > Cheers > Maurice If using Jython to complie, is the end-user need JRE instead of Python installed, or need both of them? > I don't know the exact details, but try using the compiled Python > scripts (bytecode). I believe they are semi-optimized and platform > independent. They are the .pyc and .pyo files generated when the script > is run. > >ryan at ryankaskel Is that means a .py convert to .pyc or .pyo, without the need of "make file" as using py2exe? From steve.horsley at gmail.com Mon Apr 18 16:21:36 2005 From: steve.horsley at gmail.com (Steve Horsley) Date: Mon, 18 Apr 2005 21:21:36 +0100 Subject: Can a function be called within a function ? In-Reply-To: <42639ddc$0$5855$9a6e19ea@news.newshosting.com> References: <42639ddc$0$5855$9a6e19ea@news.newshosting.com> Message-ID: Peter Moscatt wrote: > Is it possible to write code and allow a function to be called within > another like I have shown below ? > > Pete > > > > def populatelist(): > f=open(_globals.appath + "dxcluster.svr","r") > while true: > text = f.readline() > if text =="": > break > _list.append(string.strip(text)) > f.close() > > > def serversettings(): > servers.main(root) > if _globals.refresh=="yes": > populatelist() <----------------------- calling function above. > > Yes. It is perfectly normal. As programs get more complex, you find methods calling methods calling methods. And as Kent pointed out, you are already callin methods from withon methods by calling the likes of open() and close(). Beware of creating loops - methods that call themselves, eitehr directly or by calling other methods that end up calling the original method. This can be done with care to make sure that at some point a method is sure to return without calling onwards, usually by having the problem simplified every time, but you should avoid this kind of thing for now. It's called recursion. An example would be in calculating x to the power of y. x^y can be calculated by working out x * x^(y-1), but x^(y-1) is x * x^(y-2) etc. But you canbe sure this ends when we finally come to work out x^1 which is x, and this breaks the loop. If that makes sense. Steve From kerny404 at gmail.com Wed Apr 27 16:17:07 2005 From: kerny404 at gmail.com (andrea) Date: Wed, 27 Apr 2005 22:17:07 +0200 Subject: creating very small types Message-ID: <426FF343.4040008@gmail.com> I was thinking to code the huffman algorithm and trying to compress something with it, but I've got a problem. How can I represent for example a char with only 3 bits?? I had a look to the compression modules but I can't understand them much... Thank you very much Any good link would be appreciated of course :) From R.Brodie at rl.ac.uk Tue Apr 19 09:03:07 2005 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Tue, 19 Apr 2005 14:03:07 +0100 Subject: xmlrpclib and binary data as normal parameter strings References: Message-ID: "Rune Froysa" wrote in message news:svlacnvhrov.fsf at dresden.uio.no... > From http://www.xmlrpc.com/spec :: > Any characters are allowed in a string except < and &, which are > encoded as < and &. A string can be used to encode binary > data. the XMLRPC specification is worded pretty loosely. Obviously characters forbidden in XML will be problematic. > From http://www.w3.org/TR/2004/REC-xml11-20040204/#dt-character :: That's XML 1.1; it's very rarely used in practice. Can XMLRPC use XML 1.1? In principle, undefined, as far as I know. In practice, not in Python anyway. From mwm at mired.org Sat Apr 23 18:15:47 2005 From: mwm at mired.org (Mike Meyer) Date: Sat, 23 Apr 2005 17:15:47 -0500 Subject: Python or PHP? References: <1114254894.512656.297040@l41g2000cwc.googlegroups.com> <87hdhxwj6s.fsf@debian.kirkjobsluder.is-a-geek.net> <1114274632.128667.281820@l41g2000cwc.googlegroups.com> Message-ID: <86br85rvfw.fsf@guru.mired.org> "Simon John" writes: > I still love Perl, it's a bit of an art form, as "there's more than one > way to do it", whereas Python usually only allows one way to do it, > which may or may not be a better mantra.... The Python mantra leads to 1) less programmer overhead, and 2) faster improvements in the language. To be a Perl expert, you have to know which of the many ways to do various things is the fasted under what conditions. Python programmers seldom have to worry about that - there's usually only one [obvious] way to do things, so you just do it that way. Having only one obvious way to do things means developers only have to worry about impact on that way when making improvements, which will speed them up. The problem these days is that there are now multiple ways to do a variety of things, because we have the "new, pythonic" way and the "old, backwards-compatible way". So it's no longer clear which is the fastest - and in the case of generators versus list comprehensions, it's not clear which you should be using. To bad. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From dan at dontspammecauseidontlikit.com Mon Apr 11 23:47:03 2005 From: dan at dontspammecauseidontlikit.com (Dan) Date: Tue, 12 Apr 2005 11:47:03 +0800 Subject: Can't Stop Process On Windows Message-ID: I have a python script running under Windows XP that I need to terminate from the keyboard. A control-c works fine under Linux, but not under Windows. I'm pretty sure that the culprit is 'select' that I'm using to multiplex socket i/o, which seems to be blocking the keyboard interrupt. Is there some way around this? Dan From cam.ac.uk at mh391.invalid Thu Apr 28 05:46:29 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Thu, 28 Apr 2005 10:46:29 +0100 Subject: dynamically generating temporary files through python/cgi In-Reply-To: <1114669935.274048.63940@z14g2000cwz.googlegroups.com> References: <1114669935.274048.63940@z14g2000cwz.googlegroups.com> Message-ID: poisondart wrote: > I've seen it on certain websites that will > generate a file under certain parameters (through forms) that will > dissapear (i.e. delete itself) after a specified amount of time... > > Is there a group of library functions that allow this? No. The easiest way, in my mind would be to store the files in a directory according to the hour they were requested, for example, a file generated between 2 p.m. and 3 p.m. today: http://www.example.com/temp/20050428T14/d41d8cd98f00b204e9800998ecf8427e.html Then you can have a cron job that runs every hour that deletes everything in the temp directory generated 24 hours ago. -- Michael Hoffman From radam2 at tampabay.rr.com Fri Apr 1 13:30:56 2005 From: radam2 at tampabay.rr.com (Ron_Adam) Date: Fri, 01 Apr 2005 18:30:56 GMT Subject: Decorater inside a function? Is there a way? Message-ID: I'm trying to figure out how to test function arguments by adding a decorator. @decorate def func( x): # do something return x This allows me to wrap and replace the arguments with my own, but not get the arguments that the original function received. To do that I would need to put the decorator inside the function. def func( x): @decorate # doc something return x Then I could use @decorators to check the function input for condition, ranges, and or types. Is there a equivalent way to do that? Also can I use @decorate with assert? Ron From __peter__ at web.de Fri Apr 8 10:50:19 2005 From: __peter__ at web.de (Peter Otten) Date: Fri, 08 Apr 2005 16:50:19 +0200 Subject: unknown encoding problem References: Message-ID: Uwe Mayer wrote: > I need to read in a text file which seems to be stored in some unknown > encoding. Opening and reading the files content returns: > >>>> f.read() > '\x00 \x00 \x00<\x00l\x00o\x00g\x00E\x00n\x00t\x00r\x00y\x00... > > Each character has a \x00 prepended to it. I suspect its some kind of > unicode - how do I get rid of it? Intermittent '\x00' bytes are a indeed strong evidence for unicode. Use codecs.open() to access the data in such a file: >>> import codecs >>> f = codecs.open(filename, "r", "UTF-16-BE") >>> f.read() u' >> _.encode("latin1") ' References: <1112101524.879186.260630@o13g2000cwo.googlegroups.com> <1112116787.160723.219160@l41g2000cwc.googlegroups.com> <4249f2d0.22628407@news.oz.net> Message-ID: <5e183f3d050402204426e9099f@mail.gmail.com> > class Player(object): > def __init__(self, **kw): self.__dict__.update(kw) > def __repr__(self): return ''%getattr(self, 'name', '(anonymous)') > > import operator > [p.name for p in sorted(players, key=operator.attrgetter('attacking'), reverse=True)] Just happened to read this thread and wanted to say this is a neat little example-- thank you! I have a couple of followup questions. (1) Is there a performance penalty for using key=operator.attrgetter()? (2) The Player class looks like a nice model for a data table when one wants to sort by arbitrary column. Would you agree? (3) Suppose one wished to construct a player list from a collection of attribute lists, e.g., names = ['bob', 'sam', 'linda'] attack = [7, 5, 8] defense = [6, 8, 6] # construct players list here Can you recommend an efficient way to construct the player list? Thanks! Marcus From sir.shz at gmail.com Mon Apr 18 15:19:37 2005 From: sir.shz at gmail.com (sir.shz) Date: 18 Apr 2005 12:19:37 -0700 Subject: Twisted for online games Message-ID: <1113851977.195434.78980@l41g2000cwc.googlegroups.com> Hi, I'm just starting to play with Twisted, and planning to use it for sone online games (e.g., casino games, etc.), have people done that before, are there any pointers? Thanks. From Gerald.Klix at klix.ch Tue Apr 12 09:37:14 2005 From: Gerald.Klix at klix.ch (Gerald Klix) Date: Tue, 12 Apr 2005 15:37:14 +0200 Subject: Programming Language for Systems Administrator In-Reply-To: <1113311618.838281.205380@l41g2000cwc.googlegroups.com> References: <1113253691.821235.9750@o13g2000cwo.googlegroups.com> <1113311618.838281.205380@l41g2000cwc.googlegroups.com> Message-ID: <425BCF0A.8060900@klix.ch> Kanthi Kiran Narisetti schrieb: > Hi All, > > Thank You for your suggestions....I request you all to eloborate the > Uses(In Practical) for systems administrator.Some of my questions > regarding the same follows. > > 1)Can i build web applications in Python ? If so how. I am planning to > build a web application for intranet use which deals with workflow of > Internal office communication. Yes, you can. There are far too many options, to be listed here: Here are just 3 pointers: http://www.zope.org/ http://www.cherrypy.org/ http://www.webwareforpython.org/ http://skunkweb.sourceforge.net/ > > 2)Which is best opensource database to be used with Python ? It's hard to say. It depends on our taste and the type of your application. There is a python standard for a relation DB-API and there are som object relational adapters, like: http://python-dbo.sourceforge.net/ http://sqlobject.org/ http://skunkweb.sourceforge.net/PyDO/ http://dustman.net/andy/python/SQLDict And, of course, there is ZODB the object oriented DB below Zope: http://www.zope.org/Products/ZODB3.3 > > 3)When i write a remote execution script in python is it required that > python should be installed in remote system. No. Using xmlrpc the server and may be written in any programming language. xmlrpc is include din the standard libray. Other remote execution systems use CORBA or do things upon their own: http://pyro.sourceforge.net/ It is also possible to package python applications in an executable using: http://starship.python.net/crew/theller/py2exe/ http://starship.python.net/crew/atuining/cx_Freeze/ or the Freeze utility delivered with the python standard distribution. > > 4)I heard about Perl/CGI and that CGI application done by python > too.....Is CGI still valid when PHP has taken over the WebApplication > Development, Dominating. No it's rather slow, but widley used. There is a mod_python for Apache which is used be some of the web application frameworks mentioned above. > > Sorry if these questions are out of this group , but answers to these ? > will help me a lot. The are perfectly valid. HTH, Gerald -- GPG-Key: http://keyserver.veridis.com:11371/search?q=0xA140D634 From rkern at ucsd.edu Sun Apr 17 22:28:31 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sun, 17 Apr 2005 19:28:31 -0700 Subject: python.exe on Mac OS X!? In-Reply-To: <1113786892.458768.95420@z14g2000cwz.googlegroups.com> References: <1113777681.330094.34320@l41g2000cwc.googlegroups.com> <1113786892.458768.95420@z14g2000cwz.googlegroups.com> Message-ID: Rodney Maxwell wrote: >>>executable produced was 'python.exe'. Can someone tell me whether > > this > >>>is a bug, feature, or UserError? > > >>I'm not sure. Why don't you grab the binary? > > >>http://www.python.org/ftp/python/2.4.1/MacPython-OSX-2.4.1-1 .dmg > > > Because I need to keep multiple versions of Python on this machine, and > as far as I can tell the binary installer overwrites the default > installed version. > I could be wrong. You are wrong. It installs alongside. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From dwelch at vcd.hp.com Thu Apr 21 12:34:54 2005 From: dwelch at vcd.hp.com (djw) Date: Thu, 21 Apr 2005 09:34:54 -0700 Subject: Regular Expressions - Python vs Perl In-Reply-To: References: <1114092105.964664.211430@l41g2000cwc.googlegroups.com> <1114098472.768814.281750@g14g2000cwa.googlegroups.com> Message-ID: Thomas Bartkus wrote: > "codecraig" wrote in message > news:1114098472.768814.281750 at g14g2000cwa.googlegroups.com... > > >>Well so far from what I have found, Perl is faster than Python for >>RegEx, although perl is harder to read. > > > Yawn > > How about Python being easier to *write*? > > It never ceases to amaze me. It takes days, weeks, months, sometimes even > years to write significantly useful software. And yet so many seem to think > it is worthy to bother over the seconds that might be saved at execution > time. > > If one were to achieve a mere percentage point or two in improving the > "write" efficiency of software - think how much more the world gains in > software quality and quantity. How about man hours saved? Why does anyone > still waste so much angst over execution speed? > > I doubt the total execution time for all the RegEx queries you ever ran took > as much time as you just wasted on your little experiment. > Thomas Bartkus > > While I agree with (most of) your points, one should not overlook the fact that there are cases when performance does matter (huge datasets maybe?). Since the OP didn't indicate why performance was important to him/her, one cannot assume that its not a valid concern. -Don From steven.bethard at gmail.com Thu Apr 28 22:08:09 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 28 Apr 2005 20:08:09 -0600 Subject: Working with method-wrapper objects In-Reply-To: References: <1830947848@web.de> Message-ID: Dr. Peer Griebel wrote: >> Why has [].__str__ a different type than object.__str__? >> Why is object.__str__ a routine while object().__str__ not? Well, I don't know why inspect.isroutine does what it does, but if you really need to detect these, can you do something like: py> MethodWrapperType = type(object().__str__) py> type([].__str__) == MethodWrapperType True This is basically all the types module does for similar types. (Take a look -- it's written in Python.) > Some more investigation shows that also the module "types" is not > universally usable. E.g. InstanceType is only usabel for instances of > old classes. How do I test for instances of new classes? isinstance(obj, object) All new-style classes are subclasses of object (even type!) STeVe From bokr at oz.net Wed Apr 27 14:57:45 2005 From: bokr at oz.net (Bengt Richter) Date: Wed, 27 Apr 2005 18:57:45 GMT Subject: suggestions on how to do this References: Message-ID: <426fe037.64166596@news.oz.net> On Wed, 27 Apr 2005 11:34:53 GMT, "chris" wrote: >The problem I have is as follows: > >I have a recursive function b(k) > >b(k) = -(A/k**2)*(b(k-2) - b(k-5)) >k<0, b(k)=0 >k=0, b(k)=1 >k=1, b(k)=0 > >eg. b(2) = -A/4 > b(3) = 0 > b(4) = A**2/64 > >note that as k increases b(k) can itself be a sum of terms in powers of A >rather than a single power of A in the examples above. > >Summing all terms and equating to zero gives: > >F= sum b(k) = 0 for all k = 0, infinity > >When this is expanded I get a polynomial F(A). I want to determine the >coefficients of the polynomial so that I can find the roots of the function >F up to a specified order of A. > > >I have yet to code this but I was hoping for some ideas on how to do this >reasonably. > >I figure I can compute each b(k) and store the numeric value(s) and >associated powers of A. Then collect coefficients for like powers of A. >Finally I have a set of polynomial coefficients in A which I can pass to >scipy.base.roots() > >Any suggestions on how I might do this efficiently? I have no doubt I can >get this done with brute force, but I would prefer to explore more elegant >means which I look to the masters for. > Does this look right? b(-5) -> 0 b(-4) -> 0 b(-3) -> 0 b(-2) -> 0 b(-1) -> 0 b(0) -> 0 b(1) -> 0 b(2) -> -A/4 b(3) -> 0 b(4) -> A**2/64 b(5) -> A/25 b(6) -> -A**3/2304 b(7) -> -29*A**2/4900 b(8) -> A**4/147456 b(9) -> 563*A**3/2116800 b(10) -> A**2/2500 -A**5/14745600 b(11) -> -5927*A**4/1024531200 b(12) -> -43*A**3/980000 +A**6/2123366400 b(13) -> 824003*A**5/11081329459200 b(14) -> 16397*A**4/10372320000 -A**7/416179814400 b(15) -> A**3/562500 -1260403*A**6/1994639302656000 Regards, Bengt Richter From reinhold-birkenfeld-nospam at wolke7.net Fri Apr 22 09:42:41 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Fri, 22 Apr 2005 15:42:41 +0200 Subject: Why Python does *SLICING* the way it does?? In-Reply-To: References: <1113976729.450677.261130@o13g2000cwo.googlegroups.com> <87r7h5lk5a.fsf@wilson.rwth-aachen.de> <3cr2caF6locm6U1@individual.net> Message-ID: <3csdegF6p6jpnU1@individual.net> Roy Smith wrote: > import types > > class slicableDict (dict): > def __getitem__ (self, index): > if type (index) == types.SliceType: > d2 = slicableDict() > for key in self.keys(): > if key >= index.start and key < index.stop: > d2[key] = self[key] > return d2 > else: > return dict.__getitem__ (self, index) [...] > Roy-Smiths-Computer:play$ ./slice.py > {'oysters': 4, 'hen': 1, 'porpoises': 5, 'geese': 3, 'ducks': 2} > {'hen': 1, 'geese': 3, 'ducks': 2} > > I defined d[x:y] as returning a new dictionary which contains those items > from the original whose keys are in the range x <= key < y. I'm not sure > this is terribly useful but it's a neat demonstration of just how simple > Python makes it to do stuff like this. I can't imagine how much work it > would be to add a similar functionality to something like C++ multimap. Other possibility, probably faster when almost all keys in the range are in the dictionary: class sdict(dict): def __getitem__(self, index): if isinstance(index, slice): d = {} for key in xrange(slice.start, slice.stop, slice.step): if key in self: d[key] = self[key] return d else: return dict.__getitem__(self, index) Reinhold From facundobatista at gmail.com Fri Apr 1 11:21:48 2005 From: facundobatista at gmail.com (Facundo Batista) Date: Fri, 1 Apr 2005 13:21:48 -0300 Subject: Combining digit in a list to make an integer In-Reply-To: <1112354472.859466.273480@f14g2000cwb.googlegroups.com> References: <1112354472.859466.273480@f14g2000cwb.googlegroups.com> Message-ID: On 1 Apr 2005 03:21:12 -0800, Harlin Seritt wrote: > num1 = ['1', '4', '5'] > > How can I combine the elements in num1 to produce an integer 145? >>> num1 = ['1', '4', '5'] >>> int(''.join(num1)) 145 . Facundo Blog: http://www.taniquetil.com.ar/plog/ PyAr: http://www.python.org/ar/ From rphillips at engineer.co.summit.oh.us Wed Apr 27 07:43:25 2005 From: rphillips at engineer.co.summit.oh.us (paron) Date: 27 Apr 2005 04:43:25 -0700 Subject: Python, Perl & PDF files In-Reply-To: References: Message-ID: <1114602205.058191.315490@g14g2000cwa.googlegroups.com> Hopefully, Adobe will choose to support SVG as a response to Microsoft's "Metro", and take us all off the hook with respect to cracking open their proprietary format. From drjonfox at gmail.com Mon Apr 11 00:37:09 2005 From: drjonfox at gmail.com (drjonfox at gmail.com) Date: 10 Apr 2005 21:37:09 -0700 Subject: PIGIP Meeting -- Python Interest Group In Princeton Message-ID: <1113194229.477902.316460@f14g2000cwb.googlegroups.com> Python Interest Group In Princeton (PIGIP) PIG/IP will hold its fourth meeting on Tuesday April 12, 2005 at the Lawrenceville Library. Unfortunately, the Lawrenceville library has no free rooms at the usual 3rd Wednesday time. We will be reviewing more of the Python Tutorial (we last left off finishing the chapter about exceptions, so the next subject will be Classes) and then open discussion about Python will be encouraged. About PIGIP The Python Interest Group In Princeton is a Central New Jersey discussion and educational group for the Python computer language. PIGIP is a forum for open discussion about the Python computer language and source of exchange for people at different levels of learning about Python. Meetings are monthly (generally on the third Wednesday) and are open to the public. You can learn more about PIGIP at the http://www.pigip.org webpage. From stealthwang at gmail.com Sat Apr 9 02:35:57 2005 From: stealthwang at gmail.com (lotmr) Date: 8 Apr 2005 23:35:57 -0700 Subject: Python/wxPython Reducing memory usage. Message-ID: <1113028557.757987.146950@g14g2000cwa.googlegroups.com> I have previously posted a simple app I am working on, and while I love python and wxWindows, after checking the memory usage on such a simple app (system try application launcher) I see that it climbs to over 17mb! I have reduced all my imports to the bare workable minimum and that just gets it under 17mb. Is there any way that I could compile or optimize the my program and/or its memory usage? (Note: I don't have a problem with making this program win32 specific, as it already is only win32) CODE: #this section broken down soley for readability, normally one line from wxPython.wx import wxMessageDialog,wxFrame,wxMenu, wxBitmap,wxOK,wxID_ANY,wxID_EXIT,wxID_ABOUT, wxBITMAP_TYPE_ICO,wxBITMAP_TYPE_PNG,wxMenuItem, wxPySimpleApp,wxTaskBarIcon,wxIcon,EVT_TASKBAR_RIGHT_UP,EVT_MENU #end from os import startfile from sys import exit class MainWindow(wxFrame): def OnAbout (self, event): m = wxMessageDialog( self, " LUNCH Bar 0.1 \n" " A launch bar written in Python using wxWindows","About LUNCH", wxOK) m.ShowModal() m.Destroy def OnExit (self, event): self.tbi.Destroy() exit() def OnTrayRight (self, event): self.PopupMenu(self.rhtmenu) def OnLaunch (self, event): print event.GetString() path = 'D:\Program Files\Mozilla Firefox\Firefox.exe' startfile(path) def __init__(self,parent,id,title): wxID_FIREFOX = 1117 wxFrame.__init__(self,parent,wxID_ANY, title, size = ( 200,100)) self.tbi = wxTaskBarIcon() icon = wxIcon('package.ico',wxBITMAP_TYPE_ICO) self.tbi.SetIcon(icon, '') self.rhtmenu = wxMenu() icon = wxBitmap(name = 'ffico.png', type = wxBITMAP_TYPE_PNG) item = wxMenuItem(parentMenu = self.rhtmenu, id = wxID_FIREFOX, text='Firefox') item.SetBitmap(icon) self.rhtmenu.Append(wxID_EXIT, "&Exit"," Terminate this program") self.rhtmenu.Append(wxID_ABOUT, "&About"," Information about this program") self.rhtmenu.AppendSeparator() self.rhtmenu.AppendItem(item) EVT_TASKBAR_RIGHT_UP(self.tbi, self.OnTrayRight) EVT_MENU(self, wxID_ABOUT, self.OnAbout) EVT_MENU(self, wxID_EXIT, self.OnExit) EVT_MENU(self, wxID_FIREFOX, self.OnLaunch) appwin = wxPySimpleApp() frame = MainWindow(None, -1, "Small editor") appwin.MainLoop() From iker at research.att.com Wed Apr 27 16:05:21 2005 From: iker at research.att.com (Iker Arizmendi) Date: Wed, 27 Apr 2005 20:05:21 GMT Subject: Inheriting socket handles on Windows Message-ID: <426FF081.5020500@research.att.com> Hello all. I'm trying to get a server process to do the following on both Linux and Windows: 1) Create a socket and bind it to some port number. 2) Use spawnl to create other processes that will then listen and accept on that socket. On Linux I've managed to do that by using command line args to pass the FD number of the listening socket to the spawned processes. Eg: # SERVER # s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('', 9999)) s.listen(5) exe = "childscript" fds = str(s.fileno()) pid = os.spawnl(os.P_NOWAIT, exe, exe, fds)) print "process spawned" time.sleep(5) # CLIENT # where fds was received from the parent # fds = int(sys.argv[1]) s = socket.fromfd(fds, socket.AF_INET, socket.SOCK_STREAM) s.listen(5) print "child listening..." However, this fails on Windows as it doesn't have the fromfd function. Aren't WinSock handles inherited by default? And if so, is there some other way to perform a listen()/accept() in this case? Regards, Iker Arizmendi From bokr at oz.net Sat Apr 23 12:26:08 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 23 Apr 2005 16:26:08 GMT Subject: a=[ lambda t: t**n for n in range(4) ] References: <1114206105.666055.33720@g14g2000cwa.googlegroups.com> <1114208333.622909.179640@l41g2000cwc.googlegroups.com> <4269a0ea.275861307@news.oz.net> <1114227955.605994.162700@g14g2000cwa.googlegroups.com> Message-ID: <426a3d7a.315941870@news.oz.net> On 22 Apr 2005 20:45:55 -0700, "El Pitonero" wrote: >Bengt Richter wrote: >> I still don't know what you are asking for, but here is a toy, >> ... >> But why not spend some time with the tutorials, so have a few more >cards in your deck >> before you try to play for real? ;-) > >Communication problem. Indeed. > >All he wanted is automatic evaluation a la spreadsheet application. >Just like in Microsoft Excel. That's all. > >There are many ways for implementing the requested feature. Here are >two: > >(1) Push model: use event listeners. Register dependent quantities as >event listeners of independent quantities. When an independent quantity >is modified, fire off the event and update the dependent quantities. >Excel uses the push model. This is essentially what I was demonstrating with the namespace of FunArray, showing object attribute namespace access as perhaps _the_ 'listening" hook of Python -- which properties and overriding base class methods with subclass methods etc. etc. all depend on. FunArray 'listens' for named "spreadsheet cell" assignments to its namespace, and it "listens" for a repr access to the "spreadsheet" as a whole, presenting its status in terms of cell names and the formula value of the last cell entered. Not conventional, but I wanted to stay as close to the OP's proposed example interactive log (if that was what it was, which apparently it wasn't ;-) This does also demonstrate that if you want to "listen" for apparent assignments to bare names, AFAIK there is no way without byte code hackery or using a trace hook, or just doing your own eval-print loop, which is why I suggested the cmd module as a start. of course, you could mess with displayhook to get what the OP originally appeared to be asking for. E.g., this toy produces an interactive log much like the OP specified: >>> class DH(object): ... def __init__(self): ... import math ... self.env = vars(math) ... self.env.update(vars(__builtins__)) ... def evalstrex(self, s): ... for name in compile(s,'','eval').co_names: ... if type(self.env[name]) == str: ... self.env[name] = self.evalstrex(self.env[name]) ... return eval(s, self.env) ... def __call__(self, o): ... if type(o)==str: ... self.env.update(globals()) ... o = self.evalstrex(o) ... sys.__displayhook__(o) ... >>> import sys >>> sys.displayhook = DH() Other than the quotes around the formula, >>> a = '[sin(x), cos(x)]' >>> x=0.0 >>> a [0.0, 1.0] >>> x=1.0 >>> a [0.8414709848078965, 0.54030230586813977] looks a lot like """ I'm looking for array of functions. Something like a=[ sin(x) , cos(x) ] >>> x=0.0 >>> a [0, 1] >>> x=1.0 >>> a ... of course it can be made by >>> def cratearray(x): ... ~~~~ ... return a a=createarray(1.0) but this isn't what i am asking for. something automized. """ Of course, this is not what the OP _really_ wanted ;-) But it's kind of fun. Anything you type in quotes is evaluated using available global bindings plus the ones in the math module and __builtins__, and it's recursive, so if a name in the quoted formula refers to another string (which must be a valid expression), that is evaluated, and so on. This is "pull" based on interactive display trigger ;-) >>> x='pi/6' >>> a [0.49999999999999994, 0.86602540378443871] >>> x='pi/6' >>> a [0.49999999999999994, 0.86602540378443871] >>> x = 'pi/y' >>> y=6 >>> a [0.49999999999999994, 0.86602540378443871] >>> y=3 >>> a [0.8660254037844386, 0.50000000000000011] The display hook passes through non-strings, so you can box a string formula to see it: >>> [a] ['[sin(x), cos(x)]'] >>> [x] ['pi/y'] >>> [y] [3] You could specify your spread sheet: >>> a1,a2,a3=100,200,'sum([a1,a2])' >>> a1,a2,a3 (100, 200, 'sum([a1,a2])') >>> a1 100 >>> a2 200 >>> a3 300 ;-) > >(2) Pull model: lazy evaluation. Have some flag on whether an >independent quantity has been changed. When evaluating a dependent >quantity, survey its independent quantities recursively, and update the >cached copies whereever necessary. > >Of course, combination of the two approaches is possible. > >For Python, metaclasses and/or decorators and/or properties may help. > >But functional languages are a more natural territory. > Regards, Bengt Richter From aahz at pythoncraft.com Thu Apr 7 11:11:31 2005 From: aahz at pythoncraft.com (Aahz) Date: 7 Apr 2005 11:11:31 -0400 Subject: Lambda: the Ultimate Design Flaw References: Message-ID: In article , =?iso-8859-1?Q?Fran=E7ois?= Pinard wrote: >[Aahz] >> [Fran?ois] >>> >>>Many of us are using Python today, week after week, year long. So >>>let's be pragmatic. Python is what it became and now is. Let's not >>>define it as a memory from the past nor as a futuristic dream. >> >> You're free to continue using 1.5.2. [...] > >Sure, of course. Yet, our friendly argument is sliding away from was it >originally was. The point was about not asserting in this forum that >Python "has only one way to do it", because this is not true anymore. > >The principle has been, it may be back in some distant future, but now >it is not. You're conflating two different things: * Whether Python currently has only one way to do things * Whether Python has a design goal of only one way to do things I'll agree that Python currently has many examples of more than one way to do things (and even Python 3.0 won't remove every example, because anything more complicated than a Turing Machine has more than one way to do things). But I won't agree that Only One Way has been abandoned as a design principle. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "The joy of coding Python should be in seeing short, concise, readable classes that express a lot of action in a small amount of clear code -- not in reams of trivial code that bores the reader to death." --GvR From max2 at fisso.casa Tue Apr 5 13:30:47 2005 From: max2 at fisso.casa (max(01)*) Date: Tue, 05 Apr 2005 17:30:47 GMT Subject: redundant imports In-Reply-To: <86zmwgx0he.fsf@guru.mired.org> References: <86zmwgx0he.fsf@guru.mired.org> Message-ID: Mike Meyer wrote: > "max(01)*" writes: > > >>Peter Hansen wrote: >> >>>max(01)* wrote: >>> >>> >>>>hi everybody. >>>> >>>>suppose that code-1.py imports code-2.py and code-3.py (because it >>>>uses names from both), and that code-2.py imports code-3.py. >>>> >>>>if python were c, code-1.c should only *include* code-2.c, because >>>>the latter in turns includes code-3.c. >>>> >>>>inclusion of modules in c is a purely preprocessing textual matter >>>>(compilation is deferred to after the fact), i guess, so that such >>>>things are possible. import of modules in python is a different >>>>beast, so the "redundancy" is (i think) necessary. >>>> >>>>any comment/suggestion/idea? >>> >>>You're mixed up about this whole idea. >>> >> >>that's why i am asking for advice here. >>my concern was motivated by a (clumsy) attempt to understand the >>difference of mechanism between the approach to modular programming in >>a more "traditional" language (c) and python. > > > [Names changed to be valid python module names.] > > I feel I ought to point out that you don't really *have* to import the > code_3.py in code_1.py. You can get to things code_3.py in code_1.py > as code_2.code_3.. > oh. it never occured to me. interesting i must say... > The semantic behavior of "include" in C is the same as "from module > import *" in python. Both cases add all the names in the included > namespace directly to the including namespace. This usage is > depreciated in Python, because it leads to problems figuring out where > a specific variable came from. so 'import module' is to be preferred, right? > In C, it creates a problem called "name > space pollution". This is the case when a file1.c gets all the symbols > for some_header.h, even though it doesn't include/need those symbols, > because some header file1.c included needed a symbol from > some_header.h. This is especially galling if the pollution collides > with some_header2.h that file1.c actually needs. > > References: <1112680718.843606.126860@o13g2000cwo.googlegroups.com> <1113034010.742291.94360@o13g2000cwo.googlegroups.com> Message-ID: <1113119372.892637.134950@f14g2000cwb.googlegroups.com> can any GNU person or emacs coder answer this? specifically: why does what-cursor-position give incorrect answer. Xah xah at xahlee.org ? http://xahlee.org/PageTwo_dir/more.html ? Xah Lee wrote: > I found the problem now. (after some one hour debug time) Python > didn't have problem. Emacs does. > > If you open a file in emacs, it will open fine regardless whether the > EOL is ascii 10 or 13. (unix or mac) This is a nice feature. However, > the what-cursor-position which is used to show cursor position and the > char's ascii code, says the EOL is ascii 10 when it is in fact ascii > 13. Fuck the irresponsible fuckhead who is responsible for this. > > http://xahlee.org/UnixResource_dir/writ/responsible_license.html > > Xah > xah at xahlee.org > ? http://xahlee.org/ > > > > Xah Lee wrote: > > Why is that some of my files written out by > > outF.write(outtext.encode('utf-8')) > > has ascii 10 as EOL, while others has ascii 13 as EOL? > > both of these files's EOL are originally all ascii 10. > > > > If i remove the EOL after the tt below in the place string, then this > > doesn't happen. > > > > findreplace = [ > > (ur'', > > ur'''tt > > '''), > > ] > > > > ... > > > > inF = open(filePath,'rb') > > s=unicode(inF.read(),'utf-8') > > inF.close() > > > > for couple in findreplace: > > outtext=s.replace(couple[0],couple[1]) > > s=outtext > > outF = open(tempName,'wb') > > outF.write(outtext.encode('utf-8')) > > outF.close() > > > > thanks. > > > > Xah > > xah at xahlee.org > > ? http://xahlee.org/PageTwo_dir/more.html ? From nick.graham at ieee.org Tue Apr 12 19:01:22 2005 From: nick.graham at ieee.org (Nicholas S. Graham) Date: Tue, 12 Apr 2005 17:01:22 -0600 Subject: Image Module Message-ID: I want to convert a field of 4:2:2 digital video data into a viewable format (.jpg or something) using the Image module. Any suggestions?? NG From ivanlan at pauahtun.org Tue Apr 26 21:02:48 2005 From: ivanlan at pauahtun.org (Ivan Van Laningham) Date: Tue, 26 Apr 2005 19:02:48 -0600 Subject: Fwd: how to find the drive in python/cygwin? References: <1114540166.625601.50420@g14g2000cwa.googlegroups.com> <3511dc75050426113375a904e@mail.gmail.com> <426E9E0E.1020905@little-lisper.org> <3511dc7505042617524edd244a@mail.gmail.com> Message-ID: <426EE4B8.6910F6DD@pauahtun.org> Hi All-- Use win32api to find drives: ====cut here==== #!/usr/bin/python # -*- coding: utf-8 -*- import os import os.path import win32api import sys def findAllDrives(): Drives=[] print "Searching for drives..." drives=win32api.GetLogicalDriveStrings().split(":") for i in drives: dr=i[-1].lower() if dr.isalpha(): dr+=":\\" inf=None try: inf=win32api.GetVolumeInformation(dr) except: pass # Removable drive, not ready # You'll still get the drive letter, but inf will be None Drives.append([dr,inf]) return Drives if __name__=="__main__": drives=findAllDrives() for i in drives: print i[0],i[1] ====cut here==== Metta, Ivan ---------------------------------------------- Ivan Van Laningham God N Locomotive Works http://www.andi-holmes.com/ http://www.foretec.com/python/workshops/1998-11/proceedings.html Army Signal Corps: Cu Chi, Class of '70 Author: Teach Yourself Python in 24 Hours From codecraig at gmail.com Thu Apr 14 12:27:43 2005 From: codecraig at gmail.com (codecraig at gmail.com) Date: 14 Apr 2005 09:27:43 -0700 Subject: py2exe + XML-RPC problem Message-ID: <1113496062.959951.41150@l41g2000cwc.googlegroups.com> Hi, I tried to take the Monkey Shell script (http://www.sharp-ideas.net/archives/2005/03/monkey_shell_us.html) and make it into an executable. I am making an executable for the server piece (monkey_shelld.py). So my setup.py looks like this # setup.py from distutils.core import setup import py2exe import sys import xmlrpclib import os import string from SimpleXMLRPCServer import * from ConfigParser import * sys.argv.append("py2exe") setup(console=[{"script": 'monkey_shelld.py'}], data_files=["monkey_shell.conf"]) ...which i think is right. I imported the same imports as monkey_shelld.py uses (is that necessary??) And i execute it like... python setup.py py2exe Anyhow, i run the setup and get a monkey_shelld.exe. I can run the exe and the server runs just fine. Then I connect to the server using the client (monkey_shell.py), and when I execute a command, the client side prints out an error... xmlrpclib.ProtocolError: References: <1113934291.419258.314390@o13g2000cwo.googlegroups.com> Message-ID: <1113939785.827851.144980@l41g2000cwc.googlegroups.com> thanks for the replies. As for why I set my default encoding to utf-8 in python, I did it a while ago and I think I did it because when I was reading some strings from database in utf-8 it raised errors b/c there were some chars it could recongnize in standard encoding. When I made the change, the error didn't happen anymore. Does it make sense? -JF From fdreger at amiga.pl Thu Apr 28 19:20:45 2005 From: fdreger at amiga.pl (Filip Dreger) Date: Fri, 29 Apr 2005 01:20:45 +0200 Subject: why "import wx" doesn't work? References: <427126ca$1_3@rain.i-cable.com> <42715a8b$1_1@rain.i-cable.com> Message-ID: U?ytkownik "monkey" napisa? w wiadomo?ci news:42715a8b$1_1 at rain.i-cable.com... >> Which version of wxPython are you running? What do you mean by >> "does not >> work"...does the import fail or is your code giving errors? > > It is the current new version 2.6. The error message said that the > class > wxApp is not defined... This is very good! wxApp is never defined if you use "import wx". You must use "wx.wxApp" instead. If you import a module using "import anything", then all the names imported from the module must begin with "anything.". If you import wx using "import wx", then ALL the wx commands, classes and variables (all the names) MUST begin with 'wx.". Change them, and your program will work. "from wx import *" is a special shortcut, allowing you to use all the names without "wx.". If you change "from something import *" to "import something", your code will always break, this is normal. regards, Filip Dreger From deetsNOSPAM at web.de Sat Apr 23 11:47:16 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Sat, 23 Apr 2005 17:47:16 +0200 Subject: Python or PHP? References: <1114254894.512656.297040@l41g2000cwc.googlegroups.com> Message-ID: > php doesn't have any smell au contraire! I've seen many code smells in PHP. http://c2.com/cgi/wiki?CodeSmell -- Regards, Diez B. Roggisch From claudio.grondi at freenet.de Sat Apr 16 19:52:22 2005 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Sat, 16 Apr 2005 23:52:22 -0000 Subject: changing colors in python References: <1113511856.510914.103960@z14g2000cwz.googlegroups.com> Message-ID: <3cdfpnF6mjvphU1@individual.net> The readline module (used e.g. in IPython) http://sourceforge.net/project/showfiles.php?group_id=82407 provides the Console.py script and in my own version of it, the (extended) Console() class supports any ANSI escape sequences of the form ESC[#m and ESC[#,#m , making it possible to set any by console supported text and background colors. http://people.freenet.de/AiTI-IT/Python/Console.py Replace the Console.py of the readline module with my extended version and run it as main script to see the coloured output looking into the code to see how it comes. Claudio http://www.python.org/moin/ClaudioGrondi "GujuBoy" schrieb im Newsbeitrag news:1113511856.510914.103960 at z14g2000cwz.googlegroups.com... > i have a ansi.py file that i use in LINUX to change the text color to > STDOUT when i use the "print" function...but when i move this ansi.py > file over the windows...it does not work > > is there a version of ansi.py i can use for windows/linux.... > > please help > From fredrik at pythonware.com Mon Apr 4 04:23:20 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 4 Apr 2005 10:23:20 +0200 Subject: Change between Python 2.3 and 2.4 under WinXP References: Message-ID: Franz Steinh?usler wrote: > My second question from my last post (PyQt on Python 2.4), I think, is > a little got under (i have installed both Python 2.3 and Python 2.4) > > Is there any possibility under WinXP, to alterntate quickly > (with batch file or similary) between python23 and python24. if you want to deploy programs that depend on a specific python version, exemaker is your friend: http://effbot.org/zone/exemaker.htm From foo.bar at freesurf.ch.invalid Sat Apr 2 15:48:46 2005 From: foo.bar at freesurf.ch.invalid (Thomas Rast) Date: Sat, 02 Apr 2005 22:48:46 +0200 Subject: Name of IDLE on Linux References: Message-ID: <8764z4nbv5.fsf@thomas.local> Edward Diener writes: > It is a pity the Python Linux binary installations do not > create folders on the desktop or in the Gnome menu system with links > to the Python to the documentation and a readme telling me what > executables were installed. Imagine they did, and the other 1392 packages (on my system) too :-) Documentation usually resides in /usr/share/doc/, /usr/share/doc/packages/ or similiar. You're on an RPM-based system, so $ rpm -ql lists all files belonging to that package. You should have little trouble spotting the documentation files there. - Thomas -- If you want to reply by mail, substitute my first and last name for 'foo' and 'bar', respectively, and remove '.invalid'. From aubry at tls.cena.fr Tue Apr 26 07:28:04 2005 From: aubry at tls.cena.fr (Sebastien Aubry) Date: Tue, 26 Apr 2005 13:28:04 +0200 Subject: How to use a Tkinter widget inside a PyGtk or wxPython HMI? Message-ID: [This is the translation of a question issued on the fr.comp.lang.python newsgroup] Hello, I happen to use in my programs a widget based on Tkinter Canvas. It is Zinc (http://www.tkzinc.org), which allows to draw using transparency, gradients, translations, rotations, ... using OpenGL. However, this widget depends on Tkinter, whose look I find oldy, though I would like to try PyGtk or wxPython. I would like to know if there is a method for using a Tkinter widget inside a PyGtk or wxPython interface. I have already seeked some information about this: - in the same window: this seems impossible, but it might actually be possible! I have seen that with GTK and VTK (http://public.kitware.com/VTK), somebody has managed to solve such a problem (type "gtkvtkrenderwindow" in Google). - in different windows: the (not so smart) idea would be to have a main PyGtk window, and, in the foreground, a Tkinter window without decorations, only containing the Tkinter-dependant widget. The events (resize, close...) should, of course, be synchronized. If you have any hint, I would be happy to know more. Regards S?bastien Aubry From llothar at web.de Mon Apr 18 10:20:14 2005 From: llothar at web.de (Lothar Scholz) Date: 18 Apr 2005 07:20:14 -0700 Subject: Can't compile with --enable-shared on MacOSX Message-ID: <6ee58e07.0504180620.4b157ebf@posting.google.com> Help, i tried to generate a dynamic library from the official Python-2.4.0.tgz on MacOSX 10.3 but when i do the ./configure --enable-shared ; make ; sudo make install or ./configure --enable-shared=yes ; make ; sudo make install It links statically. It's also strange that i can't find a libpython2.4.a in my /usr/local/lib. It's not installed by the install command. Also /usr/local/bin/python24 works fine. I get an error that TK/TCL was not found. Is this the reason, i thought i can simply ignore this error message. From tjreedy at udel.edu Tue Apr 12 11:39:18 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 12 Apr 2005 11:39:18 -0400 Subject: Python 2.4 killing commercial Windows Python development ? References: <425a9869$0$38039$bed64819@news.gradwell.net><425aa0fb$0$38041$bed64819@news.gradwell.net><425AF2AB.1030401@v.loewis.de> <425b8948$0$38045$bed64819@news.gradwell.net> Message-ID: "Michael Kearns" wrote in message news:425b8948$0$38045$bed64819 at news.gradwell.net... >I understand this, and it's obviously a solution. Unfortunately it defeats >the whole point of me 'freezing' my code in the first place. >The main feature (for me) of the way I could use this, was to create a >simple Java launcher that didn't require the user to install anything >extra, or end up with a whole stack of unused data on their machine. I guess I don't understand some people's determination to not have users install fully useable Python on their Windows machines. Doing so seems no different to me than having to install (or upgrade) Shockwave, or Apple's Quicksomething for Windows (not used so much anymore), or RealPlayer, or the lastest upgrade for DirectX, or DivX, or a zip decoder, or any other 3rd party software, to run .xxx files or specialized .exe programs. (And I left out the most direct analogy of a java system.) In other words, it seems to me that most Windows users should be familiar with the idea of having to install a player or platform to run something built on top of that player or platform. Bundling a private Python interpreter with every Python script is much like bundling a private Shockwave player with every Schockwave script. I think most people would prefer having one copy of each. To put it another way, needing a Python interpreter to run .py files is no different from, for instance, needing a movie player to run .mpg files, and all Windows users are or need to become familiar with that general concept. Also, I think it a bit 'anti-social' to hide usage of Python. If all Python Windows programs ran with a normal, communally installed Python, then users would gradually get the idea that having Python installed is much like having Shockwave and other utility platforms installed, and that is is part of a 'fully loaded' Windows system to have a .py player installed. If there is something about the default install of Python on Windows that makes it less desireable or less easy than other platforms, then maybe that can be fixed. To make installation easier, maybe someone could write a small .exe that could be frozen with scripts or run with installers and that would detect the presence/absence of the needed Python version and offer an auto download and install if needed. At least one thing in Python's favor is the lack of having to 'register' before downloading (or after installation) and the ability to redistribute the installer free and without special license. Terry J. Reedy From steve at holdenweb.com Wed Apr 13 12:07:02 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 13 Apr 2005 12:07:02 -0400 Subject: Codig style: " or """ In-Reply-To: <20050413151321.791.qmail@web61109.mail.yahoo.com> References: <20050413151321.791.qmail@web61109.mail.yahoo.com> Message-ID: Sara Khalatbari wrote: > Hi! > > Suppose you're writing a module & writing the > definition of each function in that module in " or > """. > for example: > a) "This function does this & that" > or: > b) """This function does blah blah blah""" > > What are the differences between " and """ ? > I'm using gedit & I wanna know a bit about coding > style. > Generally speaking """ ... """ is reserbed for multiline string constats and those whihc need to contain both single and double quotes - such as """Python's quotes are "'" and '"'""" or """\ This is a multiline string that has one newline in it.""" [Note that there is no starting newline in the second example, as I escaped it off with the \]. > To be very honest: I have a very strict boss who looks > for bugs in my codes & he insists to know exactly > which 'CODING STYLE AUTHORITATIVE SOURCE' I've based > my coding style on when using " or """. > > Can anybody out there give me some hint? > Can anybody tell me where to find a document on python > coding style. > > tnx, > Sara > Sara: Show your boss http://python.org/peps/pep-0008.html Be sure he understands that you are not responsible for the title :-) regards Steve -- Steve Holden +1 703 861 4237 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ From abpillai at gmail.com Wed Apr 6 14:26:10 2005 From: abpillai at gmail.com (Anand) Date: 6 Apr 2005 11:26:10 -0700 Subject: Harvestman install not working In-Reply-To: References: Message-ID: <1112811970.231676.122830@g14g2000cwa.googlegroups.com> Hi Latest version of py2exe does not support the option --force-imports anymore I think. You can edit the .bat file to remove that option. It should work. -Anand From fernandomirandamuro at gmail.com Wed Apr 13 14:58:12 2005 From: fernandomirandamuro at gmail.com (Fernando) Date: 13 Apr 2005 11:58:12 -0700 Subject: are DLLs needed to run glade interfaces in python with Windows? Message-ID: <9cac1d03.0504131058.451438a6@posting.google.com> Hi, I've a .glade file with a little interface I made. I've managed to load it from a python script, using pyGTK, but the only way it succeed was copying into the same directory the "libxml2.dll" and "libglade-2.0.0.dll" files. I think you only need to install theese as packages in Linux, but I'm using Windows and I'm wondering if this is a must using it, or if there are ways much cleaner that simply start dropping DLLs inside the directory... Thanks. From fabio.pliger at siavr.it Sat Apr 30 03:19:03 2005 From: fabio.pliger at siavr.it (Fabio Pliger) Date: Sat, 30 Apr 2005 07:19:03 GMT Subject: [wxPython] Many wxPanel forms in 1 wxFrame References: Message-ID: "CYBER" ha scritto nel messaggio news:d4uo3o$1ee4$1 at node3.news.atman.pl... > Is this possible to create 1 wxFrame and > register more than 1 wxPanel in it. > And select the one you want to show at the moment ? > > I'm trying to implement a multistep wizard under wxPython. > I need to be able to hide and show windows inside my > frame. > > Help :) > Take a look at the wx documentation about wizards... There is a good example about doing wizards! F.P. From grante at visi.com Sun Apr 24 22:03:27 2005 From: grante at visi.com (Grant Edwards) Date: Mon, 25 Apr 2005 02:03:27 -0000 Subject: Is this a bug? References: <426bb3e9$0$83084$ed2619ec@ptn-nntp-reader01.plus.net> <116nfblc10i9340@corp.supernews.com> Message-ID: <116ojvf473dc16b@corp.supernews.com> On 2005-04-25, Terry Reedy wrote: >> According to the language reference, >> >> An augmented assignment expression like x += 1 can be >> rewritten as x = x + 1 to achieve a similar, but not >> exactly equal effect. In the augmented version, x is only >> evaluated once. >> >> I don't consider the two results you posted "similar". > > It continues > "Also, when possible, the actual operation is performed in-place, meaning > that rather than creating a new object and assigning that to the target, > the old object is modified instead. ...Similarly, with the exception of the > possible in-place behavior, the binary operation performed by augmented > assignment is the same as the normal binary operations. > " > I take the behavior observed to be the exceptional in-place behavior > referred to. I certainly don't see how. Strings are immutable. The old object can't be modified in-place, so the "in-place" behavior is moot. In any case, the only difference is supposed to be whether a new object is created or an existing object is modified. The two results shouldn't be completely different as shown by the OP. Your quote states quite clearly that the binary operation *is the same* whether it's spelt a = a + b or a += b. That is simply not true for the example we're discussing. > But this could certainly be clearer. I don't see how that statement has anything to do with the bug at hand. -- Grant Edwards grante Yow! Oh my GOD -- the at SUN just fell into YANKEE visi.com STADIUM!! From deetsNOSPAM at web.de Mon Apr 18 19:08:29 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Tue, 19 Apr 2005 01:08:29 +0200 Subject: def a((b,c,d),e): References: <1113854757.229118.137260@g14g2000cwa.googlegroups.com> <1113862997.242449.12330@l41g2000cwc.googlegroups.com> Message-ID: AdSR wrote: >> Yes, but usually not so much in function arguments but more in >> list-comprehensions or other places where unpacking was useful. I > love the >> feature - I just don't have nested enough data to use it more :) > > I use tuple unpacking in its typical uses, it's one of the first > language features I learned about. Somehow it never occurred to me that > you could use it in function arguments this way - I only knew f(*args, > **kwargs) style in this context. That's what I made the whole fuss > about... Well, if you think about it the whole positional argument passing is nothing more than tuple unpacking. Its like having an anonymous variable that gets unpacked: def foo(a,b,c = i_m_so_anonymous): pass So it's just orthogonal to have the full functionality of unpacking available for function arguments - including the nested tuples. -- Regards, Diez B. Roggisch From martin at v.loewis.de Sat Apr 9 07:22:45 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 09 Apr 2005 13:22:45 +0200 Subject: changing from python2.3 to python2.4 In-Reply-To: References: Message-ID: <4257bb06$0$31529$9b622d9e@news.freenet.de> Uwe Mayer wrote: > How do you suggest dealing with this: > - is calling /usr/bin/python2.3 in the bang-line problematic? > - installing into both python2.3 and python2.4 > - rebuilding (re- ./configure, make, make install) the app solves the > problem > > Whats the usual way to deal with this? People normally often install multiple versions of Python on a machine if they need to support many different Python applications. They then migrate one application after another to the new Python version, and eventually uninstall the old version. Putting python2.3 in the bang line should work fine, so if you can arrange to find all scripts that need to be changed, that might be the easiest solution. For rebuilding, you probably would need to do some testing whether everything still works fine; if it does, this is likely what you will do in the long run either way - at some point, on a new machine, it will be easier to recompile your application than installing python2.3 from sources. Regards, Martin From kay.schluehr at gmx.net Mon Apr 18 01:07:39 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 17 Apr 2005 22:07:39 -0700 Subject: pre-PEP: Suite-Based Keywords - syntax proposal References: <1113720183.913168.184770@f14g2000cwb.googlegroups.com> <42621c83.157344138@news.oz.net> <1113755254.226237.138550@z14g2000cwz.googlegroups.com> Message-ID: <1113800859.317109.27720@f14g2000cwb.googlegroups.com> Steven Bethard wrote: > So the object of a "where" is then always an ordered dict? Yes. > If so, then > I guess I like this proposal best so far. > > However, it does seem to have the problem that you can't have any > additional local variables so, for example, list comprehensions are > probably not usable... > > Or can you still drop the argument to "where" and just use the names > directly? E.g.: > > x = property(fget=fget, doc=doc) where: > doc = "I'm the 'x' property." > def fget(self): > return self.__x I can't see why this shouldn't work? The specifiers behind "where" are present to determine the matching behaviour. The order of a dict is caused by different specifiers i.e. a dict- or tuple-like specifier. If a specifier is not present only names can be matched regardless of a sequence and this is always possible because we still have a dict with names as keys. What should not be possible are statements like this: x = property(a, b) where: doc = "I'm the 'x' property." def fget(self): return self.__x because there is no rule to match doc and fget onto a and b. In this case we would need specifiers: x = property(a, b) where **a: doc = "I'm the 'x' property." where **b: def fget(self): return self.__x Ciao, Kay From fredrik at pythonware.com Tue Apr 5 11:19:46 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 5 Apr 2005 17:19:46 +0200 Subject: re module non-greedy matches broken References: <115040egk00tf9d@corp.supernews.com> <11535p0mdgqde1@corp.supernews.com> Message-ID: "lothar" wrote: > with respect to the documentation, the module is broken. nope. > the module does not necessarily deliver a "minimal length" match for a > non-greedy pattern. it isn't supposed to: a regular expression describes a *set* of matching strings, and the engine is free to return any string from that set. Python's engine returns the *first* string it finds that belongs to the set. if you use a non-greedy operator, the engine will return the first non-greedy match it finds, not the overall shortest non-greedy match. if you don't want to understand how regular expressions work, don't use them. From ola.natvig at infosense.no Wed Apr 6 05:04:35 2005 From: ola.natvig at infosense.no (Ola Natvig) Date: Wed, 06 Apr 2005 11:04:35 +0200 Subject: Does IronPython indicate MS interest in dynamic languages? In-Reply-To: <42539aa9.438452150@news.oz.net> References: <1111603770.909447.18070@z14g2000cwz.googlegroups.com> <1f7befae05040512422ef693d4@mail.gmail.com> <42539aa9.438452150@news.oz.net> Message-ID: <3alci2-rr1.ln1@pluto.i.infosense.no> Bengt Richter wrote: > > If there is to be an MSPython, how long 'til Mozilla FirePython? ;-) > > Regards, > Bengt Richter 'Reclaim your runtime' I can't wait... -- -------------------------------------- Ola Natvig infoSense AS / development From fallon at das.com Fri Apr 29 12:06:03 2005 From: fallon at das.com (AKA) Date: Fri, 29 Apr 2005 16:06:03 GMT Subject: Ron Grossi: God is not a man References: <1114098221.580669.86300@g14g2000cwa.googlegroups.com> <1114127633.859113.292290@l41g2000cwc.googlegroups.com> <#2tJ0r3RFHA.3664@TK2MSFTNGP15.phx.gbl> <1114328806.147822.64660@z14g2000cwz.googlegroups.com> <1114329202.229148.82550@o13g2000cwo.googlegroups.com> <1114654290.690332.155200@f14g2000cwb.googlegroups.com> <3dc8hjF6s5i2uU1@individual.net> <3desu2F6qoj7aU1@individual.net> <#ATbpqMTFHA.3980@TK2MSFTNGP12.phx.gbl> Message-ID: "Donald L McDaniel" wrote in message news:%23ATbpqMTFHA.3980 at TK2MSFTNGP12.phx.gbl... > MC05 wrote: >> "sheltech" wrote in message >> news:FEpce.1407$7F4.136 at newsread2.news.atl.earthlink.net... >>> >>> "MC05" wrote in message >>> news:3dc8hjF6s5i2uU1 at individual.net... >>>> >>>> "Donald L McDaniel" wrote in message >>>> news:ueXTQC8SFHA.3184 at TK2MSFTNGP15.phx.gbl... >>>>> >>>>> 4) I doubt seriously whether God plays a guitar, since guitars are >>>>> made by men, for men. His Son could theoretically play a guitar. >>>>> Perhaps He does. Perhaps He doesn't. Only the Father and His Holy >>>>> Angels know. >>>> >>>> So then Lucifer was a wicked bass player whose sex and drugs and >>>> rock n roll alientated the rest of the band and was fired? >>>> >>>> >>>> >>> >>> "Fired" .... good one >> >> Heh. Can't take credit for an accident. Your eye is better than >> mine. :) > > The Devil has been fired...by God Himself. Read the Book of Revelation in > the New Testament: Satan's end is clearly outlined by the Angel Jesus > sent to St. John. This end is very clear: he will be cast alive into the > Lake which burns with fire and brimstone, where he will be tormented day > and night forever. > > Not only Satan and his angels will be cast into the Lake, but all those > who follow him and his servants. I assure you, Satan won't be ruling > anyone in the Fire. He will be in just as much torment as his followers. > Neither will he have any sort of job. > > I strongly advise you to stop making fun of things you have no > understanding of. Your eternal destiny depends on the way you treat > others. > > -- > Donald L McDaniel > Please reply to the original thread, > so that the thread may be kept intact. > ============================== > Just imagine if you actually had a coherent thought. From rbt at athop1.ath.vt.edu Tue Apr 5 16:51:09 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Tue, 05 Apr 2005 16:51:09 -0400 Subject: Add System Path?!? In-Reply-To: References: Message-ID: andrea_gavana at tin.it wrote: > Hello NG, > > I have a GUI (written in wxPython) that calls some external exe files. > Some of them requires that I add to the PATH variable 1 directory. Basically, > the exe are located in: > > /MyApp/Solvers/FirstExe > /MyApp/Solvers/SecondExe > > And so on, while the dll needed by these exe are located in: > > /MyApp/MyDll > > These exe files do not work if I don't set the PATH variable also to that > adress. I know I can do it by hand (and also my users can), but I wonder > if there is a way to do it in Python... > > Thank you for all suggestions/pointers. > > Andrea. > > Check out the 'Path' value under this registry key: "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" You can import _winreg to edit it as you like. I think it's a string... just append your path(s) to them. rbt From rkern at ucsd.edu Tue Apr 12 15:46:20 2005 From: rkern at ucsd.edu (Robert Kern) Date: Tue, 12 Apr 2005 12:46:20 -0700 Subject: chaco and wx 2.5.... In-Reply-To: References: Message-ID: Fabio Pliger wrote: > anyone know if it's possibile to run chaco with wx 2.5.3 or grater? No, not at this time. Enthought expects that they will have some "conversion days" around summertime to move their codebase to the soon-to-be-released wxPython 2.6. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From steve at holdenweb.com Fri Apr 8 01:46:17 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 08 Apr 2005 01:46:17 -0400 Subject: [JIM_SPAM] Microsoft supporting a .NET version of Python... In-Reply-To: <42560469.8000104@msn.com> References: <42560469.8000104@msn.com> Message-ID: <42561AA9.2040601@holdenweb.com> Jim Hargrave wrote: > http://www.gotdotnet.com/workspaces/workspace.aspx?id=ad7acff7-ab1e-4bcb-99c0-57ac5a3a9742 > You really shoud try and get out more: http://www.pycon.org/dc2005/talks/keynote regards Steve -- Steve Holden +1 703 861 4237 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ From bill.mill at gmail.com Tue Apr 5 10:51:14 2005 From: bill.mill at gmail.com (Bill Mill) Date: Tue, 5 Apr 2005 10:51:14 -0400 Subject: change extensions In-Reply-To: <001a01c539ed$dfc550d0$d502a8c0@JEFF> References: <001a01c539ed$dfc550d0$d502a8c0@JEFF> Message-ID: <797fe3d405040507517d998772@mail.gmail.com> On Apr 5, 2005 10:43 AM, Jeffrey Maitland wrote: > That approach works, but so does this one. > > import os, glob > > input_file_list = glob.glob('*.txt') > for in_file in input_file_list: > name = in_file.split('.') > os.rename(in_file, str(name[0]) + '.' + 'text')) > you should really use in_file.splitext - your script renames myfile.with.lots.of.dots.txt to myfile.text instead of myfile.with.lots.of.dots.text . If you *really* wanted to use split(), it oughta be ''.join(in_file.split('.')[:-1]) , but why not use the built-in? Peace Bill Mill bill.mill at gmail.com From bokr at oz.net Tue Apr 5 08:36:44 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 05 Apr 2005 12:36:44 GMT Subject: Decorator Base Class: Needs improvement. References: <0v4351l5v1f3i9h3fssvcfklifkdlhjv7o@4ax.com> <43d351pq3qmlr8vlealdj818p8mt61p1ps@4ax.com> <1112687665.297515.231430@o13g2000cwo.googlegroups.com> Message-ID: <42526c32.357421755@news.oz.net> On 5 Apr 2005 00:54:25 -0700, "Kay Schluehr" wrote: >Steve Holden wrote: > >> You have several times mentioned the possibility of a decorator >taking >> more than one argument, but in my understanding of decorators this >just >> wouldn't make sense. A decorator should (shouldn't it) take precisely > >> one argument (a function or a method) and return precisely one value >(a >> decorated function or method). > I agree from an English language point of view. I.e., a verber is something that does the verbing, so a decorator ought to be the thing that does the decorating, which is the function/callable(s) resulting on stack from the evaluation of the @-line. In the case of a single @deco name, the evaluation is trivial, and the difference between the @-expression and the resulting callable might be overlooked. Full-fledged general expressions after the '@' are for some reason disallowed, but it is handy to allow attribute access and calling in the syntax, so the relevant Grammar rules are: >From the 2.4 Grammar, the key part seems to be decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE decorators: decorator+ funcdef: [decorators] 'def' NAME parameters ':' suite and further on dotted_name: NAME ('.' NAME)* So the Python Grammar's name for the @-expression is just plain "decorator" which conflicts with my English-based reading of the word ;-/ So it appears the intent is to call the entire @-line the "decorator" and I guess to have a name for what evaluating the @-line returns on the stack, we could call it the "decorating callable" since it is what takes the function parameter as its first parameter and decorates the function and returns the decorated function. But I don't like it, English-wise. I would rather call the @-line the "decorator expression" and what it evaluates to the "decorator." Can we change the grammar with s/decorator/decorator_expr/ ? >Yes. I think this sould be fixed into the minds of the people exacly >this way You state it: I think we may be agreeing in principle but with different words ;-) > >When writing > >@decorator(x,y) >def f(): > .... > >not the so called "decorator" function but decorator(x,y) is the ^--(the result of evaluating) >decorating function and decorator(x,y) is nothing but a callable object ^--(the result of evaluating) >that takes f as parameter. A little correcture of Your statement: it is >NOT nessacary that a function or method will be returned from a >decorator. Yes, in fact it could even perversely be colluding with a known succeeding decorator callable to pass info strangely, doing strange things, e.g., >>> trick = ['spam', 'eggs'] >>> def choose_name(tup): ... nx, f = tup ... f.func_name = trick[nx] ... return f ... >>> def namedeco(nx=1): ... return lambda f, nx=nx:(nx, f) ... >>> @choose_name ... @namedeco() ... def foo(): pass ... >>> foo >>> @choose_name ... @namedeco(0) ... def foo(): pass ... >>> foo I.e., namedeco evaluates to the lambda as decorator function, and that passes a perverse (nx, f) tuple on to choose_name, instead of a normal f. > >def decorator(x,y): > def inner(func): > return x+y > return inner > >@decorator(1,2) >def f():pass > >>>> f >3 > >This is perfectly valid allthough not very usefull ;) > Perhaps even less useful, the final decorator can return something arbitrary, as only the name in the def matters at that point in the execution (as a binding target name), so: >>> def dumbdeco(f): return 'something dumb' ... >>> @dumbdeco ... def foo(): pass ... >>> foo 'something dumb' Hm, maybe some use ... >>> def keydeco(name): ... return lambda f: (name, f) ... >>> @keydeco('pooh_foo') ... def foo(): pass ... >>> @keydeco('tigger_bar') ... def bar(): pass ... >>> dict([foo, bar]) {'pooh_foo': , 'tigger_bar': } ... nah ;-) Anyway, I think a different name for what comes after the "@" and the callable that that (very limited) expression is supposed to return would clarify things. My conceptual model is @decorator_expression # => decorator def decorating_target(...): ... Regards, Bengt Richter From gsakkis at rutgers.edu Wed Apr 27 20:07:08 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 27 Apr 2005 17:07:08 -0700 Subject: =?iso-8859-1?q?Re=3A_Good_morning_or_good_evening_depending_upon?= =?iso-8859-1?q?_your_location=2E_I_want_to_ask_you_the_most_import?= =?iso-8859-1?q?ant_question_of_your_life=2E_Your_joy_or_sorrow_for?= =?iso-8859-1?q?_all_eternity_depends_upon_your_answer=2E_The_quest?= =?iso-8859-1?q?ion_is=3A_Are_you_saved=3F_It_is_not_a_question_of_?= =?iso-8859-1?q?how_good_you_are=2C_nor_if_you_are_a_church_member?= =?iso-8859-1?q?=2C_but_are_you_saved=3F_Are_you_sure_you_will_go_t?= =?iso-8859-1?q?o_Heaven_when_you_die=3F_GOOGLE=B7NEWSGROUP=B7POST?= =?iso-8859-1?q?=B7151?= In-Reply-To: <1114640110.171596.223260@g14g2000cwa.googlegroups.com> References: <1114640110.171596.223260@g14g2000cwa.googlegroups.com> Message-ID: <1114646828.777860.117470@o13g2000cwo.googlegroups.com> wrote in message news:2g8071h8e3np64c0tccf8053torm33p8te at 4ax.com... > Reports to groups-abuse at google.com, abuse at aol.net, domains at aol.net, > abuse at yahoo.com, abuse at yahoo-inc.com > > And do not feed the troll! I'm afraid he's not a troll. He's just a lame spammer, doesn't need feeding to survive... In any case, the hell with :-/ From poisondart985 at gmail.com Thu Apr 28 02:32:15 2005 From: poisondart985 at gmail.com (poisondart) Date: 27 Apr 2005 23:32:15 -0700 Subject: dynamically generating temporary files through python/cgi Message-ID: <1114669935.274048.63940@z14g2000cwz.googlegroups.com> Is there a way to dynamically generate temporary files (such as an html, xml or text file) in Python? I'm not sure if I'm explaining myself clearly as I've no clue how to describe this mechanism. I've seen it on certain websites that will generate a file under certain parameters (through forms) that will dissapear (i.e. delete itself) after a specified amount of time. These files usually have some phony string for their filenames...like it's been md5 hashed or something. Is there a group of library functions that allow this? I imagine that if i manually go and allocate a bunch of timers to monitor files, it would be really expensive in load. Or perhaps is this a client-side mechanism? Thanks, - poisondart From steve at holdenweb.com Tue Apr 5 10:51:40 2005 From: steve at holdenweb.com (Steve Holden) Date: Tue, 05 Apr 2005 10:51:40 -0400 Subject: Python & MySQL In-Reply-To: <1112711966.414550.38680@z14g2000cwz.googlegroups.com> References: <1112711966.414550.38680@z14g2000cwz.googlegroups.com> Message-ID: <4252A5FC.3030000@holdenweb.com> jason.massey at gmail.com wrote: > Hi all, > > I've got a weird problem. I was running Python 2.3 and MySQLdb and had > everything running fine. > > Cutting to the chase: After upgrading to 2.4 (and latest modules) the > MySQLdb functions in Python can connect to the database, do queries and > do inserts. > > Or rather, it seems to do inserts. If I just run in the Python command > line and manually connect to the database and do an insert and then a > query on what I just inserted the info is there. > > However when I use SQLyog to look at the database the info isn't there. > When I close down Python, restart, reconnect and query the info isn't > there. > > Info inserted from SQLyog is persistant. > > Has anyone had any problems like this before? > > thanks, > > jason > I suspect you are forgetting to commit your changes to the database, so they are being rolled back when you close your connection. regards Steve -- Steve Holden +1 703 861 4237 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ From greg at cosc.canterbury.ac.nz Thu Apr 7 06:45:05 2005 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Thu, 07 Apr 2005 22:45:05 +1200 Subject: Calling a Perl Module from Python ( future direction of Python) In-Reply-To: <3bkgsvF6d50ppU2@individual.net> References: <3bkgsvF6d50ppU2@individual.net> Message-ID: <3bkh9tF6d50ppU3@individual.net> By the way, is the Parrot project still alive, or has it been given up on? Not that I actually want it, but the idea is kind of morbidly fascinating. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From cookedm+news at physics.mcmaster.ca Mon Apr 4 20:27:23 2005 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Mon, 04 Apr 2005 20:27:23 -0400 Subject: Gnuplot.py and, _by far_, the weirdest thing I've ever seen on my computer References: <1112649790.752371.98360@g14g2000cwa.googlegroups.com> Message-ID: "syd" writes: > I don't even know where to begin. This is just bizarre. I just picked > up the Gnuplot.py module (a light interface to gnuplot commands) and > was messing around with it today. > > I've got a tiny script, but it only works from the command line about > half the time! In the python interpreter, 100%. Ipython, 100%. I'm > not kidding. > > #!/bin/env python > import Gnuplot > g = Gnuplot.Gnuplot(debug=1) > g.title('A simple example') > g('set data style linespoints') > g('set terminal png small color') > g('set output "myGraph.png"') > g.plot([[0,1.1], [1,5.8], [2,3.3], [3,100]]) > > Here's just one example -- it does not work, then it works. It seems > totally random. It will work a few times, then it won't for a few > times... > > bash-2.05b$ ./myGnu.py > gnuplot> set title "A simple example" > gnuplot> set data style linespoints > gnuplot> set terminal png small color > gnuplot> set output "myGraph.png" > gnuplot> plot '/tmp/tmp5LXAow' notitle > > gnuplot> plot '/tmp/tmp5LXAow' notitle > ^ > can't read data file "/tmp/tmp5LXAow" > line 0: util.c: No such file or directory > > bash-2.05b$ ./myGnu.py > gnuplot> set title "A simple example" > gnuplot> set data style linespoints > gnuplot> set terminal png small color > gnuplot> set output "myGraph.png" > gnuplot> plot '/tmp/tmpHMTkpL' notitle > > (and it makes the graph image just fine) > > I mean what the hell is going on? My permissions on /tmp are wide open > (drwxrwxrwt). It does the same thing when I run as root. And it > _always_ works when I use the interpreter or interactive python. > > Any clues would be greatly appreciated. I'm baffled. What's your OS? Python version? Gnuplot.py version (I assume 1.7)? Put a 'import sys; print sys.version' in there to make sure /bin/env is using the same python as you expect it to. It looks like any temporary file it's writing to is deleted too early. Have a look at gp_unix.py in the Gnuplot source. There's some customization options that might be helpful. In particular, I'd try import Gnuplot Gnuplot.GnuplotOpts.prefer_fifo_data = 0 ... then the data will be save to a temporary file instead of piped through a fifo. Alternatively, try Gnuplot.GnuplotOpts.prefer_inline_data = 1 ... then no file will be used. [I don't use Gnuplot myself; this is just what I came up with after a few minutes of looking at it] -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From roy at panix.com Tue Apr 19 08:18:30 2005 From: roy at panix.com (Roy Smith) Date: Tue, 19 Apr 2005 08:18:30 -0400 Subject: Why does python class have not private methods? Will this never changed? References: <311b5ce105041902165a0969a0@mail.gmail.com> Message-ID: In article , Simon Brunning wrote: > On 4/19/05, could ildg wrote: > > Python is an oop language, > > Yes. > > > Private stuff always makes programming much easier. > > That contention is, at best, debatable. See > http://groups-beta.google.com/group/comp.lang.python/msg/b977ed1312e10b21. Nice essay. Now, for another look at the same issue... http://thedailywtf.com/forums/32534/ShowPost.aspx From programmer.py at gmail.com Tue Apr 19 09:42:16 2005 From: programmer.py at gmail.com (Jaime Wyant) Date: Tue, 19 Apr 2005 08:42:16 -0500 Subject: Why does python class have not private methods? Will this never changed? In-Reply-To: References: <311b5ce105041902165a0969a0@mail.gmail.com> Message-ID: Have I missed something? Doesn't this mangle class methods: class Foo: def __bar(self): print "bar" Granted, you could probably figure out how the names are being mangled. In the example above __bar is a defacto private method. Griping about it not having `private' in front of it is asinine. If someone intentionally has to call a `private' method, then the design is at fault, not the language. jw On 4/19/05, Peter Hansen wrote: > Roy Smith wrote: > > Simon Brunning wrote: > >>On 4/19/05, could ildg wrote: > >>>Private stuff always makes programming much easier. > >> > >>That contention is, at best, debatable. See > >>http://groups-beta.google.com/group/comp.lang.python/msg/b977ed1312e10b21. > > > > Nice essay. Now, for another look at the same issue... > > http://thedailywtf.com/forums/32534/ShowPost.aspx > > Where in the original posting or in the 86 replies > in that massive page are we supposed to find something > pointed about this issue? > > Also, do any of the people there use a language like > Python, or are you merely pointing to one example in > another language (Java) where, perhaps, "private" > should have been used? > > Or does this actually back up Simon's point? You > don't say and it's really unclear what your point is. > > -Peter > -- > http://mail.python.org/mailman/listinfo/python-list > From mwm at mired.org Tue Apr 26 03:12:07 2005 From: mwm at mired.org (Mike Meyer) Date: Tue, 26 Apr 2005 02:12:07 -0500 Subject: What's do list comprehensions do that generator expressions don't? References: <86ll77pgqz.fsf@guru.mired.org> <426ddda7.553554359@news.oz.net> Message-ID: <861x8ynha0.fsf@guru.mired.org> bokr at oz.net (Bengt Richter) writes: > On Mon, 25 Apr 2005 16:48:46 -0400, Bill Mill wrote: >>+1 . I think that we should still have the form [genexp] , but without >>the dangling variable, and implemented with generator expressions. It >>seems to me that it is inconsistent if I can do list(genexp) but not >>[genexp] , since they are so similar. Once that happens, we can tell >>people who ask the OP's question that [genexp] is just another way to >>spell list(genexp), and he should use it if he wants the entire list >>constructed in memory. > ISTM you have to account for > > >>> def foo(g): return g > ... > >>> foo(123) > 123 > >>> foo(c for c in 'abc') > > >>> [(c for c in 'abc')] > [] > >>> [c for c in 'abc'] > ['a', 'b', 'c'] Right. But that shouldn't be hard to do. Let genexp stand for a a generator expression/list comprehension without any brackets on it at all. Then [genexp] is the syntax to expand the list. [(genexp)] is the syntax to create a list of one element - a generator object. foo(genexp) will do the right thing. The question under these circumstances is then: do you want bare genexp to mean something? Right now, it's a syntax error. But there's no reason you couldn't have: y = x for x in stuff assign a generator object to y. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From fredrik at pythonware.com Thu Apr 21 16:24:03 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 21 Apr 2005 22:24:03 +0200 Subject: New line References: <42680a8a_1@mk-nntp-2.news.uk.tiscali.com> Message-ID: "ionic" wrote: > This is probably going to sound very dull but, how do you get to the next > line after youve finished typing the first line? > > Thanks in advance if you don't know how to get a new line, how did you write that message? From timo.linna at gmail.com Thu Apr 7 12:39:14 2005 From: timo.linna at gmail.com (Timo) Date: 7 Apr 2005 09:39:14 -0700 Subject: Erroneous line number error in Py2.4.1 [Windows 2000+SP3] References: <1112794029.667294.134370@f14g2000cwb.googlegroups.com> <425447A2.2070508@v.loewis.de> Message-ID: <1112891954.804992.113670@z14g2000cwz.googlegroups.com> Martin v. L?wis wrote: > Timo wrote: > > Does anyone have a clue what is going on? > > No. Please make a bug report to sf.net/projects/python. > Done: http://sourceforge.net/tracker/index.php?func=detail&aid=1178484&group_id=5470&atid=105470 BR, Timo From spam4bsimons at yahoo.ca Sun Apr 3 19:21:10 2005 From: spam4bsimons at yahoo.ca (Brendan) Date: 3 Apr 2005 16:21:10 -0700 Subject: Help me dig my way out of nested scoping References: <1112562768.181026.180140@l41g2000cwc.googlegroups.com> Message-ID: <1112570470.560599.223390@f14g2000cwb.googlegroups.com> Thanks for the tips. Making FW a callable class (choice 5) seems to be a good (if verbose) solution. I might just wrap my temporary values in a list [lastX, lastA, lastB] and mutate them as Michael suggests. Thanks to Michael especially for the explanation of the name-binding process that's at the heart of the issue. The other choicess are not as helpful to me for the following reasons: choice 1: I don't want the temporary values of lastA and lastB to be global variables in my case as they are great big numeric arrays, and I'd like their memory to be reclaimed after FW is done. choice 2: I tried this without success. Using Micheal's example, I would assume you mean something like this: def outer(): b = 1 def inner(): outer.b += 1 print outer.b inner() outer() Which gives me: AttributeError: 'function' object has no attribute 'b' Perhaps I misapplied this method? choice 3: I know that Python can return multiple values in one line, but I don't think that applies here. My library function F, is looking for two separate function arguments From cookedm+news at physics.mcmaster.ca Fri Apr 1 16:10:12 2005 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Fri, 01 Apr 2005 16:10:12 -0500 Subject: numeric module References: <1112377090.192124.303640@o13g2000cwo.googlegroups.com> Message-ID: shama.bell at gmail.com writes: > Hello, > What's the problem with this code? I get the following error message: > > File "test.py", line 26, in test > print tbl[wi][bi] > IndexError: index must be either an int or a sequence > > ---code snippet---- > > from Numeric import * > tbl = zeros((32, 16)) > > def test(): > > val = testme() > wi = val >> 4 > bi = val & 0xFL [above changed to use val instead of crc, as you mentioned in another post] > print wi > print bi > print tbl[wi][bi] tbl[wi][bi] would be indexing the bi'th element of whatever tbl[wi] returns. For Numeric arrays, you need tbl[wi,bi] Now, you'll have another problem as Terry Reedy mentioned: the indices (in Numeric) need to be Python ints, not longs. You could rewrite your test() function as def test(): val = testme() wi = int(val >> 4) bi = int(val & 0xF) print wi print bi print tbl[wi,bi] and that'll work. -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From denise.hartley at gmail.com Wed Apr 20 14:57:48 2005 From: denise.hartley at gmail.com (D. Hartley) Date: Wed, 20 Apr 2005 11:57:48 -0700 Subject: python-text window vs. game/graphics window Message-ID: <8daabe5605042011577adf2f7d@mail.gmail.com> Hello, group! I am asking anyone who is knowledgeable about entering text into the text window while a game/graphics window is running (am using pygame). I have asked this on the 'tutor' mailing list and no one could/would answer it. I am making a space invaders clone for my Python Teacher's birthday, and so obviously can not ask him for help! Even the debugger wouldn't shed light on the situation, due to when it happens: I am trying to make a high score list. If you do not score high enough, the list displays in the text window (fine), and you can type y/n in the game window for a new game. If you DO make the high score list, it prompts you to enter your name on the text window (and hit enter), and displays the updated score list (great). However, when I click back to the graphics window, the whole thing closes/shuts down/crashes. For the life of me I cant figure it out. I have looked at the order of my steps, I've tried to follow it through piece by piece, and like I said I tried to use the debugger to step through it - but since the game just closes out, it doesnt tell me anything. 1. How can I stop this crash from happening? I have copied and pasted the "game over" section of my code below, and am attaching the entire code to the email, in case that would be helpful. 2. I'd REALLY like to make it display the high scores/prompt for user name on the game/graphics window, not in the text window, anyway - and that would eliminate the problem it seems to have when using keystrokes in the text window and then trying to switch back to the game window. (it's not a click-specific issue, alt-tab does it too). I apologize for the "newbie" nature of this question to a more advanced list, but I have tried everything else I can think of and am at my wits' end. The 'deadline' (birthday) is in a week and I'm stuck. I'd appreciate any comments or suggestions you might have, in as simple of language as you can offer them, ha ha. I *am* new to python, and so my code may not be so elegant. But I hope you can read it enough to see what I'm doing wrong or possibly just offer suggestions for displaying it all in the graphics window and avoiding the problem altogether. Thank you so much for your time and ideas! Sincerely, Denise #game over.. if lives == 0: def add_score(): high_scores = pickle.load(file("scores.pik")) score = total_enemy_hits if score > high_scores[-1][0]: print "Ta da! You got", total_enemy_hits, "Ranch Delivery Devices!" name = read_string("You made the high score list! What's your name? ") user_score = (score,name) high_scores.append(user_score) high_scores.sort(reverse=True) del high_scores[-1] pickle.dump(high_scores, file("scores.pik", "w")) for score, name in high_scores: slip = 30 - len(name) slip_amt = slip*" " prefix = 5*" " print prefix,name,slip_amt,score else: print "Sorry, you only got", total_enemy_hits, "Ranch Delivery Devices." print "You didn't quite make the high score list!" for score, name in high_scores: slip = 30 - len(name) slip_amt = slip*" " prefix = 5*" " print prefix,name,slip_amt,score print "Better luck next time!" add_score() end.play() showGameOver(screen, background_image) pygame.display.flip() answer = "" while not answer in ("y","n"): for event in pygame.event.get(): if event.type == KEYDOWN: if event.key == K_n: answer = "n" elif event.key == K_y: answer = "y" if answer == "n": running = 0 else: return 1 #refresh the display pygame.event.pump() pygame.display.flip() #well, nice playing with you... screen = pygame.display.set_mode((640, 480)) return 0 -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: Copy of play w scorelist2.py URL: From bokr at oz.net Fri Apr 15 17:12:36 2005 From: bokr at oz.net (Bengt Richter) Date: Fri, 15 Apr 2005 21:12:36 GMT Subject: Using python from a browser/security hole References: Message-ID: <42602bef.30220374@news.oz.net> On Fri, 15 Apr 2005 09:52:41 -0400, James Carroll wrote: >I don't think Jython will help much here... you would have to embed >jython in your applet which makes it big, which makes it take longer >to download... (or you could install it ahead of time on each client.) > >I asked my friend who did some smartcard authentication at a previous >job... and in his case the card had an LCD readout that gave a >different key every minute, and the user had to look at that number, >and type it in for access. To automate this, with a card reader, >there could be a (barcoder-scanner-like) app on each client that would >emulate typing on the keyboard when the card was read. The user would >have to click on a text field, then scan their card and the number >would show up automatically. One step further... some javascript >could possibly get the keyboard events as long as the page had input >focus, and if it sees a smart-card key like sequence of keystrokes, >then submit a form from a hidden IFrame.... > >So, short of writing your own plug-in extension for each different >browser, I'm not sure you're going to be able to access the client >hardware from a client-side web page. Either way (plug-in or java >applet with privileges) your user will have to agree to give access to >the hardware. > >-Jim I wonder if anyone has written a safe proxy for this kind of purpose, so that any browser would see just ordinary html at a particular url but would then be viewing html either passed through from a particular server or synthesized for for the local access part, which it could do arbitrarily, depending on its user/privilege status. [BTW, note reason why top-posts scramble things eventually. Please reconsider ;-)] > >On 4/15/05, Philippe C. Martin wrote: >> Neil, >>=20 >> Would Jpython let me do that ? >> Would java let me call an external Python script - which in turn would >> access my device ? >>=20 >> Thanks >>=20 >> Philippe >>=20 >>=20 >> Neil Hodgson wrote: >>=20 >> > Philippe: >> > >> >> Since I need to access a local/client device from the page and >> >> that I wish to be cross-platform; does that mean Java is my only >> >> way out ? See comment above. >> > >> > Java is designed to be safe and not allow access to client devices. >> > There is a mechanism where you can attempt to ask for permission from >> > Java but it looked complex to me and I doubt many browsers will >> > cooperate. They have often locked security down to prevent this sort of >> > access. >> > >> > Neil >>=20 >> -- >> http://mail.python.org/mailman/listinfo/python-list >>=20 >> Regards, Bengt Richter From mahs at telcopartners.com Fri Apr 8 18:03:15 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Fri, 08 Apr 2005 15:03:15 -0700 Subject: [Marshal Bug] Was Re: curious problem with large numbers In-Reply-To: <4256e2ff$1@nntp0.pdx.net> References: <723eb693050407124816431b6a@mail.gmail.com> <4255cd93$1@nntp0.pdx.net> <4256a676@nntp0.pdx.net> <4256b80b.34130777@news.oz.net> <4256b774$1@nntp0.pdx.net> <4256c65c$1@nntp0.pdx.net> <4256e2ff$1@nntp0.pdx.net> Message-ID: <4256FFA3.1060304@telcopartners.com> OK - I think this is it: My last post fingering pickle was almost but not quite right*. Actually the cuplrit is marshal, which produces the incorrect result that was noted. The bug has nothing to do with IDLE, except that it uses marshal for inter-process communication. Here's the failure case: >>> marshal.dumps(1e10000) 'f\x061.#INF' >>> marshal.loads(_) 1.0 >>> I speculate that this comes from marshal doing eval('1.#INF') rather than float('1.#INF'), and that it should be fixed to use float. Alternatively, it could detect this special case and raise its own exception. By analogy with pickle and cPickle it would make sense to raise ValueError on unmarshalling i.e., marshal.load(s). >>> import pickle >>> pickle.dumps(1e10000) 'F1.#INF\n.' >>> pickle.loads(_) Traceback (most recent call last): File "", line 1, in ? File "c:\python24\lib\pickle.py", line 1394, in loads return Unpickler(file).load() File "c:\python24\lib\pickle.py", line 872, in load dispatch[key](self) File "c:\python24\lib\pickle.py", line 968, in load_float self.append(float(self.readline()[:-1])) ValueError: invalid literal for float(): 1.#INF >>> A more ambitious fix (which could be combined with option 1) would have the float constructor accept 1.#INF Incidentally, the reason why this workaround is effective: IDLE 1.1 >>> 1e308*2 1.#INF >>> is that it is the compiled code object (not what it evaluates to) that is marshalled >>> co = compile("1e308*2","","single") >>> dis.dis(co) 1 0 LOAD_CONST 0 (1e+308) 3 LOAD_CONST 1 (2) 6 BINARY_MULTIPLY 7 PRINT_EXPR 8 LOAD_CONST 2 (None) 11 RETURN_VALUE >>> ma = marshal.dumps(co) >>> ma 'c\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00@\x00\x00\x00s\x0c\x00\x00\x00d\x00\x00d\x01\x00\x14Fd\x02\x00S(\x03\x00\x00\x00f\x061e+308i\x02\x00\x00\x00N(\x00\x00\x00\x00(\x00\x00\x00\x00(\x00\x00\x00\x00(\x00\x00\x00\x00t\x06\x00\x00\x00t\x01\x00\x00\x00?\x01\x00\x00\x00s\x00\x00\x00\x00' >>> Michael From mahs at telcopartners.com Wed Apr 20 20:09:16 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Wed, 20 Apr 2005 17:09:16 -0700 Subject: Enumerating formatting strings In-Reply-To: References: <3cm9r2F6nif67U1@individual.net> <42660fc2.42093557@news.oz.net> <42662dc9.49780670@news.oz.net> Message-ID: Andrew Dalke wrote: > I see you assume that only \w+ can fit inside of a %() > in a format string. The actual Python code allows anything > up to the balanced closed parens. > Gah! I guess that torpedoes the regexp approach, then. Thanks for looking at this Michael From robin at alldunn.com Tue Apr 26 21:17:16 2005 From: robin at alldunn.com (Robin Dunn) Date: Tue, 26 Apr 2005 18:17:16 -0700 Subject: ANN: wxPython 2.6.0.0 Message-ID: <426EE81C.6070608@alldunn.com> Announcing ---------- I'm pleased to announce the 2.6.0.0 release of wxPython, now available for download at http://wxpython.org/download.php. This release consists of one more round of stabalization work (bug fixes and such) since the 2.5 series, and a few minor new features. This first 2.6 release marks the begining of a new stable release series, which for Python means that there will be no API compatibility breakage for the life of the series. (It means more than that for the core C++ code, see http://wiki.wxpython.org/index.cgi/ReleaseSeries) See the changes list below for details. What is wxPython? ----------------- wxPython is a GUI toolkit for the Python programming language. It allows Python programmers to create programs with a robust, highly functional graphical user interface, simply and easily. It is implemented as a Python extension module that wraps the GUI components of the popular wxWidgets cross platform library, which is written in C++. wxPython is a cross-platform toolkit. This means that the same program will usually run on multiple platforms without modifications. Currently supported platforms are 32-bit Microsoft Windows, most Linux or other Unix-like systems using GTK or GTK2, and Mac OS X. Changes in 2.6.0.0 ------------------ wxMSW: Fixed wx.TransientPopupWindow (and therefore wx.TipWindow) to auto-dismiss when the mouse is clicked outside of the popup like it is supposed to. wxMSW: Fixed bug #1167891 wx.Notebook display problem with wx.NB_MULTILINE. wxMSW: Fixed bad cliping of hidden windows inside of wx.StaticBox. wxGTK: The configure flags for selecting GTK+ 1.2.x or 2.x has changed slightly. It is now --with-gtk[=VERSION] where VERSION is either '1', '2' or 'any'. The default is '2'. wx.stc.StyledTextCtrl: Added the following methods for alternate ways to set and fetch text from the document buffer. They work similarly to the existing methods of the same name, except that they don't go through the same string/unicode <--> wxString conversions. The "Raw" methods will do no conversions at all and in a unicode build of wxPython the strings will be in the utf-8 encoding and in an ansi build no assumption is made about the encoding. The "UTF8" functions will attempt to always get/set utf-8 text, which it will always be able to do in a unicode build, and in an ansi build it will depend on the content of the utf-8 used being compatible with the current encoding, (you'll get an exception otherwise.) =================== ==================== AddTextRaw AddTextUTF8 InsertTextRaw InsertTextUTF8 GetCurLineRaw GetCurLineUTF8 GetLineRaw GetLineUTF8 GetSelectedTextRaw GetSelectedTextUTF8 GetTextRangeRaw GetTextRangeUTF8 SetTextRaw SetTextUTF8 GetTextRaw GetTextUTF8 AppendTextRaw AppendTextUTF8 =================== ==================== wx.stc.StyledTextCtrl: Added the StyleSetFontEncoding(style, enc) method that allows you to set the encoding to be used by the font for a particular style. wxMac: Fixed wx.ComboBox to forward the EVT_CHAR, EVT_KEY_DOWN, EVT_KEY_UP and EVT_TEXT events from its embedded text control. wxMac: Corrected refresh bugs in wxGrid. XRCed: Updated to version 0.1.5. * Added wxWizard, wxWizardPageSimple (only from pull-down menu). * Hide command for test window. * Replacing classes works better. * Added Locate tool. -- Robin Dunn Software Craftsman http://wxPython.org Java give you jitters? Relax with wxPython! From magoldfish at gmail.com Fri Apr 22 23:10:46 2005 From: magoldfish at gmail.com (Marcus Goldfish) Date: Fri, 22 Apr 2005 23:10:46 -0400 Subject: internet explorer/firefox plugin/toolbar In-Reply-To: <008201c5479c$18222b90$0301a8c0@Mesa.com> References: <008201c5479c$18222b90$0301a8c0@Mesa.com> Message-ID: <5e183f3d050422201016a48edf@mail.gmail.com> > does anyone have any ideas as to how to go about creating a plugin/toolbar > for both/either the IE/Firefox browsers? For IE, checkout Browser Helper Objects (BHOs). Sample python code can be found at: http://aspn.activestate.com/ASPN/Mail/Message/ctypes-users/2263094 Marcus From bokr at oz.net Sun Apr 17 03:31:34 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 17 Apr 2005 07:31:34 GMT Subject: pre-PEP: Simple Thunks References: <4260bc72.67216001@news.oz.net> Message-ID: <4261da60.140413834@news.oz.net> On Sat, 16 Apr 2005 18:46:28 -0700, Brian Sabbey wrote: [...] >> In that case, my version would just not have a do, instead defining the do suite >> as a temp executable suite, e.g., if instead >> >> >> we make an asignment in the suite, to make it clear it's not just a calling thing, e.g., >> >> do f(27, 28): >> x = stuff() >> >> then my version with explict name callable suite would be >> >> def f(thunk, a, b): >> # a == 27, b == 28 >> before() >> thunk() >> after() >> >> set_x(): >> x = stuff() # to make it plain it's not just a calling thing >> >> f(set_x, 27, 28) >> # x is now visible here as local binding >> >> but a suitable decorator and an anonymous callable suite (thunk defined my way ;-) would make this >> >> @f(27, 28) >> (): x = stuff() >> > >Hmm, but this would require decorators to behave differently than they do >now. Currently, decorators do not automatically insert the decorated >function into the argument list. They require you to define 'f' as: > >def f(a, b): > def inner(thunk): > before() > thunk() > after() > return inner > >Having to write this type of code every time I want an thunk-accepting >function that takes other arguments would be pretty annoying to me. > Yes, I agree. That's the way it is with the decorator expression. Maybe decorator syntax is not the way to pass thunks to a function ;-) My latest thinking is in terms of suite expressions, :: being one, and actually (): is also a suite expression, yielding a thunk. So the call to f could just be written explicitly with the expression in line: f((():x=stuff()), 27, 28) or f((): x = stuff() done = True ,27, 28) # letting the dedented ',' terminate the (): rather than parenthesizing or safe_open((f): for line in f: print f[:20] ,'datafile.txt', 'rb') That's not too bad IMO ;-) >>> >>> Thunks can also accept arguments: >>> >>> def f(thunk): >>> thunk(6,7) >>> >>> do x,y in f(): >>> # x==6, y==7 >>> stuff(x,y) >> >> IMO >> @f >> (x, y): stuff(x, y) # like def foo(x, y): stuff(x, y) >> >> is clearer, once you get used to the missing def foo format >> > >OK. I prefer a new keyword because it seems confusing to me to re-use >decorators for this purpose. But I see your point that decorators can be >used this way if one allows anonymous functions as you describe, and if >one allows decorators to handle the case in which the function being >decorated is anonymous. I tend to agree now about using decorators for this. With thunk calling parameter and extra f calling parameters, in line would look like f((x,y): # x==6, y==7 stuff(x, y) ,'other' ,'f' ,args) I guess you could make a bound method to keep the thunk dothunk_n_all = f.__get__((x, y): stuff(x,y) ,type(():pass)) and then call that with whatever other parameter you specified for f do_thunk_n_all(whatever) if that seemed useful ;-) > >>> >>> The return value can be captured >>> >> This is just a fallout of f's being an ordinary function right? >> IOW, f doesn't really know thunk is not an ordinary callable too? >> I imagine that is for the CALL_FUNCTION byte code implementation to discover? > >yes > >> >>> def f(thunk): >>> thunk() >>> return 8 >>> >>> do t=f(): >>> # t not bound yet >>> stuff() >>> >>> print t >>> ==> 8 >> That can't be done very well with a decorator, but you could pass an >> explicit named callable suite, e.g., >> >> thunk(): stuff() >> t = f(thunk) > >But not having to do it that way was most of the purpose of thunks. I forgot that (): is an expression t = f(():stuff()) # minimal version or final_status = safe_open((f): for line in f: print f[:20] ,'datafile.txt', 'rb') > >It wouldn't be a problem to use 'return' instead of 'continue' if people >so desired, but I find 'return' more confusing because a 'return' in 'for' >suites returns from the function, not from the suite. That is, having >'return' mean different things in these two pieces of code would be >confusing: > >for i in [1,2]: > return 10 > >do i in each([1,2]): > return 10 But in my syntax, each((i): return 10 ,[1,2]) Um, well, I guess one has to think about it ;-/ The thunk-accepter could pass the thunk a mutable arg to put a return value in, or even a returnvalue verse thunk? def accepter(thk, seq): acquire() for i in seq: thk(i, (retval):pass) if retval: break release() accepter((i, rvt): print i rvt(i==7) # is this legal? , xrange(10)) Hm, one thing my syntax does, I just noticed, is allow you to pass several thunks to a thunk-accepter, if desired, e.g., (parenthesizing this time, rather than ending (): with dedented comma) each( ((i): # normal thunk print i), ((j): # alternative thunk rejectlist.append(j)), [1,2]) >I see what you're getting at with decorators and anonymous functions, but >there are a couple of things that, to me, make it worth coming up with a >whole new syntax. First, I don't like how one does not get the thunk >inserted automatically into the argument list of the decorator, as I >described above. Also, I don't like how the return value of the decorator >cannot be captured (and is already used for another purpose). The fact >that decorators require one more line of code is also a little bothersome. >Decorators weren't intended to be used this way, so it seems somewhat >hacky to do so. Why not a new syntax? > Ok, I agree this does not fit decorators well. And I do agree that a nice syntax that sugars over the creation and passing of thunks makes for clean simple cases, but I would like access to the non-sugar primitives too, which for do in (): IIUC translates to my < opt assignment> (((): ),) With possible paren dropping and white space insertion if you want to arrange things. With the primitives, I can pass multiple thunks to an accepter, and put them in specific arg positions. I also can also bind it and use it to get a side effect out of a generator expression that now has its own scope, e.g., count = 0 counter(count): count +=1 list(i for i in xrange(20) if counter() or True) Interestingly, this ought to work, right? stopper(i): if i>5: raise StopIteration list(stopper(i) or i for i in xrange(20)) All untested hadwaving, of course ;-) Regards, Bengt Richter From dirgesh at gmail.com Mon Apr 4 15:59:39 2005 From: dirgesh at gmail.com (GujuBoy) Date: 4 Apr 2005 12:59:39 -0700 Subject: Changing TEXT color from python Message-ID: <1112644779.486105.179240@l41g2000cwc.googlegroups.com> so i am writing a program in Python and i want to print out a few statements in Different colors for example "Print hello world in RED, and "GOOD BYE in blue" " how can i do this...and hopefully without including any external modules. thanks in advance From python-url at phaseit.net Mon Apr 25 13:08:03 2005 From: python-url at phaseit.net (Simon Brunning) Date: Mon, 25 Apr 2005 17:08:03 GMT Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Apr 25) Message-ID: QOTW: "Sure, but what about the case where his program is on paper tape and all he has for an editor is an ice pick?" - Grant Edwards "And in this case, you get improved usability *and* improved speed at the same time. That's the way it should be." - Fredrik Lundh The Simplest Possible Metaclass: http://orbtech.com/blog/simplemetaclass Enumerating formatting strings: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/315099737b139c5e Andrew Dalke continues to produce interesting articles at a frankly preposterous rate. A selection, covering tracing python code, using XML-RPC, screen scraping, parsing and statistics: http://www.dalkescientific.com/writings/diary/archive/2005/04/20/tracing_python_code.html http://www.dalkescientific.com/writings/diary/archive/2005/04/21/using_xmlrpc.html http://www.dalkescientific.com/writings/diary/archive/2005/04/21/screen_scraping.html http://www.dalkescientific.com/writings/diary/archive/2005/04/22/parsing.html http://www.dalkescientific.com/writings/diary/archive/2005/04/22/statistics.html Wing 2.0.3 is available: http://wingware.com/pub/wingide/press/2.0.3-release.html Why does Python slicing work the way it does? http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/947866ec21512405 Another Python tool from Google; this one a MySQL status monitor: http://goog-mmaim.sourceforge.net/ Processing XML one 'record' at a time: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/4b5f06d837a0e20b GOTO hell: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/832906c6122dc137 Launching a subprocess without a console window on Windows: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/409002 Python or PHP? Duh! http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/6d65bbac956ebbb0 ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. For far, FAR more Python reading than any one mind should absorb, much of it quite interesting, several pages index much of the universe of Pybloggers. http://lowlife.jp/cgi-bin/moin.cgi/PythonProgrammersWeblog http://www.planetpython.org/ http://mechanicalcat.net/pyblagg.html comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Steve Bethard, Tim Lesher, and Tony Meyer continue the marvelous tradition early borne by Andrew Kuchling, Michael Hudson and Brett Cannon of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ The Python Business Forum "further[s] the interests of companies that base their business on ... Python." http://www.python-in-business.org Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Cetus collects Python hyperlinks. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ (requires subscription) http://groups-beta.google.com/groups?q=python-url+group:comp.lang.python*&start=0&scoring=d& http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From ajikoe at gmail.com Sun Apr 24 11:49:11 2005 From: ajikoe at gmail.com (ajikoe at gmail.com) Date: 24 Apr 2005 08:49:11 -0700 Subject: Is this a bug? In-Reply-To: <116nfblc10i9340@corp.supernews.com> References: <426bb3e9$0$83084$ed2619ec@ptn-nntp-reader01.plus.net> <116nfblc10i9340@corp.supernews.com> Message-ID: <1114357751.497493.307900@o13g2000cwo.googlegroups.com> check this site: http://mail.python.org/pipermail/python-bugs-list/2003-November/021201.html pujo From kent37 at tds.net Wed Apr 27 07:10:22 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 27 Apr 2005 07:10:22 -0400 Subject: Can .py be complied? In-Reply-To: <426f562f$1_3@rain.i-cable.com> References: <426ec8f7_2@rain.i-cable.com> <426f562f$1_3@rain.i-cable.com> Message-ID: <426f6eb7$1_1@newspeer2.tds.net> monkey wrote: >>It is generally not very easy or straight-forward. >>For now, you can use pyfreeze to snap the application..... >>If your application does not use any C modules, you can try to use >>Jython instead. >> >>Cheers >>Maurice > > > If using Jython to complie, is the end-user need JRE instead of Python > installed, or need both of them? The end-user needs the JRE, not Python. Kent From harlinseritt at yahoo.com Fri Apr 1 06:19:16 2005 From: harlinseritt at yahoo.com (Harlin Seritt) Date: 1 Apr 2005 03:19:16 -0800 Subject: Showing errors explicitly in try... except Message-ID: <1112354356.092391.238710@f14g2000cwb.googlegroups.com> When using try... except... errors don't show up. Is there a way to force stderr despite using try...except? thanks, Harlin Seritt From sjmachin at lexicon.net Wed Apr 20 17:58:40 2005 From: sjmachin at lexicon.net (John Machin) Date: Thu, 21 Apr 2005 07:58:40 +1000 Subject: Python Win32 Extensions and Excel 2003. OL 11.0 Supported? References: <1114012496.533936.297580@l41g2000cwc.googlegroups.com> Message-ID: <1iid61lqtl5u2hek2c7khnho9uinhgo4ie@4ax.com> On Wed, 20 Apr 2005 13:05:54 -0400, Steve Holden wrote: >Mudcat wrote: >> Howdy, >> >> I could have sworn I downloaded a version of python win that supported >> object library 11.0 at some point. However I just downloaded versions >> 204 and 203, and the highest version they have is OL 9.0. >> >> Does anyone know if this is a mistake or if Excel 2003 isn't yet >> supported with the extensions? >> >I was under the impression that makepy just listed the libraries it >found on the system it ran on. Is this wrong? > This is my impression also. Basis 1: Observation: E.g. client machine with Excel 2000: OL 9.0. My machine: OL 10.0 and (no kidding) 5.0 Basis 2: Reductio ad a[db]surdum [1]: Where else would makepy be getting its info from? Would we really expect pywin32 to have all the info available to support all libraries ever used on any Windows machine? How long would the download take? What would be the legal implications of [re]distributing all that Microsoft-created stuff? Cheers, John Note [1]: What's happened to the martellibot? Not a post for over 2 months! Who else will leap in and tell me which of adsurdum and absurdum is better usage? From WLigtenberg at gmail.com Fri Apr 22 14:02:16 2005 From: WLigtenberg at gmail.com (Willem Ligtenberg) Date: Fri, 22 Apr 2005 20:02:16 +0200 Subject: XML parsing per record References: Message-ID: Since there are more than one database references possible per record you should get per record a list of database names, database strings and databases ids. (where the strings and the id's are really the same thing...) So per record you check for both alternatives but since there could be more than one, you do findall and get a (unsorted) list back. And now you don't know which ID belonged to which database... See my problem? Cheers, Willem On Fri, 22 Apr 2005 19:38:03 +0200, Fredrik Lundh wrote: > Willem Ligtenberg wrote: > >> So I get a list database names and two! lists of ID's >> And those two are in no way related. Is there an easy way to create a >> dictionary like this DBname --> ID > > why not just check for both alternatives? > > text = elem.findtext("Object-id_str") > if text is None: > text = elem.findtext("Object-id_id") > > (or you can loop over the child elements and map elem.tag through a > dictionary...) > >> If not, I still might need to revert to SAX... :( > > you still have to check for both alternatives... > > (if you find a parsing problem that you cannot solve with a light-weight > DOM, SAX won't help you...) > > From wweston at att.net Fri Apr 8 11:04:32 2005 From: wweston at att.net (wes weston) Date: Fri, 08 Apr 2005 15:04:32 GMT Subject: Rotating arbitrary sets of elements within a list In-Reply-To: <1112971150.361681.313100@o13g2000cwo.googlegroups.com> References: <1112971150.361681.313100@o13g2000cwo.googlegroups.com> Message-ID: <44x5e.54931$cg1.34951@bgtnsc04-news.ops.worldnet.att.net> phil_nospam_schmidt at yahoo.com wrote: > I'm trying to come up with a good algorithm to do the following: > > Given a list 'A' to be operated on, and a list 'I' of indices into 'A', > rotate the i'th elements of 'A' left or right by one position. > > Here's are some examples: > > A = [a, b, c, d, e, f] > I = [0, 3, 4] > > rotate(A, I, 'left') --> [b, c, d, e, f, a] > rotate(A, I, 'right') --> [b, a, c, f, d, e] > > I = [1, 3, 4] > > rotate(A, I, 'left') --> [b, a, d, e, c, f] > rotate(A, I, 'right') --> [a, c, b, f, d, e] > > Any ideas? > phil, Could you do a circlular buffer where the front starts at 'a' (0) and rotate left increments front. The i'th element is gotten as mod 6 (front+i) where 6 would be the length of the list. wes From roccomoretti at hotpop.com Thu Apr 21 10:22:00 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Thu, 21 Apr 2005 09:22:00 -0500 Subject: Why Python does *SLICING* the way it does?? In-Reply-To: References: <1113976729.450677.261130@o13g2000cwo.googlegroups.com> <_Lm9e.23143$Xm3.17864@trndny01> <1114003997.778676.144950@z14g2000cwz.googlegroups.com> Message-ID: Steve Holden wrote: > The principle of least surprise is all very well, but "needless surprise > of newbies" is a dangerous criterion to adopt for programming language > design and following it consistently would lead to a mess like Visual > Basic, which grew by accretion until Microsoft realized it was no longer > tenable and broke backward compatibility. Well, *needless* surprise of newbies is never a good thing. If it were, it wouldn't be needless, now would it? :-) Surprising newbies just to surprise newbies is just cruel, but there is room in this world for "it may suprise you now, but you'll thank us later" and situations where there is a "newbie way" and an "other way", and the "other" way is chosen because it's the easiest thing for the most people in the long run. But I agree, having "the easiest thing for newbies" as your sole criterion for language design is a road to madness, for no other reason than that newbies don't stay newbies forever. From ola.natvig at infosense.no Mon Apr 11 07:13:09 2005 From: ola.natvig at infosense.no (Ola Natvig) Date: Mon, 11 Apr 2005 13:13:09 +0200 Subject: database in python ? In-Reply-To: References: <1113197530.990898.46130@z14g2000cwz.googlegroups.com> <1113216765.784331.156820@f14g2000cwb.googlegroups.com> Message-ID: <5n2qi2-g9g.ln1@pluto.i.infosense.no> Pierre-Fr?d?ric Caillaud wrote: > >> MySQL is an excellent option is very well documented. It is also a >> defacto standard for OpenSource databases. > > > MySQL sucks for anything but very very basic stuff as it supports > no transactions, foreign keys, procedures, triggers, concurrency, etc. > Postgresql is a lot better, free, and the psycopg adapter for > Postgres is *very very* fast (a lot faster than the MySQL one) and it > has a dictfetchall() method which is worth its weight in donuts ! MySQL has support for transactions and foreign keys in it's InnoDB engine. In 5.0 it supports views procedures. Some people seems to hate MySQL :-) but a whole lot of other people like it a lot. The thing is, if you don't spesificaly state that you want triggers, concurrency and procedures I guess that your needs are quite basic. However you won't be be disappointed with either MySQL or postgree in your trunk :) ola -- -------------------------------------- Ola Natvig infoSense AS / development From ville at spammers.com Wed Apr 6 03:38:58 2005 From: ville at spammers.com (Ville Vainio) Date: 06 Apr 2005 10:38:58 +0300 Subject: Best editor? References: <1112725379.514651.66540@l41g2000cwc.googlegroups.com> Message-ID: >>>>> "Miki" == Miki Tebeka writes: Miki> Emacs (or VIm in my case) takes time to learn. However when Miki> you start to understand it and know you way around it'll do Miki> things no other editor will do for you. Other editors also do stuff Emacs won't do. Code completion is a killer feature and emacs sucks at it (yes, w/ Cedet too). Emacs is pretty good for Python if you can't wait for something like Eclipse+pydev to start (which is a good choice, and worth learning). Emacs is not necessarily worth learning unless you are an emacs user already. Emacs also looks so horrible in Linux that I tend to go for Kate when I'm at home. -- Ville Vainio http://tinyurl.com/2prnb From syorty at socal.rr.com Tue Apr 19 12:33:09 2005 From: syorty at socal.rr.com (Sam Yorty) Date: Tue, 19 Apr 2005 16:33:09 GMT Subject: Do You Want To Know For Sure That You Are Going To Heaven? The reason some people don't know for sure if they are going to Heaven when they die is because they just don't know. The good news is that you can know for sure that you are going to Heaven wh References: <1113925283.115755.202120@f14g2000cwb.googlegroups.com> Message-ID: <9pa9e.893$zX7.248@newssvr13.news.prodigy.com> The only people who "know" they are going to heaven, clearly aren't wrote in message news:1113925283.115755.202120 at f14g2000cwb.googlegroups.com... > > The reason some people don't know for sure > if they are going to Heaven when they die > is because they just don't know. > > The good news is that you can know for > sure that you are going to Heaven which is > described in the Holy Bible as a beautiful > place with no death, sorrow, sickness or > pain. > > God tells us in the Holy Bible how simple > it is to be saved so that we can live > forever with Him in Heaven. > > "For if you confess with your mouth Jesus > is Lord and believe in your heart that God > raised Him from the dead, you > WILL BE SAVED." (Romans 10:9) > > Over 2000 years ago God came from Heaven > to earth in the person of Jesus Christ to > shed His blood and die on a cross to pay > our sin debt in full. > > Jesus Christ was born in Israel > supernaturally to a virgin Jewish woman > named Mary and lived a sinless life for > thirty-three years. > > At the age of thirty-three Jesus was > scourged and had a crown of thorns pressed > onto His head then Jesus was crucified. > > Three days after Jesus died on a cross and > was placed in a grave Jesus rose from the > dead as Jesus said would happen before > Jesus died. > > If someone tells you that they are going > to die and in three days come back to life > again and it happens then this person must > be the real deal. > > Jesus Christ is the only person that ever > lived a perfect sinless life. > > This is why Jesus is able to cover our > sins(misdeeds) with His own blood because > Jesus is sinless. > > The Holy Bible says, "In Him(Jesus) we > have redemption through His blood, the > forgiveness of sins..." (Ephesians 1:7) > > If you would like God to forgive you of > your past, present and future sins just > ask Jesus Christ to be your Lord and > Saviour. > > It doesn't matter how old you are or how > many bad things that you have done in > your life including lying and stealing > all the way up to murder. > > Just pray the prayer below with your > mouth and mean it from your heart and > God will hear you and save you. > > Dear Jesus Christ, I want to be saved so > that I can have a home in Heaven with You > when I die. I agree with You that I am a > sinner. I believe that You love me and want > to save me. I believe that You bled and > died on the cross to pay the penalty for my > sins and that You rose from the dead. > Please forgive my sins and come into my > heart and be my Lord and Saviour. Thanks > Lord Jesus Christ for forgiving me and > saving me through Your merciful grace. > Amen. > > Welcome to the family of God if you just > allowed God to save you. Now you are a real > Christian and you can know for sure that > you will live in Heaven forever when this > life comes to an end. > > As a child of God we are to avoid > sin(wrongdoing), but if you do sin the > Holy Bible says, "My dear children, I > write this to you so that you will not sin. > But if anybody does sin, we have one who > speaks to the Father in our defense Jesus > Christ, the Righteous One." > > Those of you that have not yet decided to > place your trust in the Lord Jesus Christ > may never get another chance to do so > because you do not know when you will die. > > Jesus said "I am the way, the truth and > the life: no one can come to the > Father(God)(in Heaven), but by me." > (John 14:6) > > This means that if you die without > trusting in Jesus Christ as your Lord and > Saviour you will be forever separated from > the love of God in a place called Hell. > > The Holy Bible descibes Hell as a place of > eternal torment, suffering, pain and agony > for all those who have rejected Jesus Christ. > > The good news is that you can avoid Hell by > allowing Jesus Christ to save you today. > Only then will you have true peace in your > life knowing that no matter what happens you > are on your way to Heaven. > > > Praise the Lord! > Servant of the Lord Jesus Christ > Ronald L. Grossi > > *Show this to your family and friends so > they can know that they have a choice > where they will spend eternity. Thanks! > > ____________________________________________________ > > > > Got Questions? > http://www.gotquestions.org/archive.html > > Other Languages > http://www.godssimpleplan.org/gsps.html > > Free Movie: To Hell and Back > http://www.tbn.org/index.php/8/1.html > > Animation > http://www.browser.to/jesus-animation > > The Passion Of The Christ > http://www.thepassionofthechrist.com > > Beware Of Cults > http://www.carm.org/cults/cultlist.htm > > About Hell > http://www.equip.org/free/DH198.htm > > Is Jesus God? > http://www.powertochange.com/questions/qna2.html > > Free Online Bible > http://www.biblegateway.com > > > ____________________________________________________ > From peter at engcorp.com Fri Apr 22 10:17:21 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 22 Apr 2005 10:17:21 -0400 Subject: Why Python does *SLICING* the way it does?? In-Reply-To: References: <1113976729.450677.261130@o13g2000cwo.googlegroups.com> <_Lm9e.23143$Xm3.17864@trndny01> <1114003997.778676.144950@z14g2000cwz.googlegroups.com> Message-ID: Rocco Moretti wrote: > Steve Holden wrote: >> The principle of least surprise is all very well, but "needless >> surprise of newbies" is a dangerous criterion to adopt for programming >> language design and following it consistently would lead to a mess >> like Visual Basic, which grew by accretion until Microsoft realized it >> was no longer tenable and broke backward compatibility. >... > But I agree, having "the easiest thing for newbies" as your sole > criterion for language design is a road to madness, for no other reason > than that newbies don't stay newbies forever. If Visual BASIC is the example of "easiest thing for newbies", then it disproves your theory already. I think VB newbies *do* stay newbies forever (or as long as they are using just VB). -Peter From greg at cosc.canterbury.ac.nz Fri Apr 1 00:59:18 2005 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Fri, 01 Apr 2005 17:59:18 +1200 Subject: Things you shouldn't do In-Reply-To: <1112159461.244256.311350@z14g2000cwz.googlegroups.com> References: <424A2080.4080800@yahoo.com> <1112159461.244256.311350@z14g2000cwz.googlegroups.com> Message-ID: <3b46a1F697cr9U1@individual.net> Paul McGuire wrote: > The code was filled with two key variables: t_1 and t_l. Printing out > the source in a Courier font made these two vars completely > indistinguishable, Are you sure it was Courier? I'm looking at it now in Courier, and they are different, although very similar. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From kay.schluehr at gmx.net Tue Apr 5 03:35:45 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 5 Apr 2005 00:35:45 -0700 Subject: Decorator Maker is working. What do you think? In-Reply-To: References: Message-ID: <1112686545.380929.142740@g14g2000cwa.googlegroups.com> Ron_Adam wrote: > Ok... it's works! :) > > So what do you think? Not much. As long as You do not present any nontrivial examples like Guidos MultiMethod decorator or an implementation of the dispatching "case" decorator I proposed that would benefit from factoring into pre- and postprocessing the pattern has only limited use and worse it suggests a misnomer: it obscures the semantics that is clearly functional/OO not procedural. Regards, Kay From bokr at oz.net Tue Apr 26 03:38:46 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 26 Apr 2005 07:38:46 GMT Subject: Quote-aware string splitting References: <9Kgbe.24031$h6.523@tornado.texas.rr.com> <116rahd5t0lq85e@corp.supernews.com> Message-ID: <426de8f7.556450523@news.oz.net> On Mon, 25 Apr 2005 19:40:44 -0700, Jeffrey Froman wrote: >J. W. McCall wrote: > >> For example, given the string: >> >> 'spam "the life of brian" 42' >> >> I'd want it to return: >> >> ['spam', 'the life of brian', '42'] > >The .split() method of strings can take a substring, such as a quotation >mark, as a delimiter. So a simple solution is: > >>>> x = 'spam "the life of brian" 42' >>>> [z.strip() for z in x.split('"')] >['spam', 'the life of brian', '42'] > >>> x = ' sspam " ssthe life of brianss " 42' >>> [z.strip() for z in x.split('"')] ['sspam', 'ssthe life of brianss', '42'] Oops, note some spaces inside quotes near ss and missing double quotes in result. Maybe (not tested beyond what you see): >>> [r for r in [(i%2 and ['"'+z+'"'] or [z.strip()])[0] for i,z in enumerate(x.split('"'))] if r] or [''] ['sspam', '" ssthe life of brianss "', '42'] >>> x = ' "" "" ' >>> [r for r in [(i%2 and ['"'+z+'"'] or [z.strip()])[0] for i,z in enumerate(x.split('"'))] ifr] or [''] ['""', '""'] >>> x='""' >>> [r for r in [(i%2 and ['"'+z+'"'] or [z.strip()])[0] for i,z in enumerate(x.split('"'))] ifr] or [''] ['""'] >>> x='' >>> [r for r in [(i%2 and ['"'+z+'"'] or [z.strip()])[0] for i,z in enumerate(x.split('"'))] ifr] or [''] [''] >>> [(i%2 and ['"'+z+'"'] or [z.strip()])[0] for i,z in enumerate(x.split('"'))] ['sspam', '" ssthe life of brianss "', '42'] Regards, Bengt Richter From pclinch at internet-glue.co.uk Fri Apr 8 11:30:58 2005 From: pclinch at internet-glue.co.uk (Paul Clinch) Date: 8 Apr 2005 08:30:58 -0700 Subject: dynamic loading of code, and avoiding package/module name collisions. References: Message-ID: <8cf2994e.0504080730.2cbdc4d4@posting.google.com> Dear "John Perks and Sarah Mount", > Long story short: what I'm looking for is information on how have a Python > app that: > * embeds an editor (or wxNoteBook full of editors) > * loads code from the editors' text pane into the app > * executes bits of it > * then later unloads to make way for an edited version of the code. > The new version needs to operate on a blank slate, so reload() may not be > appropriate. This sounds like 'idle'. Regards, Paul C. From hdnews at gawab.com Fri Apr 1 07:56:17 2005 From: hdnews at gawab.com (Hans Oesterholt-Dijkema) Date: Fri, 01 Apr 2005 14:56:17 +0200 Subject: Lambda: the Ultimate Design Flaw In-Reply-To: References: Message-ID: <424d427e$0$142$e4fe514c@news.xs4all.nl> > > The Fate Of LAMBDA in PLT Scheme v300 > or > Lambda the Ultimate Design Flaw > > Why drop LAMBDA? Why not? Isn't all code eventually anonymous and relocatable? From eurleif at ecritters.biz Sat Apr 23 22:17:49 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Sun, 24 Apr 2005 02:17:49 GMT Subject: Python or PHP? In-Reply-To: References: Message-ID: Peter Ammon wrote: > I'm bewildered why you haven't mentioned magic quotes. A one line > change to the configuration file can render your PHP site almost > entirely immune to SQL injection attacks. PHP's magic quotes is one of the most poorly-designed features I can think of. Instead of magically escaping only strings which will actually be passed to a database (like Python's DB-API does), it escapes every string that comes from the user, meaning that strings which will be sent back to the user have to be manually unescaped. Even worse, since it can be turned on and off, code which is designed for a magic_quotes=on environment will become seriously vulnerable when moved to an environment with magic_quotes on. Security-related features should never be toggleable! From steven.bethard at gmail.com Thu Apr 21 10:50:25 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 21 Apr 2005 08:50:25 -0600 Subject: deprecation of has_key? In-Reply-To: References: <1114069715.945176.73750@l41g2000cwc.googlegroups.com> <426775C8.3000303@holdenweb.com> Message-ID: Denis S. Otkidach wrote: > I believe it's a bad idea to remove this method, since behavior of both > "item in dict" and "for item in dict" (especially the later) in Python > does't seem sane to me. Just look at reverse operations: > > dict.fromkeys(seq) <-> d.keys(), d.iterkeys() - OK > dict(iterable) <-> d.iteritems() - why not iter(d)? > dict(l) <-> d.items() - why not list(d)? > dict(seq) <-> d.keys(), d.iterkeys() - looks very strange. > > And those ("item in dict" and "for item in dict") are related of course, > since the following should pass: > > for item in d: > assert item in d > > That's the reason why I always prefer to use has_key() and iteritems() > to in and iter(). Huh? I'm not following your logic. Why is "item in dict" less readable than "dict.has_key(item)"? Something to do with expecting inverses that don't exist? Personally, I use "item in dict" because it's quite readable to me, and generally faster. STeVe From bokr at oz.net Sat Apr 2 16:28:36 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 02 Apr 2005 21:28:36 GMT Subject: Docorator Disected References: <4p9t419ockcg8578g6guse3a14t16orebf@4ax.com> Message-ID: <424f04d0.137947037@news.oz.net> On Sat, 02 Apr 2005 14:29:08 GMT, Ron_Adam wrote: > >I was having some difficulty figuring out just what was going on with >decorators. So after a considerable amount of experimenting I was >able to take one apart in a way. It required me to take a closer look >at function def's and call's, which is something I tend to take for >granted. > I think it might help you to start out with very plain decorators rather than decorators as factory functions that return decorator functions that wrap the decorated function in a wrapper function. E.g., (this could obviously be parameterized as a single decorator factory, but I wanted to show the simplest level of decorator functionality) >>> def decoa(f): ... f.decstr = getattr(f, 'decstr', '') + 'a' ... return f ... >>> def decob(f): ... f.decstr = getattr(f, 'decstr', '') + 'b' ... return f ... >>> def decoc(f): ... f.decstr = getattr(f, 'decstr', '') + 'c' ... return f ... >>> @decoa ... @decoc ... @decob ... @decob ... def foo(): pass ... >>> foo.decstr 'bbca' I.e., @decoa @decoc def foo(): pass is almost[1] exactly equal to (note calling order c then a) def foo(): pass foo = decoc(foo) foo = decoa(foo) [1] One difference is that foo = deco(foo) is a RE-binding of foo, and the binding wouldn't happen at all if the @deco version raised an exception in deco. E.g., >>> def deco(f): raise NotImplementedError ... foo not yet defined: >>> foo Traceback (most recent call last): File "", line 1, in ? NameError: name 'foo' is not defined Try the bad decorator: >>> @deco ... def foo(): pass ... Traceback (most recent call last): File "", line 1, in ? File "", line 1, in deco NotImplementedError No go, and foo still undefined: >>> foo Traceback (most recent call last): File "", line 1, in ? NameError: name 'foo' is not defined But the other way around: bar undefined to start: >>> bar Traceback (most recent call last): File "", line 1, in ? NameError: name 'bar' is not defined Define it sucessfully: >>> def bar():pass ... >>> bar Try to decorate the old-fashioned way: >>> bar = deco(bar) Traceback (most recent call last): File "", line 1, in ? File "", line 1, in deco NotImplementedError >>> bar Still there, defined as before (well, strictly speaking, not necessarily as before: with bar already defined, deco could have messed with the existing bar and THEN raised the exception). Which would also happen with @deco, just that the new binding to bar wouln't happen. >>> def decobomb(f): ... f.bomb = 'bombed' ... raise Exception, 'Did it bomb the existing function?' ... >>> def foo(): pass ... >>> vars(foo).keys() [] >>> @decobomb ... def foo(): pass ... Traceback (most recent call last): File "", line 1, in ? File "", line 3, in decobomb Exception: Did it bomb the existing function? >>> vars(foo).keys() [] Nope, seems that was a new foo that got bombed and then not bound to replace the old foo. >>> foo.bomb Traceback (most recent call last): File "", line 1, in ? AttributeError: 'function' object has no attribute 'bomb' >I'm not sure this is 100%, or if there are other ways to view it, but >it seems to make sense when viewed this way. I like annotated code walk-throughs. But as others have pointed out, it's still a bit buggy ;-) Regards, Bengt Richter From mahs at telcopartners.com Fri Apr 8 02:08:06 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Thu, 07 Apr 2005 23:08:06 -0700 Subject: curious problem with large numbers In-Reply-To: References: <723eb693050407124816431b6a@mail.gmail.com> <4255cd93$1@nntp0.pdx.net> Message-ID: Steve Holden wrote: > Scott David Daniels wrote: > >> Terry Reedy wrote: >> >>> On my Windows machine with 2.2.1, I get exactly what you expected: >>> >>>>>> 1e10000 >>> >>> >>> 1.#INF >>> ... >>> If you get wrong behavior on a later version, then a bug has been >>> introduced somewhere, even perhaps in VC 7, used for 2.4. >> >> >> >> Nope, it is also there for 2.3.4 (May 25 2004, 21:17:02). This is not >> necessarily a bug in the sense of a fixable bug; floating point has >> vagaries that are not necessarily easily controllable from the C source >> side. > > > While this may be true, it's pretty strange that Michael Spencer reports > apparently correct results on Windows 2.3.3 and 2.4, and I confirm the > Windows 2.4 result on my own system, while you report that 2.3.4 gives > an error. Or isn't that what you are reporting? > > A further Windows data point from Cygwin: > > Python 2.4 (#1, Dec 4 2004, 20:10:33) > [GCC 3.3.3 (cygwin special)] on cygwin > Type "help", "copyright", "credits" or "license" for more information. > >>> 1e10000 > Inf > >>> > > regards > Steve I guess the behavior is also hardware-dependent. FWIW, I tested on an Athlon XP box. Michael From lucio.torre at gmail.com Fri Apr 15 19:56:35 2005 From: lucio.torre at gmail.com (lucio.torre at gmail.com) Date: 15 Apr 2005 16:56:35 -0700 Subject: ANN: Python 2.3.2 for PalmOS available In-Reply-To: References: <1113608405.558884.235890@f14g2000cwb.googlegroups.com> Message-ID: <1113609395.016316.202220@f14g2000cwb.googlegroups.com> Fixed. Thanks. From jjl at pobox.com Sun Apr 24 07:44:22 2005 From: jjl at pobox.com (John J. Lee) Date: 24 Apr 2005 11:44:22 +0000 Subject: gui developing References: <116iir4hq8muc62@corp.supernews.com> <200504222027.40280.james@wrong.nu> <87sm1ilfhr.fsf@pobox.com> Message-ID: <87sm1gqu09.fsf@pobox.com> jjl at pobox.com (John J. Lee) writes: > Shane Hathaway writes: [...] > > However, I haven't heard whether PyQt for Qt 4 will also be available > > under the GPL. > > Yes, PyQt will be available under the same license as Qt. Oops, s/license/licenses/ John From reinhold-birkenfeld-nospam at wolke7.net Tue Apr 19 09:21:27 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Tue, 19 Apr 2005 15:21:27 +0200 Subject: Variables variable In-Reply-To: References: Message-ID: <3ckeukF6n53cpU1@individual.net> Adriano Monteiro wrote: > Hi folks, > > Someone know how to make variables variable like in PHP? > It's something like this: > > $a = 'hi' > $$a = 'testing' > echo $hi > 'testing' You are most certainly wanting to use dictionaries. Or, if you work with attributes of an object, use getattr. Reinhold From vze4rx4y at verizon.net Wed Apr 6 20:35:30 2005 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Thu, 07 Apr 2005 00:35:30 GMT Subject: sorting a list and counting interchanges References: <1112826641.728979.278530@f14g2000cwb.googlegroups.com> Message-ID: [RickMuller] > I have to sort a list, but in addition to the sorting, I need to > compute a phase factor that is +1 if there is an even number of > interchanges in the sort, and -1 if there is an odd number of > interchanges. This sounds like a homework problem but will offer a solution anyway: >>> phase = 1 >>> def mycmp(x, y): global phase phase = -phase return cmp(x, y) >>> sorted('abracadabra', cmp=mycmp) ['a', 'a', 'a', 'a', 'a', 'b', 'b', 'c', 'd', 'r', 'r'] >>> phase -1 Raymond Hettinger From t.bettio at transnorm.ch Thu Apr 14 14:44:13 2005 From: t.bettio at transnorm.ch (Tiziano Bettio) Date: Thu, 14 Apr 2005 20:44:13 +0200 Subject: Socket Error In-Reply-To: <1113503903.874232.322370@o13g2000cwo.googlegroups.com> References: <1113503903.874232.322370@o13g2000cwo.googlegroups.com> Message-ID: <425EB9FD.3020409@transnorm.ch> kingofearth.com at gmail.com wrote: >When I try to open a socket with python i get the following error: > >Traceback (most recent call last): > File "./mailer", line 3, in ? > sock = socket.socket(socket.PF_INET, socket.SOCK_STREAM) >NameError: name 'socket' is not defined > >the code is: > >#!/usr/bin/python > >sock = socket.socket(socket.PF_INET, socket.SOCK_STREAM) >sock.connect(("mail.oasd.k12.wi.us", 25)) >sock.send("HELO") >print sock.recv(8192) >sock.close() > > > tried: import socket ??? From michael.kearns at REMOVEsaaconsultants.com Tue Apr 12 04:56:07 2005 From: michael.kearns at REMOVEsaaconsultants.com (Michael Kearns) Date: Tue, 12 Apr 2005 09:56:07 +0100 Subject: Python 2.4 killing commercial Windows Python development ? In-Reply-To: <1113264839.497914.210170@z14g2000cwz.googlegroups.com> References: <1113264839.497914.210170@z14g2000cwz.googlegroups.com> Message-ID: <425b8cf7$0$38043$bed64819@news.gradwell.net> A.B., Khalid wrote: > Kindly note that the Python source distribution does include project > files for building Python 2.4 with MSVC6. Add to that the fact that > with pyMinGW[1] one can build yet another Windows distribution not > dependent on mscvr71.dll and some of the logic about not upgrading to > Python 2.4, IMHO, just goes away. > > An official release of installers for either or both versions would I > think complicate matters: more choices translate to more confusion. > Needless to say that extension authors (for Python 2.4) would then need > to make two binaries for every extension they release for Python 2.4: > one for the mscvr71.dll dependent Python distribution, and another one > for the mscvrt.dll dependent version(s). This I think would hurt Python > and its users. > > The solution is to have those that know enough to really need to build > Python on their own according to their requirments. They would then > have to deal with compiling the Python 2.4 extensions themselves, of > course. But this would make things simple and hopefully address the > needs of everyone. This is all very true, and a fair point of what is achievable. It just seems unfortunate that a developer is required to get involved in C compilation and looking after all module dependencies, purely to use Python in a commercial environment. I write Java as my main language. It's what I'm paid to do, and I've spent the best part of the last 8 years doing so. Over the last couple of years, I've been toying with Python, and trying to find ways to integrate it with my daily routine - I now have a complete internal build system written with it, along with several utility scripts. I don't code C. I could probably blag it at a very slow pace, but I'm not going to be given time to play with it. We have some C developers, but again, no resource allocation will ever be made to compile a language that isn't used for the mainstream software we produce. All I'm trying to do is use python wherever I can without having to persuade those in power that it would be a valuable asset (as this would probably be a waste of breath in many circumstances), and yet I can't (from 2.4 at least) because it requires more time and cost to be allocated. I would guess from the responses so far that Python 2.4 just isn't used within commercially shipping products, or is quietly used by an product so as not to incur any legal wrath that might be found. Perhaps it isn't quite ready for what I want to achieve. I don't know. I just know that I am spending the rest of the day migrating back to 2.3 where I will stay. Michael. From nyamatongwe+gravity at gmail.com Wed Apr 27 21:56:16 2005 From: nyamatongwe+gravity at gmail.com (Neil Hodgson) Date: Thu, 28 Apr 2005 01:56:16 GMT Subject: win32ui CreateFileDialog SLOW (since the SP2 Windows XP patch?) References: <1114644362.619393.317800@l41g2000cwc.googlegroups.com> Message-ID: Kitty: > Now it can take up to 4 minutes for the file dialog box to appear. No > problems with speed in PythonWin, of course, but she is not used to > doing that. Any suggestions? Anyone know why it is so slow? I have seen similar issues in the past but mainly on Windows 9x with particular start directories for the dialog. Windows tries to remember which directory was most recently chosen by each application. Possibly it has associated python.exe with a directory on a removed drive, network share, or virtual location (like "My Network Places") and takes a while to fail over to a working place. Neil From ruach at chpc.utah.edu Fri Apr 8 13:41:51 2005 From: ruach at chpc.utah.edu (Matthew Thorley) Date: Fri, 08 Apr 2005 11:41:51 -0600 Subject: Can dictionary values access their keys? In-Reply-To: References: Message-ID: Steve Holden wrote: while not impossible (using Python's excellent > introspection facilities) is way beyond what most people would consider > practical. Obviously the garbage collector has to solve this problem, > but you *really* don't want to be doing this stuff in Python unless you > absolutely *must*. > > regards > Steve Thanks very much for the detailed reply. Let me explain in a little more detail what I am doing, and perhaps you could let me know if I am going about it the wrong way. I am creating an object database to store information about network devices, e.g. switches and routers. At the top level there are device objects, every device object contains a mib object--and other various properties--where the actual data is stored. The mib object is a dicitionary--or at least subclasses dictionary--where the key is the oid (a unique string) and the value is a special object called Datapoint. Datapoints come in two types Static and Dynamic, and every Datapoint is unique. So a simple structure looks something like this: Device1 Mib1 {'1.3.6.1':Datapoint-x1, '1.3.6.2':Datapoint-y1, '1.1.5.4':Datapoint-z1, '1.2.7.3':Datapoint-q1} Device2 Mib2 {'1.3.6.1':Datapoint-x2, '1.3.6.2':Datapoint-y2, '1.1.5.4':Datapoint-z2, '1.2.7.3':Datapoint-q2} In the example Datapoint-xx should be read as, some unique data point in memory. The key in the Mib object is important because it is used by the Datapoint is points to to look up its current value on the given device, which is why I asked the two questions. In my program I use snmp to look up values on network devices. i.e. 'Go find the value of 1.3.6.1 from device1.' I want to be able to say something like Device1.Mib['1.3.6.1].update(), and the correct Datapoint discovers its key (oid) and parent device, then executes an snmp query that looks something like this snmpget(keyThatPointsToSelf, parentObj.ipAddress, parentObj.paramx) I know of course I could keep all this in a relational database and do a bunch of queries, but that would really suck! and I would have to track all the Devices and oids my self. What I really want is smart objects that think for me--thats what computers are for, right? ;) I thought my design was a wonderfuly beautiful use of python an oop, but perhaps I am mistaken and there is a much more pragmatic way to get the job done. In the end preformance doesn't matter a lot. The front end will be web based, so if the db can process faster than http/javascript and user Bob who has to mouse, then everything will be fine. Let me know what you think Thanks much --Matthew From simon.brunning at gmail.com Wed Apr 6 10:01:48 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Wed, 6 Apr 2005 15:01:48 +0100 Subject: shebang in cross platform scripts In-Reply-To: References: Message-ID: <8c7f10c605040607015d7cb7d5@mail.gmail.com> On Apr 6, 2005 2:37 PM, rbt wrote: > Does the line below have any negative impact on Windows machines? I > develop and test mostly on Unix, but my scripts are often used on Win > systems too. > > #!/usr/bin/env python Nope. On Windows it's just a comment. -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From bvande at po-box.mcgill.ca Sat Apr 16 15:27:25 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat, 16 Apr 2005 15:27:25 -0400 Subject: pydoc preference for triple double over triple single quotes -- any reason? Message-ID: <4261671D.7080404@po-box.mcgill.ca> Hi all, I'm posting partly so my problem and solution might be more easily found by google, and partly out of mere curiosity. I've just spent a frustrating bit of time figuring out why pydoc didn't extract a description from my module docstrings. Even though I had a well formed docstring (one line, followed by a blank line, followed by the rest of the docstring), when I ran Module docs, my modules showed up as having "no description". ("Module docs" referring to the shortcut installed on Windows that launches the pydoc server.) It turns out that I was using '''triple single quotes''' and pydoc only pulls a description out from module docstrings that are formatted in """triple double quotes""". I've poked about with google, and cannot find any explanation of why pydoc should treat the two cases differently. Anyone have an idea? I do see that both -- Style Guide for Python Code and -- Docstring Conventions suggest triple double, so I guess it is my fault. But still, those PEP's have the tone of suggestions, and since the two quoting schemes are semantically equivalent . . . I do prefer the look of triple-single, but oh well. My attempts to google for an answer didn't come up with anything, so perhaps this post will help someone else, if nothing else :-) Best to all, Brian vdB From nyamatongwe+gravity at gmail.com Wed Apr 20 09:17:15 2005 From: nyamatongwe+gravity at gmail.com (Neil Hodgson) Date: Wed, 20 Apr 2005 13:17:15 GMT Subject: To decode the Subject =?iso-8859-2?Q?=... in email in python References: <1113982235.201423.32480@l41g2000cwc.googlegroups.com> Message-ID: Dan Polansky: > When parsing messages using python's libraries email and mailbox, the > subject is often encoded using some kind of = notation. Apparently, the > encoding used in this notation is specified like =?iso-8859-2?Q?=... or > =?iso-8859-2?B?=. Is there a python library function to decode such a > subject, returning a unicode string? The use would be like > > human_readable = cool_library.decode_equals(message['Subject']) Here is some code from a front end to Mailman moderation pages: import email.Header hdr = email.Header.make_header(email.Header.decode_header(sub)) Neil From artiegold at austin.rr.com Sat Apr 2 23:28:27 2005 From: artiegold at austin.rr.com (Artie Gold) Date: Sat, 02 Apr 2005 22:28:27 -0600 Subject: Lambda: the Ultimate Design Flaw In-Reply-To: <87is3663cn.fsf@wilson.rwth-aachen.de> References: <87is3663cn.fsf@wilson.rwth-aachen.de> Message-ID: <3b99ncF6fd2apU1@individual.net> Torsten Bronger wrote: > Hall?chen! > > Daniel Silva writes: > > >>Shriram Krishnamurthi has just announced the following elsewhere; it might >>be of interest to c.l.s, c.l.f, and c.l.p: >>http://list.cs.brown.edu/pipermail/plt-scheme/2005-April/008382.html >> >> >> The Fate Of LAMBDA in PLT Scheme v300 >> or >> Lambda the Ultimate Design Flaw >> >>About 30 years ago, Scheme had FILTER and MAP courtesy of Lisp >>hackers who missed them from their past experience. To this >>collection, Scheme added a lexically-scoped, properly-functioning >>LAMBDA. But, despite of the PR value of anything with Guy >>Steele's name associated with it, we think these features should >>be cut from PLT Scheme v300. >> >>[...] > > > The whole text seems to be a variant of > . > > Tsch?, > Torsten. > Ya think? ;-) --ag -- Artie Gold -- Austin, Texas http://it-matters.blogspot.com (new post 12/5) http://www.cafepress.com/goldsays From jeffrey at fro.man Fri Apr 8 10:44:52 2005 From: jeffrey at fro.man (Jeffrey Froman) Date: Fri, 08 Apr 2005 07:44:52 -0700 Subject: compound strip() string problem References: Message-ID: <115d67dq70ht7d8@corp.supernews.com> Dylan Wilson wrote: > Now i need to compond that string remove the whitespace if you will.Well > i read up on strip(), lstrip() and rstrip() and all i could deduce was > that they striped the whitespace from the start and/or end of the > string.But I tried that anyway and failed.Is there an easier way than i > did it below? As Sidharth Kuruvila pointed out, time.strftime() is probably the best choice for your situation. For the general case of removing whitespace from a sting, one method is: ''.join(mystring.split()) Jeffrey From roy at panix.com Fri Apr 22 08:37:51 2005 From: roy at panix.com (Roy Smith) Date: Fri, 22 Apr 2005 08:37:51 -0400 Subject: Regular Expressions - Python vs Perl References: <1114092105.964664.211430@l41g2000cwc.googlegroups.com> Message-ID: iny+news at iki.fi (Ilpo Nyyss?nen) wrote: > Of course it caches those when running. The point is that it needs to > recompile every time you have restarted the program. With short lived > command line programs this really can be a problem. Are you speculating that it might be a problem, or saying that you have seen it be a problem in a real-life program? I just generated a bunch of moderately simple regexes from a dictionary wordlist. Looks something like: Roy-Smiths-Computer:play$ head exps a.*a[0-9]{34} a.*ah[0-9]{34} a.*ahed[0-9]{34} a.*ahing[0-9]{34} a.*ahs[0-9]{34} a.*al[0-9]{34} a.*alii[0-9]{34} a.*aliis[0-9]{34} a.*als[0-9]{34} a.*ardvark[0-9]{34} Then I ran them through a little script that does: for exp in sys.stdin.readlines(): regex = re.compile (exp) and timed it for various numbers of lines. On my G4 Powerbook (1 GHz PowerPC), I'm compiling about 1000 regex's per second: Roy-Smiths-Computer:play$ time head -5000 < exps | ./regex.py real 0m5.208s user 0m4.690s sys 0m0.090s So, my guess is that unless you're compiling 100's of regexes each time you start up, the one-time compilation costs are probably not significant. > And yes, I have read the source of sre.py and I have made an ugly > module that digs the compiled data and pickles it to a file and then > in next startup it reads that file and puts the stuff back to the > cache. That's exactly what I would have done if I really needed to improve startup speed. In fact, I did something like that many moons ago, in a previous life. See R. Smith, "A finite state machine algorithm for finding restriction sites and other pattern matching applications", CABIOS, Vol 4, no. 4, 1988. In that case, I had about 1200 patterns I was searching for (and doing it on hardware running about 1% of the speed of my current laptop). BTW, why did you have to dig out the compiled data before pickling it? Could you not have just pickled whatever re.compile() returned? From simon.brunning at gmail.com Mon Apr 4 06:28:03 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Mon, 4 Apr 2005 11:28:03 +0100 Subject: Raise Error in a Module and Try/Except in a different Module In-Reply-To: <7f285d16.0504040211.1e1b8783@posting.google.com> References: <7f285d16.0504040211.1e1b8783@posting.google.com> Message-ID: <8c7f10c60504040328676e5539@mail.gmail.com> On 4 Apr 2005 03:11:23 -0700, Issa-Ahmed SIDIBE wrote: > I Have a function FUNC1 that is define in ModuleA. This function raise > an exception EXCP1 (raise EXCP1), with EXCP1 a global variable in > ModuleA. > > In ModuleB, I have some classes that call FUNC1. I would like to catch > EXCP1 and make some processing. How can I do that. > > I tried in Module B > > import ModuleA > ... > class(): > ... > try: a = ModuleA.FUNC1 > except ModuleA.EXCP1: print 'catch' > > But It does not work. What is wrong? You're not *calling* FUNC1 here, you're just assigning a reference to it to the name 'a'. Try FUNC1() instead. -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From tjreedy at udel.edu Fri Apr 1 13:32:21 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 1 Apr 2005 13:32:21 -0500 Subject: Ternary Operator in Python References: <20050401072442.73412.qmail@web8408.mail.in.yahoo.com> Message-ID: "praba kar" wrote in message news:20050401072442.73412.qmail at web8408.mail.in.yahoo.com... > Dear All, > I am new to Python. I want to know how to > work with ternary operator in Python. I cannot > find any ternary operator in Python. So Kindly > clear my doubt regarding this A unary operator has one operand; a binary operator has two operands; a ternary operator has three operands. Python has none built-in, although one can 'synthesize' all sorts of ternary operators by combining two binary operators, with the operand of one being the result of the other. However, people often don't think of such combinations as being such. Since C has one builtin ternary 'operator' (if-else), the term 'ternary operator' is too often used as a synonym for that particular example of a ternary operator. Others have referred you to discussions of if-else expressions in Python. Ironically, if one thinks of or defines an operator as being a function called without parenthesis, then C's ';:' and Python's 'and..or' are not really ternary operators but flow control expressions equivalent in effect to certain if/else statement pairs. That is because some of the operands may not be evaluated. That is also why there are no special methods corresponding to 'and' and 'or'. They are directly compiled to conditional code with no a function call corresponding to the 'operator'. Terry J. Reedy From rkern at ucsd.edu Thu Apr 14 06:20:02 2005 From: rkern at ucsd.edu (Robert Kern) Date: Thu, 14 Apr 2005 03:20:02 -0700 Subject: Python license (2.3) In-Reply-To: References: Message-ID: Antoon Pardon wrote: > Op 2005-04-14, Robert Kern schreef : > >>Antoon Pardon wrote: >> >>>Op 2005-04-14, Robert Kern schreef : >>> >>> >>>>Antoon Pardon wrote: >>>> >>>> >>>>>Op 2005-04-13, Robert Kern schreef : >>>>> >>>>>I would do that if I were just writing code I thought others could >>>>>find usefull. I then would feel no problem "burdening" those users >>>>>with the same kind of license I found in the product I took some >>>>>code from. But I also think that readers of documentation should >>>>>be free to use any code included in any way they see fit. >>>> >>>>If they have issues with distributing code derived from Python, why are >>>>they reading a Python tutorial? >>> >>> >>>Try and look it from a students viewpoint. He is learing languages, >>>algorithms and so on. Now he is ready to write his own program. >>>Chances are high that he will rely on examples from the >>>courses/documentation he read. It is just not practical for someone >>>like that to figure out all the possible different licenses under >>>which he can use the examples from the various documenation sources. >> >>The PSF License is about as light as they come. >> >> >>>Now if this documentation refers to code from yet another source >>>with its own license, using it becomes an utter nightmare for >>>the student, because now he has to figure out which piece of >>>the code is original from the author of the documentation and >>>which was copied from the other source. >> >>Then write your own code and don't use anyone else's. You can't offer >>extra permissions for code that's not yours. > > > Well then I'll just have to do that. > > >>>Consideration like this, let me come to the conclusion that >>>code included with documentation should come with no strings >>>attached for the students to reuse. >> >>No such thing, really. Copyright law requires almost as much as the PSF >>license. The MIT license is shorter, possibly more easily >>understandable, but practically amounts to more-or-less the same thing. > > > If I read a tutorial or a course on algorithms both with examples. > Does copyright law require that I attribute if I reuse code > from these examples? If the amount copied is large enough. > Even if it was pseudo code that I had > to translate in an actual language. Probably not. Copyright controls copying (and a few other things, but they have less relevance in a software context). > Suppose some time has passed and I have to write similar code. > I cant find the documentation but this time I'm experienced > enough so that I can recreate the code. Do I still need to > attribute the code? Again, probably not. > What if the code is so short that basically everyone that > solves the problem writes the same kind of code? No, copyright requires creativity. Rosen's book should answer these questions for you. >>In short, don't worry about it. Don't sue people, keep the attributions >>intact, and probably no one will care. Sorry, that list should also have had "follow courteous practices with other people's code" which includes listing changes and a reference to the license of that code. > If they don't care, why did they attach such a license in the first > place. Lawyers. The original license (the "CNRI License") was much briefer and vaguer, although it amounts to the same requirements, practically. The PSF license made those requirements, disclaimers, etc. explicit. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From tim.leeuwvander at nl.unisys.com Mon Apr 11 03:45:08 2005 From: tim.leeuwvander at nl.unisys.com (Tim N. van der Leeuw) Date: 11 Apr 2005 00:45:08 -0700 Subject: PyWin32 COM mailing list / web forum? Message-ID: <1113205508.055046.276360@f14g2000cwb.googlegroups.com> Hi, I have some questions specifically about python win32com extensions, and I thought it might be more appropriate to ask them on a mailing list / newsgroup / webforum etc. dedicated to that. But is there such a thing anywhere? I couldn't find links to it from the pywin32 homepage or sourceforge-page. Cheers, --Tim From edcjones at comcast.net Sun Apr 10 12:10:17 2005 From: edcjones at comcast.net (Edward C. Jones) Date: Sun, 10 Apr 2005 12:10:17 -0400 Subject: numarray.array can be VERY slow Message-ID: #! /usr/bin/env python """Should this program take 4.3 seconds to run? I have a Linux PC with an AMD Athlon XP 2000+ chip (1.7Gh). I use Python 2.4.1 and numarray 1.2.3, both compliled from source.""" import time, numarray from numarray.numerictypes import * nested = [] for i in range(8): inner = [] for j in range(8): inner.append(numarray.ones((256,256), Float64)) nested.append(inner) t = time.clock() arr = numarray.array(nested) print time.clock() - t From vze4rx4y at verizon.net Tue Apr 5 09:13:21 2005 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Tue, 05 Apr 2005 13:13:21 GMT Subject: StopIteration in the if clause of a generator expression References: <424db34c.51543105@news.oz.net> <_2R3e.3341$7b.3033@trndny06> Message-ID: > > [Steven Bethard] > > > So do I read this right in preferring > > > [ for in ] > > > over > > > list( for in ) [Raymond Hettinger] > > Yes! [Simon Brunning] > Why? (Serious question. I'm sure that you have a good reason - I just > can't figure out what it is.) > > The generator expression has the advantage of not leaking references > into the enclosing namespace. What's advantage of the list comp? One advantage relates to mental parsing and chunking. A list comp reads as a single step: "make a list". The genexp form reads as "make a generator and turn it into a list." The listcomp form has slightly more economy of expression (it is succinct) and the brackets are a nice visual cue that may save a neuron or two. Another advantage is that listcomps are older. They tend to be better understood already. And, they run on older pythons. The design rule, "use listcomps to make lists and genexps to make generators", encourages data centric thinking.With being distracting, it helps maintain an awareness of whether you're filling memory or generating elements one-at-a-time. Internally, there are performance differences favoring listcomps when the desired output is a list. List comprehensions are interpreted immediately through syntax rather than a global lookup of the list() builtin. The code for listcomps does not have to create, switch between, and destroy a separate stackframe. The compiler creates custom code for list comps that takes advantage of the new LIST_APPEND opcode. Partially balancing out all of the above are some small advantages for the list(somegen) form. It lets you forget about listcomps and it works with other contructors, deque(somegen) or set(somegen) for example. To my tastes, the net balance favors using listcomps whenever you need to create a list. Raymond Hettinger From littlejohn.75 at news.free.fr Tue Apr 19 14:31:46 2005 From: littlejohn.75 at news.free.fr (F. Petitjean) Date: 19 Apr 2005 18:31:46 GMT Subject: XML-RPC -- send file References: <1113921569.905111.155230@f14g2000cwb.googlegroups.com> <1113930209.259905.112850@o13g2000cwo.googlegroups.com> <1113933767.439552.169130@g14g2000cwa.googlegroups.com> Message-ID: <42654e90$0$20628$626a14ce@news.free.fr> Le 19 Apr 2005 11:02:47 -0700, codecraig a ?crit : > Experient I have been :) > > Here is what I am getting now.... > > CLIENT > ----------- > d = xmlrpclib.Binary(open("C:\\somefile.exe").read()) open the file with mode "rb" fin = open(r'C:\somefile.exe', 'rb') contents = fin.read() fin.close() d = xmlrpclib.Binary(contents) > server.sendFile(d) > > any ideas? > From ojokimu at yahoo.co.uk Mon Apr 4 20:13:47 2005 From: ojokimu at yahoo.co.uk (John Ridley) Date: Tue, 5 Apr 2005 01:13:47 +0100 (BST) Subject: Super Newbie Question Message-ID: <20050405001347.48469.qmail@web26801.mail.ukl.yahoo.com> --- John Ridley blurted: > I suppose the simplest thing to do would be to write an empty string > to the file: > > >>> f = open('tmpfile.txt', 'w') > >>> f.write('') > >>> f.close() # or f.flush(), if keeping open Apologies - this is, of course, nonsense. Time for me to hit the sack, I think... John Ridley Send instant messages to your online friends http://uk.messenger.yahoo.com From bvande at po-box.mcgill.ca Tue Apr 12 11:23:16 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Tue, 12 Apr 2005 11:23:16 -0400 Subject: [OT] Re: Programming Language for Systems Administrator In-Reply-To: <1113307867.975905.300380@l41g2000cwc.googlegroups.com> References: <1113253691.821235.9750@o13g2000cwo.googlegroups.com> <1113307867.975905.300380@l41g2000cwc.googlegroups.com> Message-ID: <425BE7E4.6020400@po-box.mcgill.ca> beliavsky at aol.com said unto the world upon 2005-04-12 08:11: > I actually like the Windows cmd language (it's an acquired taste), but > I have read it is going away in Windows Longhorn (WH). That's an > argument for writing more complicated scripts in Python. WH is supposed > to get a much better shell, called Monad, inspired by the philosophy of > Gottfried Wilhelm Leibniz :). Hi all, this is the first I've heard of Monad. Leibniz characterized his monads as the fundamental building blocks of nature, insusceptible of change from the outside, and as "windowless". So, if the account of MS's plans is true, it would seem to indicate a combination of arrogance, honesty, and ignorance. (I leave it to you to decide which part, if any, of this triad, is surprising.) Best to all, Brian vdB From spiralx at gmail.com Tue Apr 19 06:29:51 2005 From: spiralx at gmail.com (James) Date: Tue, 19 Apr 2005 11:29:51 +0100 Subject: Why does python class have not private methods? Will this neverchanged? In-Reply-To: References: <311b5ce105041902165a0969a0@mail.gmail.com> Message-ID: <7ee3dcd805041903294341f5ba@mail.gmail.com> Trolls? On 4/19/05, Fredrik Lundh wrote: > "could ildg" wrote: > > > Private stuff always makes programming much easier. > > says who? > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From tjreedy at udel.edu Fri Apr 8 18:16:01 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 8 Apr 2005 18:16:01 -0400 Subject: Thoughts on some stdlib modules References: Message-ID: "vegetax" wrote in message news:d35hul$o4p$1 at sea.gmane.org... > And those thoughts comes to mind again, if python is such a great > language > why does the stdlib is so bloated with duplication,bad bad library > design,clumsy to use modules,etc. Some general responses: 1. The Python lib was not 'designed'. It has grown over 15 years by contributions from numerous authors around the world. 2. Backwards compatibility is a near absolute constraint. The major exception is code dependent on bugs. 3. Enhancing the lib, within that constraint, is a major focus of current development work. (Fixing bugs is another, but that is constant.) But many patches languish because there are not enough volunteers to review them. 4. I believe acceptance of new modules is tougher now than some years ago. 5. More help is needed to improve the lib. Are you volunteering? >Is it because of legacy code and backwards compatibility or > because not too much people in the python-dev cares about library design? I hope I answered that for you. > Are those issues being considered right now? i cant find any PEP > addressing > the issue especifically, at least cooking it for python 3000. > > specific topics could be: > > grouping related modules. I would like this and others have said the same. Not sure what Guido thinks. > removing useless legacy modules. like gopherlib? But how do we know that none of the 100000s of Python programmers use it? Any effort to find out is more effort than leaving it alone. And if the number is greater than 0, how many are you willing to disappoint and say 'Tough' to? > refactoring duplicated functionality. > removing/redesigning poorly written modules. Patches welcome within the compatibility constraint. > adding a module versioning system. Modules that began and continue as independent projects may have such already. Otherwise, they get the CPython version number. Or did you mean something else? There are Python 3 topics in the Python wiki that you could add to. Or go ahead and write a PEP, Terry J. Reedy From rune.strand at gmail.com Fri Apr 29 10:05:07 2005 From: rune.strand at gmail.com (runes) Date: 29 Apr 2005 07:05:07 -0700 Subject: Getting PID for process In-Reply-To: References: <1114770926.016150.181310@l41g2000cwc.googlegroups.com> Message-ID: <1114783507.027246.152720@l41g2000cwc.googlegroups.com> On XP/2003 at least, os.system('taskkill /pid le ') will do. From greg at cosc.canterbury.ac.nz Wed Apr 13 23:59:35 2005 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Thu, 14 Apr 2005 15:59:35 +1200 Subject: Programming Language for Systems Administrator In-Reply-To: References: <1113253691.821235.9750@o13g2000cwo.googlegroups.com> Message-ID: <3c685iF6jaogjU1@individual.net> Peter Maas wrote: > > This is only true for trivial bash scripts. I have seen bash scripts > which were quite hard to read especially for beginners. I've seen shell scripts which are quite hard to read even for experts! -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From harlinseritt at yahoo.com Sat Apr 23 05:49:16 2005 From: harlinseritt at yahoo.com (Harlin Seritt) Date: 23 Apr 2005 02:49:16 -0700 Subject: Question Regarding PIL and PhotoImage classes Message-ID: <1114249756.229138.204300@l41g2000cwc.googlegroups.com> Why is that I can only get the PhotoImage class to show up when I write a straight procedural script (no object orientation) but not when I try to use object-orientation? These two scripts in theory should produce the same results but they don't. Is there any reason why? ---Procedural--- root = Tk() im = Image.open('image.gif') photo = ImageTk.PhotoImage(im) label = Label(image=photo) label.pack() root.mainloop() ---Object-Oriented--- from Tkinter import * import Image, ImageTk class App: def __init__(self, master): im = Image.open('dellserver.gif') photo = ImageTk.PhotoImage(im) label = Label(master, image=photo) label.pack() if __name__ == '__main__': root = Tk() app = App(root) root.mainloop() ---END of CODE--- Thanks, Harlin Seritt From miki.tebeka at zoran.com Mon Apr 25 07:09:53 2005 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Mon, 25 Apr 2005 14:09:53 +0300 Subject: Changing a line in a text file In-Reply-To: <1114421951.029066.190120@g14g2000cwa.googlegroups.com> References: <1114421951.029066.190120@g14g2000cwa.googlegroups.com> Message-ID: <20050425110953.GI3652@zoran.com> Hello kah, > How do I change a line in a file?? > > For example I have the follwing text in my file: > > line1 > line2 > line3 > line4 > > How do I replace 'line2' with 'newline'. Since the write operation in > python will overwrite everything. See http://docs.python.org/lib/module-fileinput.html (inplace=1 is what you want). Bye. -- ------------------------------------------------------------------------ Miki Tebeka http://tebeka.bizhat.com The only difference between children and adults is the price of the toys -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 193 bytes Desc: not available URL: From dave at pythonapocrypha.com Thu Apr 14 11:03:52 2005 From: dave at pythonapocrypha.com (Dave Brueck) Date: Thu, 14 Apr 2005 09:03:52 -0600 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Apr 11) In-Reply-To: References: Message-ID: <425E8658.8020300@pythonapocrypha.com> Roel Schroeven wrote: > Simon Brunning wrote: >>... > > Not that it really matters, but does anybody know why the weekly Python > news always arrives twice? Does it only happen to me, or does it happen > to others too? > > It's not that it irritates me or anything, I'm just being curious. I just thought it was for emphasis. -Dave From apardon at forel.vub.ac.be Thu Apr 21 06:48:18 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 21 Apr 2005 10:48:18 GMT Subject: Why Python does *SLICING* the way it does?? References: <1113976729.450677.261130@o13g2000cwo.googlegroups.com> <_Lm9e.23143$Xm3.17864@trndny01> <1114003997.778676.144950@z14g2000cwz.googlegroups.com> Message-ID: Op 2005-04-21, Steve Holden schreef : > beliavsky at aol.com wrote: >> Terry Hancock wrote: >> >> >> >>>So I like Python's slicing because it "bites *less*" than intervals >> >> in C or Fortran. >> >> I disagree. Programming languages should not needlessly surprise >> people, and a newbie to Python probably expects that x[1:3] = >> [x[1],x[2],x[3]] . Array-oriented languages, such as Fortran 90/95, >> Matlab/Octave/Scilab, and S-Plus/R do not follow the Python convention, >> and I don't know of Fortran or R programmers who complain (don't follow >> Matlab enough to say). There are Python programmers, such as the OP and >> me, who don't like the Python convention. What languages besides Python >> use the Python slicing convention? >> > The principle of least surprise is all very well, but "needless surprise > of newbies" is a dangerous criterion to adopt for programming language > design and following it consistently would lead to a mess like Visual > Basic, which grew by accretion until Microsoft realized it was no longer > tenable and broke backward compatibility. >> Along the same lines, I think the REQUIREMENT that x[0] rather than >> x[1] be the first element of list x is a mistake. At least the >> programmer should have a choice, as in Fortran or VBA. In C starting at >> 0 may be justified because of the connection between array subscripting >> and pointer arithmetic, but Python is a higher-level language where >> such considerations are less relevant. >> > But Pythonicity required that there should be one obvious way to do > something. How obvious is having two ways? How obvious is that lists can be any length? Do you consider it an unbounded number of ways, that lists can be any length? Like users have a choice in how long they make a list, they should have a choice where the indexes start. (And that shouldn't be limited to 0 and 1). > Then when you read code you > would continually be asking yourself "is this a one-based or a > zero-based structure?", which is not a profitable use of time. No you wouldn't. If you have the choice you just take the start index that is more natural. Sometimes that is 0 sometimes that is 1 and other times it is some whole other number. The times I had the opportunity to use such structures, the question of whether it was zero-based or one-based, rarely popped up. Either it was irrelevant or it was clear from what you were processing. That you are forced to use zero-based structures, while the problem space you are working on uses one-based structures is a far bigger stumbling block where you continually have to be aware that the indexes in your program are one off from the indexes the problem is expressed in. The one obvious way is to use the same index scheme as the one that is used in the specification or problem setting. Not to use always zero no matter what. -- Antoon Pardon From gsakkis at rutgers.edu Mon Apr 25 22:37:45 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 25 Apr 2005 19:37:45 -0700 Subject: Quote-aware string splitting In-Reply-To: <87oec2e1qa.fsf@mrbun.watterson> References: <9Kgbe.24031$h6.523@tornado.texas.rr.com> <87oec2e1qa.fsf@mrbun.watterson> Message-ID: <1114483065.551933.68460@f14g2000cwb.googlegroups.com> > "J. W. McCall" writes: > > > > I need to split a string as per string.strip(), but with a > > modification: I want it to recognize quoted strings and return them as > > one list item, regardless of any whitespace within the quoted string. > > > > For example, given the string: > > > > 'spam "the life of brian" 42' > > > > I'd want it to return: > > > > ['spam', 'the life of brian', '42'] > > > > I see no standard library function to do this, so what would be the > > most simple way to achieve this? This should be simple, but I must be > > tired as I'm not currently able to think of an elegant way to do this. > > > > Any ideas? > > How about the csv module? It seems like it might be overkill, but it > does already handle that sort of quoting > > >>> import csv > >>> csv.reader(['spam "the life of brian" 42'], delimiter=' ').next() > ['spam', 'the life of brian', '42'] > I don't know if this is as good as CSV's splitter, but it works reasonably well for me: import re regex = re.compile(r''' '.*?' | # single quoted substring ".*?" | # double quoted substring \S+ # all the rest ''', re.VERBOSE) print regex.findall(''' This is 'single "quoted" string' followed by a "double 'quoted' string" ''') George From matthew_shomphe at countrywide.com Thu Apr 14 20:48:31 2005 From: matthew_shomphe at countrywide.com (Matt) Date: 14 Apr 2005 17:48:31 -0700 Subject: Socket Error In-Reply-To: <1113509426.452739.166010@z14g2000cwz.googlegroups.com> References: <1113503903.874232.322370@o13g2000cwo.googlegroups.com> <1113509426.452739.166010@z14g2000cwz.googlegroups.com> Message-ID: <1113526111.194220.126160@o13g2000cwo.googlegroups.com> kingofearth.... at gmail.com wrote: > Thanks everybody, it works now. I thought I needed to do something like > that but it didn't show it in the tutorial so I decided to ask here. Where was the tutorial? If it's in the Python docs, perhaps you could submit a patch to fix it ... ;-) M@ From bucknuggets at yahoo.com Tue Apr 12 13:06:40 2005 From: bucknuggets at yahoo.com (Buck Nuggets) Date: 12 Apr 2005 10:06:40 -0700 Subject: Programming Language for Systems Administrator References: <1113253691.821235.9750@o13g2000cwo.googlegroups.com> <1113311618.838281.205380@l41g2000cwc.googlegroups.com> <2ctn519amssrp10m6ulo5bkakc6vrv6537@4ax.com> Message-ID: <1113325600.436778.302960@o13g2000cwo.googlegroups.com> >> I also tried SAP-DB before. > Now known as (or was, last time I checked) "MaxDB by MySQL" and formerly known as the pre-relational dbms 'Adabas'. I think the only reason for its continued existance is that SAP was hoping for a very low cost, low-end database years ago. However, the database world has changed substantially over the last ten years: you can get postgresql and firebird for nothing, and db2 & oracle are often under $1000 for a small server. With that in mind I can't think of a database that's more of a has-been than maxdb. Maybe something from the 70s like IMS-DB or Model 204? buck From Please Wed Apr 27 19:42:02 2005 From: Please (Please) Date: 27 Apr 2005 18:42:02 -0500 Subject: =?iso-8859-1?q?Good_morning_or_good_evening_depending_upon_yo?= =?iso-8859-1?q?ur_location=2E_I_want_to_ask_you_the_most_important_questi?= =?iso-8859-1?q?on_of_your_life=2E_Your_joy_or_sorrow_for_all_eternity_dep?= =?iso-8859-1?q?ends_upon_your_answer=2E_The_question_is=3A_Are_you_saved?= =?iso-8859-1?q?=3F_It_is_not_a_question_of_how_good_you_are=2C_nor_if_you?= =?iso-8859-1?q?_are_a_church_member=2C_but_are_you_saved=3F_Are_you_sure_?= =?iso-8859-1?q?you_will_go_to_Heaven_when_you_die=3F_GOOGLE=B7NEWSGROUP?= =?iso-8859-1?q?=B7POST=B7151?= References: <1114640110.171596.223260@g14g2000cwa.googlegroups.com> Message-ID: <2g8071h8e3np64c0tccf8053torm33p8te@4ax.com> Reports to groups-abuse at google.com, abuse at aol.net, domains at aol.net, abuse at yahoo.com, abuse at yahoo-inc.com And do not feed the troll! From ml at fgranger.com Fri Apr 15 05:17:03 2005 From: ml at fgranger.com (Fran=?ISO-8859-1?B?5w==?=ois Granger) Date: Fri, 15 Apr 2005 11:17:03 +0200 Subject: new to mac OS10 In-Reply-To: Message-ID: Le 15/04/05 1:54, ??Thomas Nelson?? a ?crit?: > I'm on a mac OS X (10.3.8), and I seem to have accidentally destroyed > the default python installation. How should I put it on? Do I need to > use the unix version? any help would be greatly appreciated. There is also a list dedicated to this version of Python: http://mail.python.org/mailman/listinfo/pythonmac-sig HTH From nick at craig-wood.com Mon Apr 18 07:30:03 2005 From: nick at craig-wood.com (Nick Craig-Wood) Date: 18 Apr 2005 11:30:03 GMT Subject: Compute pi to base 12 using Python? References: <1113390479.738210.49530@z14g2000cwz.googlegroups.com> <1113430615.592715.78440@f14g2000cwb.googlegroups.com> <1113495726.884203.326670@f14g2000cwb.googlegroups.com> Message-ID: mensanator at aol.com wrote: > Nick Craig-Wood wrote: > > mensanator at aol.com wrote: > > > I'm using GMPY (see code). > > [snip] > > > > If you are using gmpy you might as well do it like this..... > > > > gmpy.pi() uses the Brent-Salamin Arithmetic-Geometric Mean formula > > for > > pi IIRC. This converges quadratically, and it will calculate you a > > million places without breaking a sweat. > > It would be nice if that were documented. What do I have to do, go get > the documentation for the original GMP to find out what else is in GMPY > that they didn't include in the doc file? "pydoc gmpy" works for me. Not sure how you use pydoc on windows, but you can do this... >>> import gmpy >>> help(gmpy) Help on module gmpy: NAME gmpy FILE /usr/lib/python2.3/site-packages/gmpy.so [snip] Help on built-in function pi: pi(...) pi(n): returns pi with n bits of precision in an mpf object [snip] The original gmp documentation is sensible also, since gmpy is really just a thin wrapper to it. There is also the gmp source code too. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From removethis.kartic.krishnamurthy at gmail.com Mon Apr 25 19:13:14 2005 From: removethis.kartic.krishnamurthy at gmail.com (Kartic) Date: Mon, 25 Apr 2005 23:13:14 GMT Subject: Parsing data from URL In-Reply-To: <1114388658.276974.304720@f14g2000cwb.googlegroups.com> References: <1114388658.276974.304720@f14g2000cwb.googlegroups.com> Message-ID: "The Great 'Harlin Seritt' uttered these words" on 4/24/2005 8:24 PM: > How can I make sure that I get the actual html data instead of the data > from redirected URL? > > thanks, > > Harlin > Harlin, I am not sure I understand what you are asking but please see if the below mentioned link will help you. I am just sending the URL that I believe is relevant to you. You may want to read the entire chapter if you are interested. http://diveintopython.org/http_web_services/redirects.html (Dive into Python's Chapter 11.7. Handling redirects) Thanks, -Kartic From abuse at solumslekt.org Sat Apr 23 19:35:31 2005 From: abuse at solumslekt.org (Leif Biberg Kristensen) Date: Sun, 24 Apr 2005 01:35:31 +0200 Subject: Python or PHP? References: <1114254894.512656.297040@l41g2000cwc.googlegroups.com> Message-ID: <3d04e3F6pjhi5U1@individual.net> Leif K-Brooks skrev: > But Python's DB-API (the standard way to connect to an SQL database > from Python) makes escaping SQL strings automatic. You can do this: > > cursor.execute('UPDATE foo SET bar=%s WHERE id=%s', ["foo'bar", 123]) So. I've been writing SQL queries in Python like this, using PostgreSQL and psycopg: cursor.execute("select * from foo where bar=%s" % baz) Is that wrong, and how should I have been supposed to know that this is bad syntax? No doc I have seen actually has told me so. -- Leif Biberg Kristensen http://solumslekt.org/ From lothar at ultimathule.nul Tue Apr 5 12:10:12 2005 From: lothar at ultimathule.nul (lothar) Date: Tue, 5 Apr 2005 16:10:12 -0000 Subject: re module non-greedy matches broken References: <1153658nrs82j13@corp.supernews.com> Message-ID: <1155e6jgesiik5d@corp.supernews.com> a non-greedy match - as implicitly defined in the documentation - is a match in which there is no proper substring in the return which could also match the regex. you are skirting the issue as to why a matcher should not be able to return a non-greedy match. there is no theoretical reason why it can not be done. "Andr? Malo" wrote in message news:d2tc04$84s$1 at news.web.de... > * "lothar" wrote: > > > no - in the non-greedy regex > > <1st-pat>*? > > > > <1st-pat>, and are arbitrarily complex patterns. > > The "not" is the problem. Regex patterns are expressed positive by > definition (meaning, you can say, what you expect, but not what you > don't expect). In other words, regexps were invented to define (uh... regular) > sets, nothing more (especially you can't define "non-sets"). So the usual > way is to define the set you've called '*?' and describe > it as regex. Modern regular expression engines (which are no longer regular > by the way ;-) allow shortcuts like negative lookahead assertions and the > like. > > I want to make clear, that it isn't, that nobody _wants_ to give an advice > how to express your pattern in general. The point is, that there's no > real syntax for it. It depends on how your <1st-pat> and look > like. Chances are, that's even not expressable in one regex (depends on > the complexity and kind of the set they define). > Each pattern you write is special to the particular use case. From martin at v.loewis.de Sun Apr 3 17:59:51 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 03 Apr 2005 23:59:51 +0200 Subject: Docorator Disected In-Reply-To: References: <4p9t419ockcg8578g6guse3a14t16orebf@4ax.com> <424f04d0.137947037@news.oz.net> <1112500967.391604.289760@f14g2000cwb.googlegroups.com> <0mqu41pham7n91vb1qgtoe567unn1cffb6@4ax.com> <424f982c.175671582@news.oz.net> Message-ID: <42506757.1010404@v.loewis.de> Ron_Adam wrote: > This would be the same without the nesting: > > def foo(xx): > global x > x = xx > return fee > > def fee(y): > global x > return y*x > > z = foo(2)(6) Actually, it wouldn't. >>> def foo(xx): ... global x ... x = xx ... return fee ... >>> def fee(y): ... global x ... return y*x ... >>> z=foo(2) >>> x=8 >>> z(6) 48 So the global variable can be changed between the time foo returns and the time fee is invoked. This is not the same in the nested function case: the value of x would be bound at the time foo is called. It can be modified inside foo, but freezes once foo returns. >>So if you are seeing (2)(6) as something to pass, as opposed to a sequence of operations, I think there's >>a misconception involved. Perhaps I am taking your words askew ;-) > > > It's not entirely a misconception. Lets see where this goes... > > >>>>>dis.dis(compiler.compile('foo(2)(6)','','eval')) >> >> 1 0 LOAD_NAME 0 (foo) >> 3 LOAD_CONST 1 (2) >> 6 CALL_FUNCTION 1 >> 9 LOAD_CONST 2 (6) >> 12 CALL_FUNCTION 1 >> 15 RETURN_VALUE Hmm. If you think that this proves that (2)(6) is being *passed*, you still might have a misconception. What this really does is: 0. Put foo on the stack. Stack is [value of foo] 3. Put 2 on the stack -> [value of foo, 2] 6. Call a function with one arg; invoking foo(2) Put the result of this call back on the stack -> [result of foo(2)] 9. Put 6 on the stack -> [result of foo(2), 6] 12. Call it, computing (result of foo(2))(6) Put the result on the stack -> [result of (result of foo(2))(6)] 13. Return top-of-stack, yielding foo(2)(6) So at no point in time, (2)(6) actually exists. Instead, when the 6 is being put onto the stack, the 2 is already gone. It computes it one by one, instead of passing multiple sets of arguments. > While all of this isn't relevant, it's knowledge in my mind, and > effects my view of programming sometimes. There is nothing wrong with that. However, you really should try to see what the interpreter actually does, instead of speculation (of course, asking in a newsgroup is fine). > The calling routine, puts (passes) the second set of arguments onto > the stack before calling the function returned on the stack by the > previous call. Sure - you need the arguments to a function before being able to call the function. So there is always a set of arguments on the stack, which internally indeed gets converted into a tuple right before calling the function. However, at no point in time, there are *two* sets of arguments. > Or it could be said equally the functions (objects) are passed with > the stack. So both view are correct depending on the view point that > is chosen. Maybe I don't understand your view, when you said # No, I did not know that you could pass multiple sets of arguments to # nested defined functions in that manner. However, they way I understood it, it seemed incorrect - there are no multiple sets of arguments being passed, atleast not simultaneously. It is, of course, possible to pass multiple sets of arguments sequentially to multiple functions, eg. a = len(x) b = len(y) Regards, Martin From RonGrossi382737 at yahoo.com Thu Apr 21 11:43:41 2005 From: RonGrossi382737 at yahoo.com (RonGrossi382737 at yahoo.com) Date: 21 Apr 2005 08:43:41 -0700 Subject: =?iso-8859-1?q?Good_morning_or_good_evening_depending_upon_your_?= =?iso-8859-1?q?location=2E_I_want_to_ask_you_the_most_important_qu?= =?iso-8859-1?q?estion_of_your_life=2E_Your_joy_or_sorrow_for_all_e?= =?iso-8859-1?q?ternity_depends_upon_your_answer=2E_The_question_is?= =?iso-8859-1?q?=3A_Are_you_saved=3F_It_is_not_a_question_of_how_go?= =?iso-8859-1?q?od_you_are=2C_nor_if_you_are_a_church_member=2C_but?= =?iso-8859-1?q?_are_you_saved=3F_Are_you_sure_you_will_go_to_Heave?= =?iso-8859-1?q?n_when_you_die=3F_GOOGLE=B7NEWSGROUP=B7POST=B7146?= Message-ID: <1114098221.580669.86300@g14g2000cwa.googlegroups.com> The reason some people don't know for sure if they are going to Heaven when they die is because they just don't know. The good news is that you can know for sure that you are going to Heaven which is described in the Holy Bible as a beautiful place with no death, sorrow, sickness or pain. God tells us in the Holy Bible how simple it is to be saved so that we can live forever with Him in Heaven. "For if you confess with your mouth Jesus is Lord and believe in your heart that God raised Him from the dead, you WILL BE SAVED." (Romans 10:9) Over 2000 years ago God came from Heaven to earth in the person of Jesus Christ to shed His blood and die on a cross to pay our sin debt in full. Jesus Christ was born in Israel supernaturally to a virgin Jewish woman named Mary and lived a sinless life for thirty-three years. At the age of thirty-three Jesus was scourged and had a crown of thorns pressed onto His head then Jesus was crucified. Three days after Jesus died on a cross and was placed in a grave Jesus rose from the dead as Jesus said would happen before Jesus died. If someone tells you that they are going to die and in three days come back to life again and it happens then this person must be the real deal. Jesus Christ is the only person that ever lived a perfect sinless life. This is why Jesus is able to cover our sins(misdeeds) with His own blood because Jesus is sinless. The Holy Bible says, "In Him(Jesus) we have redemption through His blood, the forgiveness of sins..." (Ephesians 1:7) If you would like God to forgive you of your past, present and future sins just ask Jesus Christ to be your Lord and Saviour. It doesn't matter how old you are or how many bad things that you have done in your life including lying and stealing all the way up to murder. Just pray the prayer below with your mouth and mean it from your heart and God will hear you and save you. Dear Jesus Christ, I want to be saved so that I can have a home in Heaven with You when I die. I agree with You that I am a sinner. I believe that You love me and want to save me. I believe that You bled and died on the cross to pay the penalty for my sins and that You rose from the dead. Please forgive my sins and come into my heart and be my Lord and Saviour. Thanks Lord Jesus Christ for forgiving me and saving me through Your merciful grace. Amen. Welcome to the family of God if you just allowed God to save you. Now you are a real Christian and you can know for sure that you will live in Heaven forever when this life comes to an end. As a child of God we are to avoid sin(wrongdoing), but if you do sin the Holy Bible says, "My dear children, I write this to you so that you will not sin. But if anybody does sin, we have one who speaks to the Father in our defense Jesus Christ, the Righteous One." Those of you that have not yet decided to place your trust in the Lord Jesus Christ may never get another chance to do so because you do not know when you will die. Jesus said, "I am the way, the truth and the life: no one can come to the Father(God)(in Heaven), but by me." (John 14:6) This means that if you die without trusting in Jesus Christ as your Lord and Saviour you will be forever separated from the love of God in a place called Hell. The Holy Bible descibes Hell as a place of eternal torment, suffering, pain and agony for all those who have rejected Jesus Christ. The good news is that you can avoid Hell by allowing Jesus Christ to save you today. Only then will you have true peace in your life knowing that no matter what happens you are on your way to Heaven. Praise the Lord! Servant of the Lord Jesus Christ Ronald L. Grossi *Show this to your family and friends so they can know that they have a choice where they will spend eternity. Thanks! ____________________________________________________ Got Questions? http://www.gotquestions.org/archive.html Other Languages http://www.godssimpleplan.org/gsps.html Free Movie: To Hell and Back http://www.tbn.org/index.php/8/1.html Animation http://www.gieson.com/Library/projects/animations/walk/index.html The Passion Of The Christ http://www.thepassionofthechrist.com Beware Of Cults http://www.carm.org/cults/cultlist.htm About Hell http://www.equip.org/free/DH198.htm Is Jesus God? http://www.powertochange.com/questions/qna2.html Free Online Bible http://www.biblegateway.com ____________________________________________________ From saint.infidel at gmail.com Tue Apr 26 16:37:29 2005 From: saint.infidel at gmail.com (infidel) Date: 26 Apr 2005 13:37:29 -0700 Subject: Getting the sender widget's name in function (Tkinter) In-Reply-To: <1114545565.116766.157000@f14g2000cwb.googlegroups.com> References: <1114545565.116766.157000@f14g2000cwb.googlegroups.com> Message-ID: <1114547849.644971.191270@f14g2000cwb.googlegroups.com> from Tkinter import Tk, Button def say_hello(event): print 'hello!' print event.widget['text'] root = Tk() button1 = Button(root, text='Button 1') button1.bind('', say_hello) button1.pack() button2 = Button(root, text='Button 2') button2.bind('', say_hello) button2.pack() root.mainloop() From vvikram at stanford.edu Fri Apr 1 02:47:27 2005 From: vvikram at stanford.edu (Vikram) Date: Thu, 31 Mar 2005 23:47:27 -0800 Subject: __init__ method and raising exceptions In-Reply-To: <1112325129.473015.266740@l41g2000cwc.googlegroups.com> References: <1112325129.473015.266740@l41g2000cwc.googlegroups.com> Message-ID: > I can't use 'break' or 'continue' in a class method, nor can I return a > boolean value from __init__() to check for errors within the for-loop. > How would I be able to stop the current iteration and continue with the > next after reporting an error? maybe i don't fully understand your qn but why don't you let __init__ of your class raise an exception and then catch it in the outer for loop and continue. something like: for i in ... try: foo() except: continue Vikram From klaus at seistrup.dk Mon Apr 11 01:35:57 2005 From: klaus at seistrup.dk (Klaus Alexander Seistrup) Date: Mon, 11 Apr 2005 05:35:57 +0000 (UTC) Subject: database in python ? References: <1113197530.990898.46130@z14g2000cwz.googlegroups.com> Message-ID: ajikoe at gmail.com wrote: > I need to build table which need searching data which needs more > power then dictionary or list in python, can anyone help me what > kind of database suitable for python light and easy to learn. Is > mySQL a nice start with python ? You could try SQLite for Python: . Cheers, -- Klaus Alexander Seistrup Magnetic Ink, Copenhagen, Denmark http://magnetic-ink.dk/ From reinhold-birkenfeld-nospam at wolke7.net Thu Apr 21 06:07:48 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Thu, 21 Apr 2005 12:07:48 +0200 Subject: goto statement In-Reply-To: <426767FD.5050104@i.com.ua> References: <426767FD.5050104@i.com.ua> Message-ID: <3cpcfmF6n6g9bU2@individual.net> Maxim Kasimov wrote: > 1) goto exempts from necessity to install new software > (it is critical for remote working, for example, installing X11 may be > impossible at all) Attributing the need for a language feature to restrictions of your ambience is hilarious. Reinhold From turkaye at ldre.Vanderbilt.Edu Tue Apr 26 15:53:14 2005 From: turkaye at ldre.Vanderbilt.Edu (Emre Turkay) Date: Tue, 26 Apr 2005 14:53:14 -0500 Subject: Python internal design Message-ID: Hi Folks, I am designing a tool, in which there are dynamic types and variables with these types. In this respect, it is more like an interpreted language design. I wonder how these issues are implemented in Python are there any documents or articles about it, which I can read and get an idea. Thanks, emre From ville at spammers.com Mon Apr 25 02:49:50 2005 From: ville at spammers.com (Ville Vainio) Date: 25 Apr 2005 09:49:50 +0300 Subject: Python or PHP? References: <1114254894.512656.297040@l41g2000cwc.googlegroups.com> <87hdhxwj6s.fsf@debian.kirkjobsluder.is-a-geek.net> <1114274632.128667.281820@l41g2000cwc.googlegroups.com> <86br85rvfw.fsf@guru.mired.org> <863bthrmtg.fsf@guru.mired.org> Message-ID: >>>>> "John" == John Bokma writes: John> Who told you Perl can't do exceptions? Back when I learned (heh, I never 'really' learned, but knew enough to write programs in it) perl, almost every function call was followed by or die("blah"); i.e. the user had to check the error code. If the function would have raised an exception instead, such check would be redundant because it would never be executed. In Python, all error conditions raise exceptions. If python 'supported' exceptions but standard library functions didn't raise them, the feature would not be worth much. -- Ville Vainio http://tinyurl.com/2prnb From mirnazim at gmail.com Mon Apr 18 10:39:07 2005 From: mirnazim at gmail.com (Mir Nazim) Date: 18 Apr 2005 07:39:07 -0700 Subject: (PHP or Python) Developing something like www.tribe.net Message-ID: <1113835147.364885.304290@l41g2000cwc.googlegroups.com> Hi there. I am about to undertake a project. My employer wants it to be developed in PHP. While I was thinking that Python will be better for this job. The project will implement the functionality similar to Yahoo360 (http://www.360.yahoo.com), http://www.Tribe.net, Orkut etc. 1) There will be a groups like functionality like google groups. 2) Groups/personal blogs/albums/events/buddy lists etc. need to be implemented. 3) Most importantly it needs to be implemented like platform. that is it has to expose API or web services so that application implemented on it can talk to each other and other applications can talk to it. My employer wants to go with PHP because almost all the functionality is available with a Drupal CMS for PHP. But it is important to note that for an application, rather a platform, which is intended to be used for a long time, time to implement should not be the major criteria above good design and maintainability(in which python scores highest). IMHO Zope3/Quixote seem to be the obvious choice here. Though functionality is not available on them but i think time spent now will be gained by gains in better design and maintainable code base. Now I want this wonderful c.l.py community to pour in their suggestions on what would be better alternatives. Also may we try various combinations of frameworks like Zope3 for components, Twisted2.0 for network functionality etc. PS: I am leaving out Zope2.x and Twisted1.x as a lot has changed in newer versions and I don't want to be hanged when Zope3 becomes official. Thanks --- Mir Nazim From tlassagn at napanet.net Tue Apr 5 15:21:30 2005 From: tlassagn at napanet.net (T.D. Lassagne) Date: Tue, 5 Apr 2005 12:21:30 -0700 Subject: Lambda: the Ultimate Design Flaw References: <87is3663cn.fsf@wilson.rwth-aachen.de> <3b99ncF6fd2apU1@individual.net> <3g_3e.134005$dP1.471451@newsc.telia.net> Message-ID: In article <3g_3e.134005$dP1.471451 at newsc.telia.net>, sunnan at handgranat.org says... > Artie Gold wrote: > > Torsten Bronger wrote: > >> The whole text seems to be a variant of > >> . > >> > >> Tsch??, > >> Torsten. > >> > > Ya think? ;-) > > Heh. I was glad that Torsten pointed it out; I didn't get what was funny > about the joke until then. Please consider joining the International Sarcasm Society. Our motto is "Like We Need YOUR Support". ----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups ----= East and West-Coast Server Farms - Total Privacy via Encryption =---- From fredrik at pythonware.com Tue Apr 12 15:28:28 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 12 Apr 2005 21:28:28 +0200 Subject: variables exist References: <9622d535.0504110552.1e070e8d@posting.google.com> <425c1353$1@nntp0.pdx.net> Message-ID: Scott David Daniels wrote: > >... STeVe stressed that the try/except solution is only really appropriate > > for cases where the failure to have the variable defined is quite rare. > > Beware: C++ and Java have an immense overhead for exceptions. Python > has a very lightweight exception mechanism. You should _very_seldom_ > choose exceptions or not on the basis of performance without measuring > the actual use; you are sure to be surprised. > > Structure your code to be easiest to understand. _If_ it is too slow, > investigate ways to improve its performance. The usual way is to > build better data structures and use better algorithms. Only in the > core of a frequently used inner loop should you even care about the > cost of exceptions. you haven't really read this thread, have you? From t.bettio at transnorm.ch Thu Apr 14 17:24:53 2005 From: t.bettio at transnorm.ch (Tiziano Bettio) Date: Thu, 14 Apr 2005 23:24:53 +0200 Subject: Supercomputer and encryption and compression @ rate of 96% In-Reply-To: <200504142221.41290.james@wrong.nu> References: <1113470846.970773.4780@g14g2000cwa.googlegroups.com> <425EDE12.3030208@transnorm.ch> <200504142221.41290.james@wrong.nu> Message-ID: <425EDFA5.2010702@transnorm.ch> R. C. James Harlow wrote: >On Thursday 14 April 2005 22:18, Tiziano Bettio wrote: > > > >>Actually your script doesn't work on my python distribution... >> >> > >Works fine here - did you decompress the first bit of the python executable? >You have to do that before Fredrick's script works... > > well i tried, but i don't have enough diskspace... my 4.67TerraByte are just 98.889 ExaByte short to complete the task ;) From mnations at gmail.com Fri Apr 22 21:51:54 2005 From: mnations at gmail.com (Mudcat) Date: 22 Apr 2005 18:51:54 -0700 Subject: Confusing: Canvas image working in function but not in class In-Reply-To: <1114120377.568827.294120@z14g2000cwz.googlegroups.com> References: <1114120377.568827.294120@z14g2000cwz.googlegroups.com> Message-ID: <1114221114.617211.249470@z14g2000cwz.googlegroups.com> I will answer my own question in case anyone else ever has this problem. I knew the problem (although some say it's not) existed with the namespace of pictures, that if you didn't save the pictures in persistent memory they would disappear as soon as the function that called them was exited. So a while ago I went through this and fixed it by saving all my pictures and widgets that held them as class objects. However, apparently I was causing the same thing to happen by not saving the class instance as an object of the class that called it. So this fixed it: def uts5100(self): self.sys5100 = UTS5100( self.master ) From syd.diamond at gmail.com Thu Apr 7 18:27:06 2005 From: syd.diamond at gmail.com (syd) Date: 7 Apr 2005 15:27:06 -0700 Subject: within a class, redefining self with pickled file Message-ID: <1112912826.542938.48500@o13g2000cwo.googlegroups.com> def unpickle(self): self = pickle.load(open(self.getFilePath('pickle'))) This evidently does not work. Any idea why? I'd like to be able to replace a lightly populated class (enough to identify the pickled version correctly) with it's full version that's sitting pickled in a file. As of right now, I need to just return self and redefine the class. Thanks! From harlinseritt at yahoo.com Fri Apr 29 21:03:31 2005 From: harlinseritt at yahoo.com (Harlin Seritt) Date: 29 Apr 2005 18:03:31 -0700 Subject: Killing process Message-ID: <1114823011.063614.27150@l41g2000cwc.googlegroups.com> I am using os.getpid() to get the pid value for a script running. I store that value (as a string) to a file. Later when I try to kill that pid (i pull this from the file as a string value) I get errors. Using the following lines I get the subsequent error. (pid is a string value) win32api.TerminateProcess(int(pid), 0) OR ctypes.windll.kernel32.TerminateProcess(int(pid), 0) Errors: Exception in Tkinter callback Traceback (most recent call last): File "C:\Python23\lib\lib-tk\Tkinter.py", line 1345, i return self.func(*args) File "vngconsole.py", line 27, in StopVngSvc win32api.TerminateProcess(int(pid), 0) error: (6, 'TerminateProcess', 'The handle is invalid.') How exactly do I kill a pid using a string value? From della at toglimi.linux.it Wed Apr 6 14:07:45 2005 From: della at toglimi.linux.it (Matteo Dell'Amico) Date: Wed, 06 Apr 2005 18:07:45 GMT Subject: Python Cookbook, 2'nd. Edition is published In-Reply-To: References: <1111973347.202875.256730@l41g2000cwc.googlegroups.com> Message-ID: Larry Bates wrote: > I received my copy on Friday (because I was a contributor). > > I wanted to thank Alex, Anna, and David for taking the time to put > this together. I think it is a GREAT resource, especially for > beginners. This should be required reading for anyone that > is serous about learning Python. +1. The Python Cookbook is really great, and being included in the contributors, even if for a little tiny idea that got heavily refactored, feels wonderful. I'm really grateful to the python community. -- Ciao, Matteo From python_only at yahoo.com Tue Apr 26 03:15:09 2005 From: python_only at yahoo.com (python_only) Date: 26 Apr 2005 00:15:09 -0700 Subject: Simple, elegant, pythonic solution for switch statement Message-ID: <1114499709.437575.266630@z14g2000cwz.googlegroups.com> Check it out! Readable switch construction without lambdas or dictionaries: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/410692 From matthew_shomphe at countrywide.com Thu Apr 7 21:00:56 2005 From: matthew_shomphe at countrywide.com (Matt) Date: 7 Apr 2005 18:00:56 -0700 Subject: text processing problem In-Reply-To: References: <1112915641.663333.175260@f14g2000cwb.googlegroups.com> Message-ID: <1112922056.365893.307550@f14g2000cwb.googlegroups.com> Maurice LING wrote: > Matt wrote: > > > > > > Try this: > > import re > > my_expr = re.compile(r'(\w+) (\(\1\))') > > s = "this is (is) a test" > > print my_expr.sub(r'\1', s) > > #prints 'this is a test' > > > > M@ > > > > Thank you Matt. It works out well. The only think that gives it problem > is in events as "there (there)", where between the word and the same > bracketted word is more than one whitespaces... > > Cheers > Maurice Maurice, I'd HIGHLY suggest purchasing the excellent Mastering Regular Expressions by Jeff Friedl. Although it's mostly geared towards Perl, it will answer all your questions about regular expressions. If you're going to work with regexs, this is a must-have. That being said, here's what the new regular expression should be with a bit of instruction (in the spirit of teaching someone to fish after giving them a fish ;-) ) my_expr = re.compile(r'(\w+)\s*(\(\1\))') Note the "\s*", in place of the single space " ". The "\s" means "any whitespace character (equivalent to [ \t\n\r\f\v]). The "*" following it means "0 or more occurances". So this will now match: "there (there)" "there (there)" "there(there)" "there (there)" "there\t(there)" (tab) "there\t\t\t\t\t\t\t\t\t\t\t\t(there)" etc. Hope that's helpful. Pick up the book! M@ From harlinseritt at yahoo.com Sun Apr 24 23:03:36 2005 From: harlinseritt at yahoo.com (Harlin Seritt) Date: 24 Apr 2005 20:03:36 -0700 Subject: Multiple tuples for one for statement Message-ID: <1114398216.258027.105070@g14g2000cwa.googlegroups.com> I have three tuples of the same size: tup1, tup2, tup3 I'd like to do something like this: for a,b,c in tup1, tup2, tup3: print a print b print c Of course, you get an error when you try to run the pseudocode above. What is the correct way to get this done? Thanks, Harlin From jeffrey at fro.man Mon Apr 25 22:40:44 2005 From: jeffrey at fro.man (Jeffrey Froman) Date: Mon, 25 Apr 2005 19:40:44 -0700 Subject: Quote-aware string splitting References: <9Kgbe.24031$h6.523@tornado.texas.rr.com> Message-ID: <116rahd5t0lq85e@corp.supernews.com> J. W. McCall wrote: > For example, given the string: > > 'spam "the life of brian" 42' > > I'd want it to return: > > ['spam', 'the life of brian', '42'] The .split() method of strings can take a substring, such as a quotation mark, as a delimiter. So a simple solution is: >>> x = 'spam "the life of brian" 42' >>> [z.strip() for z in x.split('"')] ['spam', 'the life of brian', '42'] Jeffrey From Mark.English at liffe.com Mon Apr 25 10:44:41 2005 From: Mark.English at liffe.com (Mark English) Date: Mon, 25 Apr 2005 15:44:41 +0100 Subject: What do list comprehensions do that generator expressions don't? Message-ID: <40E605146701DE428FAF21286A97D3090457E42F@wphexa02.corp.lh.int> > Date: Mon, 25 Apr 2005 08:51:17 -0500 > From: Mike Meyer > Which means that the real rule should be always use generator expressions, > unless you *know* the expression will always fit in memory. > Which leads to the obvious question of why the exception. >>> l = [(1, 2), ('a', 'b'), (3, 2), (23, 32)] >>> l [(1, 2), ('a', 'b'), (3, 2), (23, 32)] This screen dump of the object is quite useful to me. >>> r = reversed(l) >>> r This screen dump of the object is less useful to me. >From a pure programming point of view it's not a sufficient reason to keep list comprehensions, especially as the interpreter shell could be massaged into giving more output, but right here right now it's a lot easier to read the former than the latter IMHO. (That is assuming I'm right in assuming functions like "reversed" are generator expressions). Mark ----------------------------------------------------------------------- The information contained in this e-mail is confidential and solely for the intended addressee(s). Unauthorised reproduction, disclosure, modification, and/or distribution of this email may be unlawful. If you have received this email in error, please notify the sender immediately and delete it from your system. The views expressed in this message do not necessarily reflect those of LIFFE Holdings Plc or any of its subsidiary companies. ----------------------------------------------------------------------- From mauriceling at acm.org Sat Apr 30 00:56:56 2005 From: mauriceling at acm.org (Maurice LING) Date: Sat, 30 Apr 2005 14:56:56 +1000 Subject: "implementation" of PEP 262 as an academic project References: <1114735502.510591.6360@f14g2000cwb.googlegroups.com> <42719DFF.5080504@acm.org> <1114781419.288939.30840@z14g2000cwz.googlegroups.com> <4272CE91.5080908@acm.org> Message-ID: <42731018.5060700@acm.org> Hi all, I reckoned that if I'm on this work, I might as well make it into an academic engineering-type project for my pass degree. Hence, I am sending this posting out to everyone to inform of my intentions. Despite the possible interests in this work, academic requires a 'personal' project with defined work. Of course, I do hope that comments and suggestions continue to flow like milk and honey. If in event I do decide against making it into an academic project or when it had cease to be academically-focused (i.e. submitted and passed my thesis), I will have the onus to inform everyone again through comp.lang.python (python-list) and catalog-sig mailing list. Thank you everyone for your kind understanding. Cheers Maurice > Hi, > > I've just read PEP 262 last night and finds that it does more or less > describes what I have in mind. However, I am not sure if there is every > need for such a descriptive database file or something slimmer, like > Fink's .info files will suffice. > > An example of Fink's .info file is: > ==================================================== > Package: g77 > Version: 3.4.1 > Revision: 1 > BuildDependsOnly: true > Source: mirror:gnu:gcc/gcc-%v/gcc-%v.tar.bz2 > Source-MD5: 31b459062499f9f68d451db9cbf3205c > NoSourceDirectory: True > ConfigureParams: --enable-languages=f77 --infodir='${prefix}/share/info' > --libexecdir='${prefix}/lib' --disable-shared > #BuildDepends: dejagnu > PatchScript: << > #!/bin/sh > cd gcc-%v/gcc > mv Makefile.in Makefile.in.orig > sed 's|$(ALL_CPPFLAGS) $(INCLUDES)|$(INCLUDES) $(ALL_CPPFLAGS)|g' < > Makefile.in.orig > Makefile.in > << > CompileScript: << > #!/bin/sh > mkdir darwin > cd darwin > ../gcc-%v/configure %c > make CFLAGS='-O' LIBCFLAGS='-g -O2' LIBCXXFLAGS='-g -O2 > -fno-implicit-templates' profiledbootstrap > #cd gcc; make check-g77 > << > InstallScript: << > #!/bin/sh > cd darwin > make install prefix=%i > cd %i/bin > /bin/rm -f gcc gccbug cpp gcov powerpc-apple* > ln -s %p/bin/g77 f77 > darwinvers=`/usr/bin/uname -v | cut -f1 -d":" | awk '{print $4}'` > gccvers=`%i/bin/g77 -dumpversion | head -1 | cut -f4 -d" "` > ln -s > %p/lib/gcc/powerpc-apple-darwin${darwinvers}/${gccvers}/include/g2c.h > %i/include/g2c.h > /bin/rm -rf %i/share/locale %i/man > /bin/rm -f %i/lib/charset.alias > /bin/rm -f %i/share/info/gcc* %i/share/info/cpp* > /bin/mv -f %i/lib/libiberty.a %i/lib/libiberty-g77.a > << > License: GPL > DocFiles: gcc-%v/gcc/f/ChangeLog gcc-%v/COPYING gcc-%v/COPYING.LIB > Description: GNU Fortran compiler > DescDetail: << > g77 consists of several components: > > 1) The g77 command itself. > 2) The libg2c run-time library. This library contains the > machine code needed to support capabilities of the Fortran > language that are not directly provided by the machine code > generated by the g77 compilation phase. > 3) The compiler itself, internally named f771. > f771 does not generate machine code directly -- > it generates assembly code, leaving the conversion to > actual machine code to an assembler, usually named as. > > g77 supports some fortran90 features, like automatic arrays, > free source form, and DO WHILE. > << > DescPort: << > Installs g77 from the FSF gcc distribution. > > This version does not install in /usr. It contains it's own cc1 and > libgcc.a installed in %p. > > libiberty.a moved to libiberty-g77.a to avoid conflict with ddd. > << > DescUsage: << > If you get unresolved symbol '_saveFP', add -lcc_dynamic when linking. > > Does not support -framework argument, to link frameworks use -Wl flag > (for example, to link vecLib use "-Wl,-framework -Wl,vecLib"). > > No man page, use "info g77". > << > Homepage: http://gcc.gnu.org/onlinedocs/g77/ > Maintainer: Jeffrey Whitaker > ================================================================================ > > > Implementing the API specified in PEP 262 is desirable. > > What I am thinking is this, > > 1. when user specify a package to install, the package's .info file will > be looked up in 'pkginfo' directory (in PEP 262, it is the INSTALLDB > directory that holds all these .info files). > > 2. to the system, only 3 things are crucial: where to get the package? > what packages the package needs? how to install? These 3 things are the > real critical parts of .info file, the rest are information and metadata. > > 3. from the dependencies, the system now creates a tree of dependencies. > Can all dependencies be satisfied, i.e. are there any required packages > that are not in standard library and there is no .info file for? > > 4. dependencies are satisfied (install the packages) from terminal leaf > nodes on the dependency tree to the root node (which is the one the user > wants to install) > > 5. appropriate entries are made in appropriate files (i.e. > pkg-install.log) to signify which packages are installed. > > 6. satisfy the files needed for API requirements of PEP 262. > > Please tell me what you think... > > > Cheers > Maurice From bvande at po-box.mcgill.ca Mon Apr 4 17:02:20 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Mon, 04 Apr 2005 17:02:20 -0400 Subject: testing -- what to do for testing code with behaviour dependant upon which files exist? In-Reply-To: References: <424F00D5.9020205@po-box.mcgill.ca> Message-ID: <4251AB5C.7010809@po-box.mcgill.ca> > "Brian van den Broek" wrote in message > news:424F00D5.9020205 at po-box.mcgill.ca... > >>Hi all, >> >>I'm just starting to employ unit testing (I'm using doctest), and I am >>uncertain how to handle writing tests where the behaviour being tested is >>dependant on whether certain file paths point to actual files. Hi all, I had a busy weekend after posting, so didn't get a chance to follow-up until now. Thanks to all who responded. Python's my first real language, and I am a mere hobbyist, so the suggestions for search terms provided by Terry (and implicitly by Andre who suggested a mock strategy) are most welcome! Sometimes the hardest part of googling is knowing what terms to search for. Grig suggested the tempfile module; I had rejected that initially, as the code I am testing displays an error message containing the bad file path, so I thought I needed to know the path name at time of coding the tests. But, I've since learned that doctest can be made to consider only leading portions of a line's content. So, this might well work for me. Thanks for reminding me of the approach. Jeremy suggested using a directory name akin to "C:\onlyanidiotwouldhavethisdirecotrynameonadrive". That is what I had settled on before I posted. Somehow it feels unhappy and inelegant. But, I'm a bit less uncomfortable with it seeing that others have done so, too. Anyway, thanks again for the suggestions :-) Best to all, Brian vdB From jjl at pobox.com Wed Apr 6 14:30:05 2005 From: jjl at pobox.com (John J. Lee) Date: 06 Apr 2005 19:30:05 +0100 Subject: Lambda: the Ultimate Design Flaw References: <4253fe0c$1@nntp0.pdx.net> <8c7f10c6050406085020a24b44@mail.gmail.com> Message-ID: <4qejlpw2.fsf@pobox.com> Simon Brunning writes: > On Apr 6, 2005 4:42 PM, Scott David Daniels wrote: > > I've always wondered about this turn of phrase. I seldom > > eat a cake at one sitting. > > Clearly you're just not trying. ;-) :-))) John From no.spam at see.below.es Wed Apr 20 14:18:16 2005 From: no.spam at see.below.es (Javier Bezos) Date: Wed, 20 Apr 2005 20:18:16 +0200 Subject: Why Python does *SLICING* the way it does?? References: <1113976729.450677.261130@o13g2000cwo.googlegroups.com> Message-ID: escribi? en el mensaje news:1113976729.450677.261130 at o13g2000cwo.googlegroups.com... > Many people I know ask why Python does slicing the way it does..... > > Can anyone /please/ give me a good defense/justification??? > > I'm referring to why mystring[:4] gives me > elements 0, 1, 2 and 3 but *NOT* mystring[4] (5th element). > > Many people don't like idea that 5th element is not invited. > > (BTW, yes I'm aware of the explanation where slicing > is shown to involve slices _between_ elements. This > doesn't explain why this is *best* way to do it.) Recently there was a short (sub)thread about that. One of my messages (against half-open slices) is, for example http://groups-beta.google.com/group/comp.lang.python/msg/5532dd50b57853b1 Javier ___________________________________________________________ Javier Bezos | TeX y tipograf?a jbezos at wanadoo dot es | http://perso.wanadoo.es/jbezos ............................|............................... CervanTeX (Spanish TUG) | http://www.cervantex.org From jason at tishler.net Mon Apr 4 16:17:23 2005 From: jason at tishler.net (Jason Tishler) Date: Mon, 4 Apr 2005 16:17:23 -0400 Subject: Problems compiling PIL under Cygwin In-Reply-To: <1112622420.b10f3c33f4b325231e47d8cc95e09ded@teranews> References: <1112622420.b10f3c33f4b325231e47d8cc95e09ded@teranews> Message-ID: <20050404201723.GA3636@tishler.net> Martin, On Mon, Apr 04, 2005 at 03:46:58PM +0200, Martin Magnusson wrote: > I'm trying to build PIL under Cygwin (for use with the Skencil vector > graphics program), and I couldn't find a better forum for questions > than this. > > I'm using Python 2.3.4, and when I run "python setup.py build_ext -i" > I get the following output: > > running build_ext > building '_imaging' extension > gcc -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict-prototypes > -DHAVE_LIBJPEG -DHAVE_LIBZ -I/usr/include/freetype2 -IlibImaging > -I/usr/include -I/usr/local/include -I/usr/include/python2.3 -c > libImaging/GifEncode.c -o > build/temp.cygwin-1.5.12-i686-2.3/libImaging/GifEncode.o > C:\cygwin\bin\python2.3.exe (1352): *** unable to remap > C:\cygwin\bin\tk84.dll to same address as parent(0x760000) != 0xBB0000 > 4 [main] python 1984 sync_with_child: child 1352(0x238) died > before initialization with status code 0x1 > 282 [main] python 1984 sync_with_child: *** child state child > loading dlls > error: Resource temporarily unavailable > > Does anybody know what could be done to solve this? See the following: http://www.google.com/search?hl=en&lr=&q=%22cygwin+python%22+%22unable+to+remap%22+%22same+address+as+parent%22 Jason -- PGP/GPG Key: http://www.tishler.net/jason/pubkey.asc or key servers Fingerprint: 7A73 1405 7F2B E669 C19D 8784 1AFD E4CC ECF4 8EF6 From kent37 at tds.net Wed Apr 20 08:33:48 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 20 Apr 2005 08:33:48 -0400 Subject: Python instances In-Reply-To: <1113983093.813565.23430@l41g2000cwc.googlegroups.com> References: <1113982340.156937.75530@f14g2000cwb.googlegroups.com> <1113983093.813565.23430@l41g2000cwc.googlegroups.com> Message-ID: <426647ea$1_3@newspeer2.tds.net> henrikpierrou at hotmail.com wrote: > Guess i shouldn't think of the __init__(self) function as a constructor > then. No, that's not it. You shouldn't think of variables defined outside of a method as instance variables. In Java for example you can write something like public class MyClass { private List list = new ArrayList(); public void add(Object x) { list.add(x); } } In this case list is a member variable of MyClass instances; 'this' is implicit in Java. In Python, if you write something that looks similar, the meaning is different: class MyClass: list = [] def add(self, x): self.list.append(x) In this case, list is an attribute of the class. The Java equivalent is a static attribute. In Python, instance attributes have to be explicitly specified using 'self'. So instance attributes have to be bound in an instance method (where 'self' is available): class MyClass: def __init__(self): self.list = [] def add(self, x): self.list.append(x) Kent From no at spam Fri Apr 1 16:58:08 2005 From: no at spam (D H) Date: Fri, 01 Apr 2005 15:58:08 -0600 Subject: decorator syntax polling suggestion In-Reply-To: References: <411BF3FC.71051A6F@alcyone.com> Message-ID: Jeremy Bowers wrote: > On Fri, 01 Apr 2005 16:52:52 -0500, Jeremy Bowers wrote: > Oops, sorry, some "send later" messages I thought were gone got sent. > Sorry. Didn't mean to revive dead threads. At least it happened on April Fool's. Or should I say: @aprilfools def happened: at least From rkern at ucsd.edu Mon Apr 11 04:35:30 2005 From: rkern at ucsd.edu (Robert Kern) Date: Mon, 11 Apr 2005 01:35:30 -0700 Subject: Thoughts on some stdlib modules In-Reply-To: References: <4257BE8B.9080209@v.loewis.de><1113120099.217977.192190@g14g2000cwa.googlegroups.com> <4258e5e6$0$3407$9b622d9e@news.freenet.de> <425999BD.7050308@v.loewis.de> Message-ID: Fredrik Lundh wrote: > Robert Kern wrote: > > >>>(the Linux distributors know how to do this: look for good stuff that's >>>either actively maintained or simple and solid enough to live for a while, >>>make sure the licenses are good enough, bundle the latest and greatest >>>version, ship tested versions at regular intervals, update when necessary, >>>and pass bugs and patches upstream. why not use the same approach >>>for Python's standard distribution?) >> >>The reason they don't is because making a distribution like this is a royal pain in the ass. It >>makes no sense to make the Python standard distribution like this. Only insane people do this. I'm >>one of them. > > > with enough volunteers, and a distributed development environment, nobody > needs to be insane. if you try to channel everything through a small number of > CPython developers, everyone will loose their sanity, and the users will suffer. Agreed, which is why I think that proper package management and a CPyAN-type system is the way to go, not trying to stuff everything into a single distribution. >>"Updating when necessary" is problematic and really requires proper package management. Python is >>not an OS and cannot control all of the little factors that make package management feasible for >>OS distributions to do. > > > "updating when necessary" means "adding new components to the standard library > when there are new stable releases available, and someone has time to run the test > suite and contact the upstream provider if necessary". Yes, that's the "royal pain in the ass" that I was referring to. Sounds easy, but it soaks up far more time than you (I) possibly thought it would. I think that pumping out a new release of the whole standard library every time one package gets updated is rather absurd and aggravates rather than ameliorates the problem. Allow me to take an example that I'm sure you are familiar with (and can correct me if I get things wrong). You were once asked why you didn't use Numeric arrays as the memory store for PIL image objects. Your (good) reason was that Numeric was not part of the standard library and you didn't want to add a dependency on another 3rd party package. Now let's suppose that Numeric was included in this standard library and PIL wasn't. If you wanted to use Numeric arrays, you could not simply depend on the standard library; you would have to depend on specific releases of the standard library because Numeric is changing what with numarray and the impending Numeric/numarray unification (actually, we ought to talk about that[1]). What's more, the version numbers of the standard library that you would have to depend on would have no particular correlation with the versioning of the underlying component on which you are really depending. And then someone is going to want to use a package that requires stdlib < 2.5.1-1004 *and* a package that requires stdlib > 2.5.1-1010. CPyAN-type systems will, if they make good on their promises, avoid this hassle. [1] As a side note, with the Numeric/numarray unification, the Numeric people are developing an array interface that will allow seamless and copyless interfacing between Numeric and other packages that either produce something array-like (e.g. PIL) or can consume something array-like (e.g. gui toolkits). With this protocol, PIL can support Numeric arrays (or anything else array-ish like whatever image classes in are in a gui toolkit) without needed to depend on the modules themselves. http://numeric.scipy.org/ Since PIL is one of the compelling reasons for such an interface, we'd like your input on it. If you have comments or questions, please let us know on the Numpy mailing list. http://lists.sourceforge.net/lists/listinfo/numpy-discussion >>What's more, once you *do* have proper package management on the platforms that you care about, it >>doesn't matter what is or isn't in the standard distribution. > > > which means that at the moment, the best way to get a Python module into the > hands of users is to 1) provide windows installers that are compatible with the > "official" distribution, and 2) make it easy for downstream providers to package > your stuff, and leave it to them to take care of the rest. At the moment, yes, more or less. However, neither the standard Windows and Mac installers are what I consider to be "proper package management." > but if the library in the standard distribution doesn't really matter, it should be > stripped down to minimum, to avoid overloading the CPython maintainers. I agree, but the CPyAN systems have to come out of the vapour first. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From danb_83 at yahoo.com Sat Apr 30 06:31:03 2005 From: danb_83 at yahoo.com (Dan Bishop) Date: 30 Apr 2005 03:31:03 -0700 Subject: Python Challenge ahead [NEW] for riddle lovers References: <4272C8A0.7050404@hathawaymix.org> Message-ID: <1114857063.468588.229880@g14g2000cwa.googlegroups.com> darren kirby wrote: > quoth the Shane Hathaway: > > pythonchallenge wrote: > > > For the riddles' lovers among you, you are most invited to take part > > > in the Python Challenge, the first python programming riddle on the net. > > > > > > You are invited to take part in it at: > > > http://www.pythonchallenge.com > > > > That was pretty fun. Good for a Friday. Too bad it comes to an abrupt > > "temporary end". > > > > Shane > > > > P.S. I hope I didn't hammer your server on step 3. I was missing the > > mark. :-) > > You're not the only one. This is where I am currently stuck. It's starting to > hurt my head. > > There are 478 results in the form *BBBsBBB* but the thing said 'exactly' > right, well there are 10 results in the form *sBBBsBBBs* > None of them seem to work... The same thing happened to me, but then I figured it out. Hint: Print all 10 results in a column. From erictexier at sbcglobal.net Mon Apr 25 23:22:33 2005 From: erictexier at sbcglobal.net (Eric Texier) Date: Tue, 26 Apr 2005 03:22:33 GMT Subject: key binding with mac Message-ID: I am just starting to use python on the mac. How do I get backspace, the arrows up/down and all the control like ctrl-a to work nicely under the console. for now I am getting a bunch of ^? ^[[A when I use any tcsh type of control. thanks, From kasimov at i.com.ua Tue Apr 26 11:33:41 2005 From: kasimov at i.com.ua (Maksim Kasimov) Date: Tue, 26 Apr 2005 18:33:41 +0300 Subject: python equivalent of php implode Message-ID: in php-scripts, to insert data to database, i'm doing like this: ... $query_param = array( 'field0' => 1, 'field1' => 3, 'field2' => $var2, 'field3' => $var3, ); ... $sql = "INSERT INTO $table (".implode(", ", array_keys($query_param)).") VALUES ('".implode("','", $query_param)."')"; how it can be done, using python (elegantly, without cycles)? -- Best regards, Maksim Kasimov mailto: kasimov at i.com.ua From http Wed Apr 20 02:38:06 2005 From: http (Paul Rubin) Date: 19 Apr 2005 23:38:06 -0700 Subject: How to run Python in Windows w/o popping a DOS box? References: <7xekd66ra3.fsf@ruckus.brouhaha.com> <4265d7b4.27743873@news.oz.net> Message-ID: <7x1x960x81.fsf@ruckus.brouhaha.com> bokr at oz.net (Bengt Richter) writes: > I would try right-clicking the shortcut icon and selecting > properties, then select the shortcut tab and edit the target string > with s/python/pythonw/ and then click ok. Thanks! I'll try that tomorrow. I never would have figured that out. From cdkrug at worldnet.att.net Wed Apr 27 20:59:21 2005 From: cdkrug at worldnet.att.net (Charles Krug) Date: Thu, 28 Apr 2005 00:59:21 GMT Subject: Is there a better interactive plotter then pylab? Message-ID: List: I'm trying to us pylab to see what I'm doing with some DSP algorithms, in case my posts about convolution and ffts weren't giving it away. I've been using pylab's plot function, but I'm finding it a bit cumbersome. It works, but if I switch from the interactive window to the plot window and back, the plot window gets trashed. Is there a better alternative for interactive use? Thanks Charles From fredrik at pythonware.com Sun Apr 10 10:03:41 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 10 Apr 2005 16:03:41 +0200 Subject: Thoughts on some stdlib modules References: <1113126605.315861.44730@z14g2000cwz.googlegroups.com> <1113139772.023037.153620@l41g2000cwc.googlegroups.com> Message-ID: Kay Schluehr wrote: > > it's also GPL:ed, and the namespace support is totally broken. there > > are faster solutions out there with Python-compatible licenses. > > Interesting. Which implementation "out there" ( so not in the std-lib ) > that maps the whole XML into an internal structure and makes it easily > accessible is currently faster? here are three alternatives: ltree (http://codespeak.net/lxml/) libxml2 (http://xmlsoft.org/downloads.html) celementtree (http://effbot.org/zone/celementtree.htm) (ltree is an alternative binding to libxml2). for raw parsing performance (disk to memory), see: http://effbot.org/zone/celementtree.htm#benchmarks as for access, celementtree builds a tree of Python objects, while the others have to convert the internal structures to Python objects as you access them. if you need to access large parts of the tree, celementtree can be a lot faster (the yum developers report a 2-3x speedup, for example). on the other hand, libxml2/ltree supports a lot more XML standards (XPath, XSLT, various validation models, etc) which can come in handy in many cases. From vze4rx4y at verizon.net Fri Apr 1 11:34:32 2005 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Fri, 01 Apr 2005 16:34:32 GMT Subject: StopIteration in the if clause of a generator expression References: Message-ID: [Peter Otten] > a StopIteration raised in a generator expression > silently terminates that generator: > > >>> def stop(): raise StopIteration > ... > >>> list(i for i in range(10) if i < 5 or stop()) > [0, 1, 2, 3, 4] > > In a list comprehension, on the other hand, it is propagated: > > >>> [i for i in range(10) if i < 5 or stop()] > Traceback (most recent call last): > File "", line 1, in ? > File "", line 1, in stop > StopIteration > > Is that an intentional difference? I would call it an unfortunate assymmetry -- one the never comes up unless you're up to no good ;-) In a way, both behave identically. They both raise StopIteration. In the case of the generator expression, that StopIteration is intercepted by the enclosing list() call. That becomes obvious if you write a pure python equivalent for list: def lyst(s): it = iter(s) result = [] try: while 1: result.append(it.next()) except StopIteration: # guess who trapped StopIter return result Raymond Hettinger From mefjr75 at hotmail.com Fri Apr 15 17:48:11 2005 From: mefjr75 at hotmail.com (M.E.Farmer) Date: 15 Apr 2005 14:48:11 -0700 Subject: Pyrex colorizer please review Message-ID: <1113601691.573420.93420@o13g2000cwo.googlegroups.com> Hello all, I have been working on a Pyrex colorizer, and need a little feedback. PyrexTypes are orange and PyrexKeywords are violet ( this will be fully extensible when finished ). Please review the webpage and let me know what you think. I do not fully grok Pyrex( never used it ). If you find tokens missing that should be added, or extra tokens that should be removed please comment. If all is well I will post the updated PySourceColor module and PyrexColor script to my website for download. http://bellsouthpwp.net/m/e/mefjr75/python/PyrexTest_XHTML2.htm M.E.Farmer From mwm at mired.org Tue Apr 26 00:00:57 2005 From: mwm at mired.org (Mike Meyer) Date: Mon, 25 Apr 2005 23:00:57 -0500 Subject: What's do list comprehensions do that generator expressions don't? References: <86ll77pgqz.fsf@guru.mired.org> Message-ID: <86acnmnq4m.fsf@guru.mired.org> Jeremy Bowers writes: > On Mon, 25 Apr 2005 16:48:46 -0400, Bill Mill wrote: > generalizing anyways, which is the right approach. I doubt that Python 3.0 > would have two radically different implementations; they'll just have the > genexp implementation, and an optimization for list creation if the list > creation can know the size in advance, regardless of where it came from. Why do we have to wait for Python 3.0 for this? Couldn't list comprehensions and generator expression be unified without breaking existing code that didn't deserve to be broken? http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From ojokimu at yahoo.co.uk Tue Apr 5 19:33:52 2005 From: ojokimu at yahoo.co.uk (John Ridley) Date: Wed, 6 Apr 2005 00:33:52 +0100 (BST) Subject: Installing Python 2.4 on Linux In-Reply-To: 6667 Message-ID: <20050405233352.5238.qmail@web26809.mail.ukl.yahoo.com> --- Edward Diener wrote: [snip] > I do not know whether this is a Python problem or a Fedora 3 problem > but > I thought I would ask here first and see if anybody else had the same > > problem. I imagine the problem might exist on other Linux systems. On my Mandrake 10.1 system I have the default python 2.3 installation plus a separate python 2.4 installation which I compiled from source. There are two executables (python2.3 and python2.4) in /usr/bin, plus a hard-link (from python2.4) named python. If necessary, I could switch back to the default setup by replacing the hard-link with one from python2.3 - so the system would then have its preferred python version and I could selectively run python2.4 whenever appropriate. So far, Mandrake has not complained about using python 2.4 exclusively, so I might try removing the old installation eventually. (Then again, it's always handy to keep it for compatibility testing). Note that if compiling and installing from source there is an option of 'make altinstall' which will leave the existing python executables (and man pages) as they are and just create a new python2.4 executable - by default the library is installed in '/usr/local/lib/python2.4'. See the README for details. John Ridley Send instant messages to your online friends http://uk.messenger.yahoo.com From flamesrock at gmail.com Thu Apr 28 22:09:00 2005 From: flamesrock at gmail.com (flamesrock) Date: 28 Apr 2005 19:09:00 -0700 Subject: Python Client & Loggin into Secure User Database Message-ID: <1114740540.255733.315170@f14g2000cwb.googlegroups.com> First, my problem doesn't make much practical sense so I hope you're up for a challenge. What I have (in concept) is a standalone web client that connects different 'players' to a central host and distributes game files between them. A user claims certain files, plays them, and then automatically uploads them to the site where they are subsequently distributed. What I want to do is have a secure system that lets users log in upon connecting so that the client has ftp privileges to upload. I'd like to avoid xmlrpc and anything that would require the server to do more than a simple php + sql script, preferably less. Basically, as simple as possible without scripting the server in python too. Whats the best way to accomplish this for a python client? (registration will be browser based btw..) -thanks in advance From grante at visi.com Tue Apr 5 17:27:41 2005 From: grante at visi.com (Grant Edwards) Date: Tue, 05 Apr 2005 21:27:41 -0000 Subject: optparse and negative numbers as positional arguments References: <115605ankljag93@corp.supernews.com> Message-ID: <11560md3p6drtc8@corp.supernews.com> On 2005-04-05, Tomi Silander wrote: > this must have been asked 1000 times (or nobody is as stupid as me), > but since I could not find the answer, here is the question. [...] > $ python2.4 ./mitvit.py -1.1 [optparse error] > How is one supposed to give negative numbers as positional arguments > when using optparse? ./mitvit.py -- -1.1 -- Grant Edwards grante Yow! .. over in west at Philadelphia a puppy is visi.com vomiting... From peter at engcorp.com Fri Apr 29 21:29:02 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 29 Apr 2005 21:29:02 -0400 Subject: Killing process In-Reply-To: <1114823011.063614.27150@l41g2000cwc.googlegroups.com> References: <1114823011.063614.27150@l41g2000cwc.googlegroups.com> Message-ID: Harlin Seritt wrote: > I am using os.getpid() to get the pid value for a script running. I > store that value (as a string) to a file. Later when I try to kill that > pid (i pull this from the file as a string value) I get errors. [...] > File "vngconsole.py", line 27, in StopVngSvc > win32api.TerminateProcess(int(pid), 0) > error: (6, 'TerminateProcess', 'The handle is invalid.') I believe the problem is you are assuming TerminateProcess() takes a PID, when in fact it takes a "handle". See this recipe for some hints: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/347462 and http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/createprocess.asp to learn more about the key function you're missing. -Peter From jbo at cannedham.ee.ed.ac.uk Thu Apr 14 06:16:18 2005 From: jbo at cannedham.ee.ed.ac.uk (Jim) Date: Thu, 14 Apr 2005 11:16:18 +0100 Subject: preallocate list In-Reply-To: References: Message-ID: John Machin wrote: > On Wed, 13 Apr 2005 14:28:51 +0100, Jim > wrote: > > >>Thanks for the suggestions. I guess I must ensure that this is my bottle >>neck. >> >> def readFactorsIntoList(self,filename,numberLoads): > > > 1. "numberLoads" is not used. > > >> factors = [] >> f = open(self.basedir + filename,'r') >> line = f.readline() >> tokens = line.split() >> columns = len(tokens) >> if int(columns) == number: > > > 2. "columns" is already an int (unless of course you've redefined > "len"!). Doing int(columns) is pointless. > 3. What is "number"? Same as "numberLoads"? > 4. Please explain in general what is the layout of your file and in > particular, what is the significance of the first line of the file and > of the above "if" test. > > >> for line in f: >> factor = [] >> tokens = line.split() >> for i in tokens: >> factor.append(float(i)) > > > 4. "factor" is built and then not used any more?? > > >> factors.append(loadFactor) > > > 5. What is "loadFactor"? Same as "factor"? > > >> else: >> for line in f: >> tokens = line.split() >> factors.append([float(tokens[0])] * number) > > > 6. You throw away any tokens in the line after the first?? > > >> return factors >> >> >>OK. I've just tried with 4 lines and the code works. > > > Which code works? The code you posted? Please define "works". > > > >>With 11000 lines it >>uses all CPU for at least 30 secs. There must be a better way. > > > Perhaps after you post the code that you've actually run, and > explained what your file layout is, and what you are trying to > achieve, then we can give you some meaningful help. > > Cheers, > > John > > > Thanks for looking John. For that I should take a little time to explain. I tried to rename the variables, some of them were four words long. I got a couple of the renames wrong. Sorry. Regarding 'works'. I meant that with a text file of four lines the code completed. With my desired size 11000 lines it didn't complete within the limits of my patience. I didn't try any other size. Also I perhaps wrongly use the newsgroup threads paradigm in trying to restart my query with extra information (that turned out a little faulty). Luckily the other branches yielded fruit. Thanks again Jim From peter at engcorp.com Mon Apr 11 11:15:26 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 11 Apr 2005 11:15:26 -0400 Subject: My stupid newbie mistake In-Reply-To: References: Message-ID: Larry Bates wrote: > Matt Feinstein wrote: >>>>>import try >> >>gave a syntax error... So, how about a >>'YouAreUsingAReservedWordStupid' exception ? > > Because Python allows you to replace built-in methods with > your own. Later you will find that this can be extremely > powerful. Powerful, but not involved in this case, since you can't redefine *keywords* such as 'try'. -Peter From codecraig at gmail.com Thu Apr 14 15:33:16 2005 From: codecraig at gmail.com (codecraig) Date: 14 Apr 2005 12:33:16 -0700 Subject: distribute python script In-Reply-To: References: <1113501385.376681.148340@o13g2000cwo.googlegroups.com> <1113505210.693247.143930@z14g2000cwz.googlegroups.com> Message-ID: <1113507196.290786.264710@z14g2000cwz.googlegroups.com> Thanks so much Thomas!!! I added encodings to my setup's...here it is setup(console=[{"script": 'monkey_shell.py'}], options={"py2exe": {"packages": ["encodings"]}}) and i did the same for the other python script. Thanks!! From steven.bethard at gmail.com Wed Apr 6 11:07:02 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 06 Apr 2005 09:07:02 -0600 Subject: formatting file In-Reply-To: References: Message-ID: SPJ wrote: > Hi, > > I am new to python hence posing this question. > I have a file with the following format: > > test1 1.1-1 installed > test1 1.1-1 update > test2 2.1-1 installed > test2 2.1-2 update > > I want the file to be formatted in the following way: > > test1 1.1-1 1.1-2 > test2 2.1-1 2.1-2 > > How can I achieve this? I am stuck here. py> import itertools as it py> for line1, line2 in it.izip(f, f): ... line1, line2 = [line.split() for line in [line1, line2]] ... print '\t'.join(line1[:2] + line2[1:2]) ... test1 1.1-1 1.1-2 test2 2.1-1 2.1-2 where f is the file containing your data. I assumed it looked like: py> import StringIO as strio py> f = strio.StringIO("""\ ... test1 1.1-1 installed ... test1 1.1-2 update ... test2 2.1-1 installed ... test2 2.1-2 update ... """) STeVe From fred.dixon at gmail.com Tue Apr 19 11:31:10 2005 From: fred.dixon at gmail.com (fred.dixon) Date: 19 Apr 2005 08:31:10 -0700 Subject: py2exe - create one EXE In-Reply-To: References: Message-ID: <1113924670.511745.181050@f14g2000cwb.googlegroups.com> what about trying cx_freeze From ajikoe at gmail.com Thu Apr 7 03:36:04 2005 From: ajikoe at gmail.com (ajikoe at gmail.com) Date: 7 Apr 2005 00:36:04 -0700 Subject: client-client connection using socket Message-ID: <1112859364.203394.34100@g14g2000cwa.googlegroups.com> Hello, I have two client computers, each has its own host name. Can I do connection like socket between the two? I check when we want to make connection we have to only put hostname and port. For example: #Server program. Could we use client hostname here ? HOST = "" PORT = 21567 BUFSIZ = 1024 ADDR = (HOST,PORT) tcpSerSock = socket(AF_INET,SOCK_STREAM) tcpSerSock.bind(ADDR) tcpSerSock.listen(5) while 1: print "waiting for connection..." tcpCliSock,addr = tcpSerSock.accept() print "connected from:",addr while 1: data = tcpCliSock.recv(BUFSIZE) if not data:break tcpCliSock.send("[%s] %s" % ctime(time()),data) tcpCliSock.close() tcpSerSock.close() #Client program HOST = "fstbpc19" PORT = 21567 BUFSIZ = 1024 ADDR = (HOST,PORT) tcpCliSock = socket(AF_INET,SOCK_STREAM) tcpCliSock.connect(ADDR) while 1: data = raw_input("> ") if not data:break tcpCliSock.send(data) data = tcpCliSock.recv(1024) if not data:break print data tcpCliSock.close() Sincerely Yours, Pujo Aji From tim.peters at gmail.com Tue Apr 19 23:56:51 2005 From: tim.peters at gmail.com (Tim Peters) Date: Tue, 19 Apr 2005 23:56:51 -0400 Subject: How to run Python in Windows w/o popping a DOS box? In-Reply-To: <7xekd66ra3.fsf@ruckus.brouhaha.com> References: <7xekd66ra3.fsf@ruckus.brouhaha.com> Message-ID: <1f7befae050419205614660348@mail.gmail.com> [Paul Rubin] > Dumb question from a Windows ignoramus: > > I find myself needing to write a Python app (call it myapp.py) that > uses tkinter, which as it happens has to be used under (ugh) Windows. > That's Windows XP if it makes any difference. Nope, the Windows flavor doesn't matter. > I put a shortcut to myapp.py on the desktop and it shows up as a > little green snake icon, which is really cool and Pythonic. When I > double click the icon, the app launches just fine and the tkinter > interface does its thing. But Windows also launches a DOS box that > just sits on the screen uselessly. ... > Question: is there any simple way to arrange to launch the app from > the desktop, without also launching a DOS box? ... >From a DOS box, ren myapp.py *.pyw and click on a link to the resulting myapp.pyw instead. It's the purpose of the .pyw extension on Windows not to "bring up a DOS box". .pyw is associated with the Windows-specific pythonw.exe. From tom at lemurconsulting.com Tue Apr 26 06:16:57 2005 From: tom at lemurconsulting.com (Tom Mortimer) Date: Tue, 26 Apr 2005 11:16:57 +0100 Subject: pstats: negative time values Message-ID: <426e1514$0$347$cc9e4d1f@news.dial.pipex.com> Hi, A quick question - can anyone tell me how to interpret negative time values in pstats.Stats.print_stats() output? Eg - 39052965 function calls (38035317 primitive calls) in -250.959 CPU seconds Ordered by: internal time List reduced from 202 to 20 due to restriction <20> ncalls tottime percall cumtime percall filename:lineno(function) 5829 26.423 0.005 -155.269 -0.027 :0(parse) ... This is with Python 2.4 on Linux. Is it a bug, or what does it mean? Thanks! Tom From Ugo_DiGirolamo at invision.iip.com Tue Apr 26 18:02:24 2005 From: Ugo_DiGirolamo at invision.iip.com (Ugo Di Girolamo) Date: Tue, 26 Apr 2005 15:02:24 -0700 Subject: Problem with embedded python Message-ID: <3D4A0A4A0225484B965A23CFD127B82F4A6802@invnmail.invision.iip.com> I have the following code, that seems to make sense to me. However, it crashes about 1/3 of the times. My platform is Python 2.4.1 on WXP (I tried the release version from the msi and the debug version built by me, both downloaded today to have the latest version). The crash happens while the main thread is in Py_Finalize. I traced the crash to _Py_ForgetReference(op) in object.c at line 1847, where I have op->_ob_prev == NULL. What am I doing wrong? I'm definitely not too sure about the way I'm handling the GIL. Thanks in adv for any suggestion/ comment Cheers and ciao Ugo ////////////////////////// TestPyThreads.py ////////////////////////// #include #include "Python.h" int main() { PyEval_InitThreads(); Py_Initialize(); PyGILState_STATE main_restore_state = PyGILState_UNLOCKED; PyGILState_Release(main_restore_state); // start the thread { PyGILState_STATE state = PyGILState_Ensure(); int trash = PyRun_SimpleString( "import thread\n" "import time\n" "def foo():\n" " f = open('pippo.out', 'w', 0)\n" " i = 0;\n" " while 1:\n" " f.write('%d\\n'%i)\n" " time.sleep(0.01)\n" " i += 1\n" "t = thread.start_new_thread(foo, ())\n" ); PyGILState_Release(state); } // wait 300 ms Sleep(300); PyGILState_Ensure(); Py_Finalize(); return 0; } From martin at v.loewis.de Thu Apr 14 02:23:02 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 14 Apr 2005 08:23:02 +0200 Subject: Python 2.4 killing commercial Windows Python development ? In-Reply-To: <1o31j2-7l6.ln1@home.rogerbinns.com> References: <425a9869$0$38039$bed64819@news.gradwell.net><425aa0fb$0$38041$bed64819@news.gradwell.net><425AF2AB.1030401@v.loewis.de><425b8948$0$38045$bed64819@news.gradwell.net> <1o31j2-7l6.ln1@home.rogerbinns.com> Message-ID: <425e0c46$0$8215$9b622d9e@news.freenet.de> Roger Binns wrote: > - I could make some sort of installer that did all the non-Python interpretter > pieces and it would have to be compatible with anyone else doing the same > thing. > > The first is a waste of my time and effort, and I do the second except I also > include the Python interpretter meaning there are no dependencies. If that works for you and your users, fine - the main point of this thread is that some users complain they can't do that anymore, because they have no license to distribute msvcr71. For those users: what is the reason not to use the approach of shipping an application that requires a certain version of Python pre-installed on the target machine? Regards, Martin From john at castleamber.com Mon Apr 25 19:26:56 2005 From: john at castleamber.com (John Bokma) Date: 25 Apr 2005 23:26:56 GMT Subject: Python or PHP? References: <1114254894.512656.297040@l41g2000cwc.googlegroups.com> <87hdhxwj6s.fsf@debian.kirkjobsluder.is-a-geek.net> <1114274632.128667.281820@l41g2000cwc.googlegroups.com> <86br85rvfw.fsf@guru.mired.org> <863bthrmtg.fsf@guru.mired.org> <86y8b8rgg5.fsf@guru.mired.org> <86d5skr2l3.fsf@guru.mired.org> <86y8b7pydc.fsf@guru.mired.org> <86u0lvph0n.fsf@guru.mired.org> <86mzrmo5j8.fsf@guru.mired.org> Message-ID: Mike Meyer wrote: > John Bokma writes: [ unless ] > Yeah - unless is a bad idea. LOL, because you don't like it? You already showed code like: if condition then nothing else something unless IMNSHO improves readability. >> I doubt that features have been added to Perl just because. Even ones >> that look like it, unless for example, have an excellent use, it >> makes the code more readable. > > Then why do most Perl programmers consider unless "! a good idea"? Reread the last part of the last sentence you quoted above. >> *sigh* you gave a list of problems, I replied by putting all answers >> on one line, with () around them, and commas between them. I was not >> constructing a tuple, or a list in Perl > > Right. You were constructing something for humans to read - and > managed to construct something that was a PITA to read. If you'd made > the oher choice, it wouldn't have been a PITA to read. *sigh*, you asked several *stand alone* problems, from the context of your question especially *you* should have been able to grasp that I wasn't creating some silly list. The etc was a giveaway. >>> Actually, it's not clear the grep was right either. The return value >>> of grep (and map) isn't always the right thing. >> If you want to have a list of results and you assign it to a scalar, >> you are doing the wrong thing. > > And what if you do something with it other than assign it to a > variable? Depends on what you are going to do with it. If you give it to something that turns the context into scalar, you get the number of items, but either that is what you want, or you make a mistake. >> But the bottom line is: I gave you answers to all, except one, of >> your problems, you think my set of answers is a kind of Perl list, >> you thought the grep was plainly wrong, and I guess you are not >> comfortable with split. > > I thought your answer was a kind of list, but the syntax you chose > made it completely unclear where each item ended, because you > overloaded the "," character to seperate arguments to functions in the > list as well as to separate items in the list. You claimed to have some experience with perl, so I was *hoping* that you at least were able to understand sort, split, and grep are perl keywords. I mean, as a joke, I even almost translated your examples literaly e.g. sort a list sort @alist split a string on white space split ' ', $astring pull select list elements based grep criteria, @list on some criteria of some kind > Choosing the other > option would have grouped the arguments, and made things clear. I doubt it, you are just looking everywhere for a point, there is none. Your Perl skills are doubtfull to say the least. And yet you think you can say how badly it is designed, and so many things are wrong with it. To me you appear like a parrot, just repeating what you read somewhere, or heard somewhere. >> And this gives me the feeling that you either haven't been using Perl >> for over 4 years, or was never got beyond the absolute beginner >> level. In the latter case I can imagine that you are overwhelmed by >> Perl. As would one by any language. > > I'll admit it's been a while since I did anything other than > debugging. I haven't had much call to do the things that Perl is > really good at (simple re-heavy scripts), so I haven't done much > development in it. Amazing, how can you debug if you know next to nothing of it? > You may be overwhelmed by any language. I'm not. Sure, LOL. You are so overwhelmed with Perl that you even lack the basic skills, but yet nag about it a lot. >> In a pure language such things are in the library. > > So, where's the ARM assemblly library that includes dictionaries? I don't have access to a small one I wrote ages ago. But I am sure there are enough people who can provide you with one, or otherwise, as a skilled programmer, you would be able to write one in a day or less. > already pointed out the LISP study on garbage collection. Bounds > checking doesn't prevent mistakes, it just makes them easier to find > by causing an error report at the point the bug occured, instead of at > some point in the future. So it prevents a mistake from poping up in production code. That's enough for me. >> If I considered garbage collection bad, I would say so. But like >> airbags doesn't improve the driving skills of someone, so doesn't all >> kind of restrictions turn bad programmers suddenly in good >> programmers. > > You keep harping on restrictions. Garbage collection isn't a > restriction. It's a feature. It's also a restriction. Why do you think in Java one can call the gc explicitly? >> Moreover, good programmers rarely need to be restricted. But I don't >> see garbage collection as an anti-memory-leak restriction (which it >> can't be in all cases) but as a time saver. > > I think garbage collection is a time saver as well. It saves me time > hunting bugs caused by incorrect usage of the facilities it > replaced. It may save a little time in not having to write explicit > deallocation instructions, but that's trivial. In my case it saves time the other way around, I consider correct usage trivial, but the typing all the time... >> But is that because there are separate communities, or because there >> are different skill levels? Moreover, I hope that "have to maintain" >> was "had to maintain (some time ago)", because your Perl skills are >> more than lacking. > > No, unfortunately I still have to maintain Perl code. Then I seriously would recommend you to take a few days to read, and re- read Learning Perl. Not as a joke, but to save yourself a lot of time. Make notes the second pass. > Ok, so it's only the skill level of the programmers that's the cause > of the changes. So why does the language offer bad choices to the > programmers? Who are "the programmers" to you? And what is a bad choice? > That's as silly as a language having garbage collection > and alloc/free. Good programmers won't use the latter. Good programmers in your opinion. A really good programmer would use alloc/free, if garbage collection works as it does with Java, in those cases it's better. >> Which Perl? ActiveState Perl does indeed come with HTML, and XML >> parsers, SMTP, etc, clients. Web server(s), I have no idea, haven't >> needed a Perl webserver, I doubt it comes with AS Perl. > > Sure, anyone can bundle whatever they want up as a distribution, but > that doesn't mean those things are part of the base library. The > original contention which caused your reaction was that Python came > with a larger base library than Perl does. It seems that this claim is > still true even if you use the ActiveState distribution of Perl. I have no idea. Which modules do you miss in Perl that come with Python? >>> That's odd - all the >>> packages I see seem to want to install those things from CPAN. >> Is there such a centralized place for libraries for Python? > > Unfortunately, no. PyPI is the one linked to from the web site. It > doesn't have CPAN's auto-install capabilities So instead of the ability to install a Perl module with just a few lines of typing, one has to eh... what? Use google? Ask around? >> So it seems I am right: the overwhelming effect of "many ways" is >> mainly seen by absolute beginners, who are able to make up many ways, >> even if there is just one or two :-D. > > Are you afraid to answer the question? Do you or do you not use the > "foreach" loop in perl? Until you do, I can't know why my asking that > question makes you call my perl experience into question. I haven't been using *foreach* for quite some time, I use *for* all the time. Which is just because I am lazy. >> Perl 4? Even Perl 5 is almost 11 years old. Which version of Perl 5 >> are you talking about? > > Yup - I was using Perl back when it was at version 3. The currently > installed Perl is 5.8.5. You used Perl 3!?? LOL! For what? To write poetry? I mean, if you used version 3, and you still make extremely basic mistakes... >>>>> Right - Perl makes writing ugly, >>>> Nope, the programmer does that. >>> No, the programme writes the ugly code. Perl makes it easy. >> So, and who is to blame? Would you trust a programmer who can only >> write code in a certain way because he is restricted by the langauge >> to do so? > > Which would you trust more - a programmer who had to unlearn all his > bad habits, or one who never had the chance to develop them? Neither, and think about that for some time. >> No. If this was crossposted in a Perl group, by now quite a lot of >> people would have pointed you out, probably in a less nice way, that >> your Perl skills are of a person who hasn't even gone beyond the >> first few chapters of "Learning Perl". > > Oh, bullshit. I admit my perl skills are rusty - that comes from > having found a language that is superior to it across a large > collection of problem domains. I never read "Learning Perl". It didnt' > exist when I learned Perl. So you got stuck with Perl 3 somehow? > Even if it is true, the point still stands - Perl programs are less > maintainable than Python programs. I maintain that the difference in > philosphy on the number of ways to do things is a cause for that. But to me, you don't sound qualified to make that statement, your Perl skills are, well, rusty. >> And a bad programmer will go at great length explaining how bad the >> tools are, because he has to learn them :-D > > A good programmer will compare the toolset to others he's familiar > with, which only can be done when he/she knows both (almost) equally well. > and choose the toolset that is best for the jobs he does. An > evangelical programmer will then spend a lot of effort explaining why > one toolset is better than another. without a good understanding of the other toolset, yup. -- John MexIT: http://johnbokma.com/mexit/ personal page: http://johnbokma.com/ Experienced programmer available: http://castleamber.com/ Happy Customers: http://castleamber.com/testimonials.html From smacpher at gmail.com Fri Apr 22 03:13:05 2005 From: smacpher at gmail.com (Shaun) Date: 22 Apr 2005 00:13:05 -0700 Subject: Noobie Question: Using strings and paths in mkdir (os.mkdir("/test/"a)) Message-ID: Hello! I can't seem to get paths and variables working together: import os a = 'books' os.chdir( '/test') os.mkdir("/test/"a) the last line does not seem to work. os.mkdir(a) makes the directory books, but i want this directory as a subdirectory of test. I also tried: os.mkdir("/test/",a), and trying to make b = 'test' and then os.mkdir(a b). Does someone have any ideas or a link they can give me, I looked under strings in the python tutorial and library manual but I guess not in the right spot. Thanks for your help! Shaun From steven.bethard at gmail.com Fri Apr 22 18:34:00 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 22 Apr 2005 16:34:00 -0600 Subject: grouping subsequences with BIO tags In-Reply-To: <42686970.196123600@news.oz.net> References: <42686970.196123600@news.oz.net> Message-ID: Bengt Richter wrote: > On Thu, 21 Apr 2005 15:37:03 -0600, Steven Bethard wrote: > >>I have a list of strings that looks something like: >> ['O', 'B_X', 'B_Y', 'I_Y', 'O', 'B_X', 'I_X', 'B_X'] >>I need to group the strings into runs (lists) using the following rules >>based on the string prefix: >> 'O' is discarded >> 'B_...' starts a new run >> 'I_...' continues a run started by a 'B_...' >>So, the example above should look like: >> [['B_X'], ['B_Y', 'I_Y'], ['B_X', 'I_X'], ['B_X']] >> >>At the same time that I'm extracting the runs, it's important that I >>check for errors as well. 'I_...' must always follow 'B_...', so errors >>look like: >> ['O', 'I_...'] >> ['B_xxx', 'I_yyy'] >>where 'I_...' either follows an 'O' or a 'B_...' where the suffix of the >>'B_...' is different from the suffix of the 'I_...'. > > With error checks on predecessor relationship, > I think I'd do the whole thing in a generator, > doing my own groupby as I went. > E.g., see if this does what you want > (slightly different error checking): > > >>> L = ['O', 'B_X', 'B_Y', 'I_Y', 'O', 'B_X', 'I_X', 'B_X'] > >>> def get_runs(seq): > ... subseq =[] > ... curr = '' > ... for latest in seq: > ... curr, last = latest, curr > ... if curr.startswith('B_'): > ... if subseq: yield subseq > ... subseq = [curr] > ... elif curr.startswith('I_'): > ... if (last[:2] not in ('B_', 'I_') or > ... last[2:] != curr[2:] > ... ): raise ValueError, '%r followed by %r'%(last, curr) > ... subseq.append(curr) > ... elif curr!='O': > ... raise ValueError, 'Unrecognized element: %r' % curr > ... if subseq: yield subseq > ... > >>> list(get_runs(L)) > [['B_X'], ['B_Y', 'I_Y'], ['B_X', 'I_X'], ['B_X']] Yeah, I started this route, and got confused by it. Of course it makes perfect sense when someone writes you a working version. ;) Thanks! > > But note that I allowed multiple I_X, did you want to do that? > >>> list(get_runs('B_X I_X I_X'.split())) > [['B_X', 'I_X', 'I_X']] Yeah, that's right. Multiple 'I_...'s should be grouped together. > Did you want all these "errors" caught? > >>> list(get_runs('B_X I_X ?_X'.split())) > Traceback (most recent call last): > File "", line 1, in ? > File "", line 15, in get_runs > ValueError: Unrecognized element: '?_X' > >>> list(get_runs('I_X I_X ?_X'.split())) > Traceback (most recent call last): > File "", line 1, in ? > File "", line 12, in get_runs > ValueError: '' followed by 'I_X' > >>> list(get_runs('B_X I_Y ?_X'.split())) > Traceback (most recent call last): > File "", line 1, in ? > File "", line 12, in get_runs > ValueError: 'B_X' followed by 'I_Y' > > Does that do what you want? (BTW, I added an error check against ['B_X', '*_X'] and such) Yeah, those are the right errors. I'll have to think about whether I should be trying to catch the [^BI]_ error. It doesn't appear in my data now, but that doesn't mean it might not in the future. Thanks! STeVe From prabapython at yahoo.co.in Wed Apr 20 05:23:58 2005 From: prabapython at yahoo.co.in (praba kar) Date: Wed, 20 Apr 2005 10:23:58 +0100 (BST) Subject: goto statement In-Reply-To: 6667 Message-ID: <20050420092359.81900.qmail@web8409.mail.in.yahoo.com> Dear All, In Python what is equivalent to goto statement regards, praba __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From kay.schluehr at gmx.net Tue Apr 26 02:54:07 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 25 Apr 2005 23:54:07 -0700 Subject: Injecting code into a function In-Reply-To: <1114495437.518381.140890@g14g2000cwa.googlegroups.com> References: <1114425158.092697.99030@o13g2000cwo.googlegroups.com> <1114451147.737426.207980@z14g2000cwz.googlegroups.com> <1114457804.600476.324860@o13g2000cwo.googlegroups.com> <1114470993.307543.133770@z14g2000cwz.googlegroups.com> <1114493251.818250.6580@g14g2000cwa.googlegroups.com> <1114495437.518381.140890@g14g2000cwa.googlegroups.com> Message-ID: <1114498447.291550.129980@z14g2000cwz.googlegroups.com> George Sakkis wrote: > > Oh, I overlooked this. Then the solution becomes simple: > > > > sys._getframe().f_trace > > > > Test: > > > > >>> an = Analyzer() > > >>> sys.settrace(an.trace_returns) > > >>> sys._getframe().f_trace > > at > > 0x010015D0>> > > Does this work for you non-interactively ? I tried running it from a > script or importing it from a module but it returns None. Very > strange... > > George You are right. The expression was context-dependent :-/ I had not yet the time to analyze the output of the following function but it returns stable values: def gettracefunc(): import sys i = 0 while 1: try: f_trace = sys._getframe(i).f_trace if f_trace: return f_trace i+=1 except ValueError: break Ciao, Kay From martin at v.loewis.de Sat Apr 2 02:48:21 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 02 Apr 2005 09:48:21 +0200 Subject: Attributes and built-in types In-Reply-To: References: Message-ID: <424E4E45.8090607@v.loewis.de> Dave Opstad wrote: > Is it just an implementation limitation that attributes cannot be > assigned to instances of internal types? No, not "just". Some types have a fixed set of attributes by design, whereas others allow addition of attributes. There are several reasons for this design. Performance is one of them; backwards compatibility another. Regards, Martin From merkosh at hadiko.de Tue Apr 12 12:40:17 2005 From: merkosh at hadiko.de (Uwe Mayer) Date: Tue, 12 Apr 2005 18:40:17 +0200 Subject: singleton objects with decorators References: <1113300588.335527.26290@o13g2000cwo.googlegroups.com> <1113310269.596284.136100@f14g2000cwb.googlegroups.com> <1113318042.836605.132820@o13g2000cwo.googlegroups.com> Message-ID: Tuesday 12 April 2005 17:00 pm Michele Simionato wrote: > I did not put memoize on __new__. I put it on the metaclass __call__. > Here is my memoize: > > def memoize(func): > memoize_dic = {} > def wrapped_func(*args): > if args in memoize_dic: > return memoize_dic[args] > else: > result = func(*args) > memoize_dic[args] = result > return result > wrapped_func.__name__ = func.__name__ > wrapped_func.__doc__ = func.__doc__ > wrapped_func.__dict__ = func.__dict__ > return wrapped_func > > class Memoize(type): # Singleton is a special case of Memoize > @memoize > def __call__(cls, *args): > return super(Memoize, cls).__call__(*args) I tried it out and found the following "inconsistency": >>> class Foobar(object): ... __metaclass__ = Memoize ... def __init__(self, *args): pass ... >>> Foobar(1) <__main__.Foobar object at 0x4006f7ec> >>> Foobar(2) <__main__.Foobar object at 0x4006f7cc> >>> Foobar(3) <__main__.Foobar object at 0x4006f82c> Unless I'm using it incorrectly (I haven't done much metaclass programming yet) this is the same problem was with using @memoize on __new__ and __init__. Talking so much about singletons I'm not even sure what the definition on calling a singleton with different constructor parameter values is. Anyways, a fix for that could be: class SingletonFactory(type): single = {} def __call__(cls, *args): if (cls not in SingletonFactory.single): SingletonFactory.single[cls] = super(SingletonFactory, cls).__call__(*args) return SingletonFactory.single[cls] i.e. not caching the parameter values or types. Uwe From radam2 at tampabay.rr.com Sat Apr 2 15:34:21 2005 From: radam2 at tampabay.rr.com (Ron_Adam) Date: Sat, 02 Apr 2005 20:34:21 GMT Subject: Decorator Dissection References: <4p9t419ockcg8578g6guse3a14t16orebf@4ax.com> <1112455359.773729.92080@l41g2000cwc.googlegroups.com> <6git41doqfbk01h8lsk1gl7u91qgspivrp@4ax.com> Message-ID: On Sat, 02 Apr 2005 21:04:57 +0200, "Diez B. Roggisch" wrote: >> I followed that part. The part that I'm having problems with is the >> first nested function get's the argument for the function name without >> a previous reference to the argument name in the outer frames. So, a >> function call to it is being made with the function name as the >> argument, and that isn't visable so it looks as if it's magic. > >No, its not - but I stepped into that trap before - and thought its magic :) It's magic until we understand it. ;) I get the feeling that those who have gotten to know decorators find them easy, and those who haven't, find them nearly impossible to understand. Which means there is a fairly large first few steps to get over, then it gets easy. There *is* some underlying processes being made, which is also the reason that makes them attractive. Less type/declare/organize/etc... but that is also what causes the difficulty in understanding and using them at first. >The trick is to know that > > - a decorator is a callable > - get passed a callable > - has to return a callable > >So this is the simplest decorator imaginable is: > >def identity(f): > return f > >And the decorator _syntax_ is just a python expression that has to be >_evaluated_ to a yield decorator. So > >@identity >def foo(self): > pass This much I understand. >the @identity is just the expression evaluated - to the function reference >to identity, which is callable and follows the decorator protocol - and the >_result_ of that evaluation is called with the callable in question. This tells me what it is, and what it does, but not how it works. How is the ***expression evaluated***, what is the ***decorator protocol***. Those are the parts I'm trying to understand at this point. I know this is the equivalent of looking behind the curtains to reveal the little man who is the wizard. But I can't resist. :) >So if you want to have _parametrized_ decorators, that expression is >_evaluated_ and has to yield a decorator. Like this: > There's that word again... **evaluated**. How? >def arg_decorator(arg): > def real_decorator(f): > return f > return real_decorator > >So, this works > >@arg_decorator('fooobar') >def foo(self): > pass > >@arg_decorator('fooobar') is evaluated to real_decorator (which a scope >containing arg), and _that_ gets called with foo. > So if I'm following you right? When the interpreter gets to the line @arge_decorator('fooobar') it does the following? foo = arg_decorator('fooobar')(foo)() #? (experiment with idle a bit...) Ok I got it. :) I wasn't aware that the form: result = function(args)(args) Was a legal python statement. So python has a built in mechanism for passing multiple argument sets to nested defined functions! (click) Which means this is a decorator without the decorator syntax. def arg_decorator(arg1): def real_decorator(function): def wrapper(arg2) return f(arg2) return real_decorator def foo(arg2): pass foo = arg_decorator('fooobar')(foo)(2arg) The apparent magic is the silent passing of the second two arguments. So this isn't a decorator question any more. Each argument gets passed to the next inner defined function, via... a stack(?) ;) Somehow I think I've completed a circle. LOL Cheers, Ron >HTH - bit me the first time too :) From opstad at batnet.com Fri Apr 1 15:42:17 2005 From: opstad at batnet.com (Dave Opstad) Date: Fri, 01 Apr 2005 12:42:17 -0800 Subject: Attributes and built-in types Message-ID: Is it just an implementation limitation that attributes cannot be assigned to instances of internal types? --------------------------- >>> x = 4 >>> type(x) >>> class Test(int): ... pass ... >>> y = Test(4) >>> type(y) >>> y.someattr = 10 >>> x.someattr = 10 Traceback (most recent call last): File "", line 1, in ? AttributeError: 'int' object has no attribute 'someattr' --------------------------- When I did a dir(int) there was no __dict__ entry, but a dir(Test) showed a __dict__entry, which is why (presumably) the attribute assignment worked for Test but not for int. Just curious... Dave From jerf at jerf.org Sat Apr 23 14:33:40 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Sat, 23 Apr 2005 14:33:40 -0400 Subject: Python or PHP? References: <1114254894.512656.297040@l41g2000cwc.googlegroups.com> <426A76A5.2050906@mage.hu> Message-ID: On Sat, 23 Apr 2005 20:13:24 +0200, Mage wrote: > Avoid them is easy with set_type($value,"integer") for integer values and > correct escaping for strings. "Avoiding buffer overflows in C is easy, as long as you check the buffers each time." The *existence* of a technique to avoid problems is not in question. The problem is when the language makes it easier to *not* do the checks than to do the checks. Any look at the real world shows that that pattern causes trouble, and that clearly, the mere *existence* of a way to not get in trouble is not sufficient in the general case. Despite the fact that all you have to do to avoid cutting your finger off with a saw is not stick your finger in the saw, most people, even carpentry professionals, are going to want to use finger-guards and other safety equipment. A programmer turning down such security protection (without another good reason, which does happen), is being like the guy too macho to use the finger guard; stupidity induced by arrogance, not some one no longer using training wheels. Using PHP and futzing with SQL directly is probably not a good enough reason, as surely PHP has safer libraries available. (If not, my opinion of PHP goes down another notch.) Data binding with something like SQLObject makes it *easier* to be secure than insecure; barring an out-and-out bug in SQLObject (given the nature of the requisite bug, it is extremely unlikely to have survived this long), a programmer must go *way* out of their way to introduce the SQL injection attacks that so plague PHP projects. From steven.bethard at gmail.com Mon Apr 4 17:13:47 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 04 Apr 2005 15:13:47 -0600 Subject: StopIteration in the if clause of a generator expression In-Reply-To: References: <424db34c.51543105@news.oz.net> <_2R3e.3341$7b.3033@trndny06> Message-ID: Raymond Hettinger wrote: > [Steven Bethard] > >>and I often find myself alternating >>between the two when I can't decide which one seems more Pythonic. > > Both are pythonic. > > Use a genexp when you need a generator > and use a listcomp when you need a list. So do I read this right in preferring [ for in ] over list( for in ) ? STeVe From theller at python.net Thu Apr 14 16:20:37 2005 From: theller at python.net (Thomas Heller) Date: Thu, 14 Apr 2005 22:20:37 +0200 Subject: distribute python script References: <1113501385.376681.148340@o13g2000cwo.googlegroups.com> <1113505210.693247.143930@z14g2000cwz.googlegroups.com> <1113507196.290786.264710@z14g2000cwz.googlegroups.com> Message-ID: "codecraig" writes: > Thanks so much Thomas!!! I added encodings to my setup's...here it is > > setup(console=[{"script": 'monkey_shell.py'}], options={"py2exe": > {"packages": ["encodings"]}}) > > and i did the same for the other python script. > > Thanks!! Cool. The next py2exe version will include the encodings automatically, unless this is overridden with the '-a' or '--ascii' command line option. Thomas From simon.brunning at gmail.com Wed Apr 20 08:08:54 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Wed, 20 Apr 2005 13:08:54 +0100 Subject: goto statement In-Reply-To: References: <20050420092359.81900.qmail@web8409.mail.in.yahoo.com> <42664190.6010507@i.com.ua> Message-ID: <8c7f10c60504200508486acf1a@mail.gmail.com> On 4/20/05, Maxim Kasimov wrote: > WOW, just greate! ... but i'd like to relax at some more interesting way than to comment each of rows Get a decent text editor. -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From KittyMCooper at gmail.com Wed Apr 27 19:26:02 2005 From: KittyMCooper at gmail.com (MsKitty) Date: 27 Apr 2005 16:26:02 -0700 Subject: win32ui CreateFileDialog SLOW (since the SP2 Windows XP patch?) Message-ID: <1114644362.619393.317800@l41g2000cwc.googlegroups.com> My client is used to clicking on the script name on her PC and getting a windows command line box which it runs in. Not fancy but did the job until recently... Now it can take up to 4 minutes for the file dialog box to appear. No problems with speed in PythonWin, of course, but she is not used to doing that. Any suggestions? Anyone know why it is so slow? Here is the code snippet to open her input file (output goes in the same directory so we have to get the directory path for that) try: d=win32ui.CreateFileDialog(1) d.DoModal() inputpath=d.GetPathName() inputsplit=string.split(inputpath,"\\") inputdir = string.join(inputsplit[:-1],"\\") inputname=d.GetFileName() if printit: print "input file is ",inputname try: input = open(inputname,"r") # expects text to mark up except: print "Error opening input file",inputname if inputname: print "Invalid Input File ",inputname line = raw_input() sys.exit(2) (there's another except later in the code ...) Kitty OpenSkyWebDesign.com From test1dellboy3 at yahoo.co.uk Sat Apr 2 05:01:30 2005 From: test1dellboy3 at yahoo.co.uk (test1dellboy3 at yahoo.co.uk) Date: 2 Apr 2005 02:01:30 -0800 Subject: How to reload local namespace definitions in the python interpreter? Message-ID: <1112435996.697236.231800@l41g2000cwc.googlegroups.com> Hi, I am a beginner using the python interpreter. To reduce typing effort, I created a module called "aliases.py" containing some aliases for objects I commonly use like - aliases.py : import filecmp, os, commands op = os.path go = commands.getoutput dc = filecmp.dircmp p1 = '/mnt/usbkey/flash/' p2 = '/mnt/fat32/myfiles/flash/' When I start up the interpreter, I can simply type - from aliases import * This works fine, but each time I change any of the definitions in aliases.py, I have to restart the interpreter and type "from aliases import *" again. Is there any way to reload these definitions without restarting the interpreter? -Slath From taroso at gmail.com Fri Apr 1 02:00:39 2005 From: taroso at gmail.com (TSO) Date: 31 Mar 2005 23:00:39 -0800 Subject: [python-perl] Translation review? Message-ID: Hi there, I've recently tried to translate some Perl code into Python - code is below. Is there a more Pythonic form? Also, is there a good reason why there are plans to remove lambda from the language? yrs complements-of-the-season-ly... ==== START OF CODE ## 2005-04-01 - TSO ## with apologies to Erudil import sys,math;[ vars() .__setitem__( "ham", lambda(spam):(""). join([chr(( spam/144**i)%(02*72)) for(i)in xrange( int(math.log(spam**0.5, 12)+1))])),[(lambda* spam:globals().update({} .__class__([spam])))( ham(spam),eval(ham(__spam)) )for(spam,__spam)in[ (47631497714,0x3A305499C7D37), (47159984399, 2337674),(327499859,2336509),(8901 +34553*10000, 2402179),(6303405375459,2295612),(11+ 7540504603011, 303839094),(95,2295612),(7540504603011, 303839094),(95,0x16241495E6D60314676F55F45E4D3F906),(216* 10529,0x1053924DE35309345),(0x6DB401B64DC,0x262efd)]]and(_) (ham(231280211),[bacon(spam,ham(0x65936781522))()for(spam)in crispy(bacon(bacon((bacon(eggs,ham(0x1051936D9600B6F4F)))(0) ,ham(6296985467094)),ham(390129778476214073077203)))]+[bacon( ham(32),ham(48473858995))()]),_(ham(110),(lovely)(Spam(cheese ,SPAM))),_(ham(231280211),[[int((lambda spam:bacon(bacon(ham (32),ham(48473858995))(),ham(330651610))([ham(6961)[bacon(( spam),ham(+906698009388057))()]for(spam)in(spam)]))(spam+ spam_),2)for(spam,spam_)in(lambda(spam):[(spam)for(spam) in(_spam)(spam[::2],spam[1::2])])(list(_spam(*spam)))] for(spam) in(lambda(spam):list(_spam(spam[::2],spam [1::2])))([(spam+ham (32)*n)[:n]for( spam)in(SPAM) ])])or(Spam)(( bacon)( bacon(eggs,ham (7233055643059 )),ham(224343 + 11402701*10** 6+ 30804988*10** 14) ),[(spam)for spam in(_spam)(*[ (ham( 668732698837 )%(spam_ ,_spam),ham( 668732698 *1000+837)%( _spam,spam_ ))for(_spam, spam_)in(_spam) (*Spam(lambda (spam_,_spam): [bacon(bacon (ham(32),ham( 0xB494463B3) )(),ham(610+ 330651000))( [_spam[spam]for(spam)in(spam)[::spam_ *-2+1]])for(spam)in(SPAM)],Ham([ham (0x40BA541813CECF0323A994C40AA00) ,ham(412853488783846916352+ 20980637114201*10**21 )])))])])] == END OF CODE From newsuser at stacom-software.de Tue Apr 26 05:06:24 2005 From: newsuser at stacom-software.de (Alexander Eisenhuth) Date: Tue, 26 Apr 2005 11:06:24 +0200 Subject: Howto debug c++ (SWIG) extension under Windows Message-ID: Hi alltogether, I use ActivePython 2.4.1 , also the debug part from http://ftp.activestate.com/ActivePython/etc/ and VC 6.0 unter Windows XP. I can't figure out howto debug my c++ extension. If i compile it as release version, I've of course no chance to set a breakpoint. If I compile as debug I get the Error-window: ... missing MSVCR71D.dll ... when I try to start or debug my application. Now I've only ;-) two questions: 1) Is it possible to debug a C++ extension in that environment anyhow ? 2) How do I have to setup the development environment in that I can debug ? Thank you in advance for your ideas, links, help, hints or whatever ... Regards Alexander From usenet at zly_adres.com Fri Apr 29 21:48:37 2005 From: usenet at zly_adres.com (CYBER) Date: Sat, 30 Apr 2005 03:48:37 +0200 Subject: [wxPython] Many wxPanel forms in 1 wxFrame Message-ID: Is this possible to create 1 wxFrame and register more than 1 wxPanel in it. And select the one you want to show at the moment ? I'm trying to implement a multistep wizard under wxPython. I need to be able to hide and show windows inside my frame. Help :) From martin at v.loewis.de Mon Apr 11 17:59:05 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 11 Apr 2005 23:59:05 +0200 Subject: NSInstaller Vs. Inno Setup In-Reply-To: <1113250756.207904.29670@f14g2000cwb.googlegroups.com> References: <1113250756.207904.29670@f14g2000cwb.googlegroups.com> Message-ID: <425AF329.6030603@v.loewis.de> dcrespo wrote: > Any comments? MSI. Martin From ivanlan at pauahtun.org Fri Apr 1 15:32:36 2005 From: ivanlan at pauahtun.org (Ivan Van Laningham) Date: Fri, 01 Apr 2005 13:32:36 -0700 Subject: string goes away References: <20050401113753.2hhq78s8z7nocwoo@mcherm.com> Message-ID: <424DAFE4.A0F75D9A@pauahtun.org> Hi All-- Michael Chermside wrote: > > The REAL lesson here is that you shouldn't follow any "optimization" > rules without actually testing them. If you don't have time to test, > then just don't optimize... write whatever is most readable. If you > NEED more speed, then profiling and testing will show you what to > fix. (Using a better algorithm is a different story... do that > whenever you need it.) > Tim Peters sayeth, "Premature Optimization is the Root of All Evil." And he is not kidding. Ever try to persuade a boatload of Java programmers that? Metta, Ivan ---------------------------------------------- Ivan Van Laningham God N Locomotive Works http://www.andi-holmes.com/ http://www.foretec.com/python/workshops/1998-11/proceedings.html Army Signal Corps: Cu Chi, Class of '70 Author: Teach Yourself Python in 24 Hours From gene.tani at gmail.com Fri Apr 1 20:36:44 2005 From: gene.tani at gmail.com (gene.tani at gmail.com) Date: 1 Apr 2005 17:36:44 -0800 Subject: Ternary Operator in Python In-Reply-To: References: Message-ID: <1112405804.458174.114250@o13g2000cwo.googlegroups.com> The good ol' DiveInto says: http://diveintopython.org/power_of_introspection/and_or.html#d0e9975 http://aspn.activestate.com/ASPN/Python/Cookbook/Recipe/52310 Diez B. Roggisch wrote: > praba kar wrote: > > > Dear All, > > I am new to Python. I want to know how to > > work with ternary operator in Python. I cannot > > find any ternary operator in Python. So Kindly > > clear my doubt regarding this > > There is no ternary operator in python. There are several idioms that can be > used to emulate one to a certain degree - but they are scolwed on by quite > a few people. So better to not use them and just do it in a if: else: > clause. > > -- > Regards, > > Diez B. Roggisch From captainrobbo at gmail.com Fri Apr 8 11:51:49 2005 From: captainrobbo at gmail.com (Andy Robinson) Date: 8 Apr 2005 08:51:49 -0700 Subject: Tutorial at Python-UK, Oxford, 19 May - handful of places left Message-ID: <1112975509.841509.287200@o13g2000cwo.googlegroups.com> Michele Simionato is giving a full day tutorial titled "The Wonders of Python" at the UK Python Conference, Randolph Hotel, Oxford on 19 May. (This replaces Alex Martelli, who is now working for Google in California). The program is here: https://www.accu.org/conference/python_tutorial.html This is a fantastic opportunity to boost your Python skills and catch up on the newer features of the language, for a fraction of the price of a professional training course. The course costs ?135 for ACCU members and ?160 for non-ACCU. There are still a few places left; anyone wishing to attend should directly contact the organisers, Archer Yates Associates, whose details are on the bottom left corner of the page. Best Regards Andy Robinson UK Python Conference program chair From MrJean1 at gmail.com Sun Apr 17 04:30:06 2005 From: MrJean1 at gmail.com (MrJean1) Date: 17 Apr 2005 01:30:06 -0700 Subject: whitespace , comment stripper, and EOL converter In-Reply-To: <1113713669.255207.39580@f14g2000cwb.googlegroups.com> References: <2ab23d7a.0504120857.14ef094a@posting.google.com> <2ab23d7a.0504130738.622a3605@posting.google.com> <1113410094.102181.315080@l41g2000cwc.googlegroups.com> <1113680973.635576.310510@g14g2000cwa.googlegroups.com> <1113713669.255207.39580@f14g2000cwb.googlegroups.com> Message-ID: <1113726606.945042.71820@z14g2000cwz.googlegroups.com> There is an issue with both my and your code: it only works if doc strings are triple quoted and if there are no other triple quoted strings in the Python code. A triple quoted string used in an assignment will be removed, for example this case s = '''this string should not be removed''' It is still unclear how to distinguish doc strings from other strings. Also, I have not checked the precise Python syntax, but doc strings do not need to be enclosed by triple quotes. A single quote may be allowed too. Maybe this rule will work: a doc string is any string preceded by a COLON token followed by zero, one or more INDENT or NEWLINE tokens. Untested! /Jean Brouwers M.E.Farmer wrote: > Thanks Jean, > I have thought about adding docstrings several times, but I was stumped > at how to determine a docstring from a regular tripleqoted string ;) > I have been thinking hard about the problem and I think I have an idea. > If the line has nothing before the start of the string it must be a > docstring. > Sounds simple enough but in Python there are 12 or so 'types' of > strings . > Here is my crack at it feel free to improve it ;) > I reversed the logic on the comments and docstrings so I could add a > special mode to docstring stripping ...pep8 mode . > Pep8 mode only strips double triple quotes from your source code > leaving the offending single triple quotes behind. Probably just stupid > but someone might find it usefull. > ###################################################################### > # Python source stripper > ###################################################################### > > import os > import sys > import token > import keyword > import StringIO > import tokenize > import traceback > __credits__ = ''' > J?rgen Hermann > M.E.Farmer > Jean Brouwers > ''' > __version__ = '.8' > __author__ = 'M.E.Farmer' > __date__ = 'Apr 16, 2005,' \ > 'Jan 15 2005,' \ > 'Oct 24 2004' \ > > > ###################################################################### > > class Stripper: > """Python source stripper > """ > def __init__(self, raw): > self.raw = raw > > def format(self, out=sys.stdout, comments=0, docstrings=0, > spaces=1, untabify=1, eol='unix'): > """ strip comments, > strip docstrings, > strip extra whitespace and lines, > convert tabs to spaces, > convert EOL's in Python code. > """ > # Store line offsets in self.lines > self.lines = [0, 0] > pos = 0 > # Strips the first blank line if 1 > self.lasttoken = 1 > self.temp = StringIO.StringIO() > self.spaces = spaces > self.comments = comments > self.docstrings = docstrings > > if untabify: > self.raw = self.raw.expandtabs() > self.raw = self.raw.rstrip()+' ' > self.out = out > > # Have you ever had a multiple line ending script? > # They can be nasty so lets get them all the same. > self.raw = self.raw.replace('\r\n', '\n') > self.raw = self.raw.replace('\r', '\n') > self.lineend = '\n' > > # Gather lines > while 1: > pos = self.raw.find(self.lineend, pos) + 1 > if not pos: break > self.lines.append(pos) > > self.lines.append(len(self.raw)) > self.pos = 0 > > # Wrap text in a filelike object > text = StringIO.StringIO(self.raw) > > # Parse the source. > ## Tokenize calls the __call__ > ## method for each token till done. > try: > tokenize.tokenize(text.readline, self) > except tokenize.TokenError, ex: > traceback.print_exc() > > # Ok now we write it to a file > # but we also need to clean the whitespace > # between the lines and at the ends. > self.temp.seek(0) > > # All this should be written into the > # __call__ method just haven't yet... > > # Mac CR > if eol == 'mac': > self.lineend = '\r' > # Windows CR LF > elif eol == 'win': > self.lineend = '\r\n' > # Unix LF > else: > self.lineend = '\n' > > for line in self.temp.readlines(): > if spaces == -1: > self.out.write(line.rstrip()+self.lineend) > else: > if not line.isspace(): > self.lasttoken=0 > self.out.write(line.rstrip()+self.lineend) > else: > self.lasttoken+=1 > if self.lasttoken<=self.spaces and self.spaces: > self.out.write(self.lineend) > > def __call__(self, toktype, toktext, > (srow,scol), (erow,ecol), line): > """ Token handler. > """ > # calculate new positions > oldpos = self.pos > newpos = self.lines[srow] + scol > self.pos = newpos + len(toktext) > > # kill comments > if self.comments: > if toktype == tokenize.COMMENT: > return > > # kill doc strings > if self.docstrings: > # Assume if there is nothing on the > # left side it must be a docstring > if toktype == tokenize.STRING and \ > line.lstrip(' rRuU')[0] in ["'",'"']: > t = toktext.lstrip('rRuU') > if (t.startswith('"""') and > (self.docstrings == 'pep8' or > self.docstrings =='8')): > return > elif t.startswith('"""') or t.startswith("'''"): > return > > # handle newlines > if toktype in [token.NEWLINE, tokenize.NL]: > self.temp.write(self.lineend) > return > > # send the original whitespace > if newpos > oldpos: > self.temp.write(self.raw[oldpos:newpos]) > > # skip indenting tokens > if toktype in [token.INDENT, token.DEDENT]: > self.pos = newpos > return > > # send text to the temp file > self.temp.write(toktext) > return > ###################################################################### > > def Main(): > import sys > if sys.argv[1]: > filein = open(sys.argv[1]).read() > Stripper(filein).format(out=sys.stdout, > comments=0, docstrings=1, untabify=1, eol='win') > ###################################################################### > > if __name__ == '__main__': > Main() From ramon.aragues at gmail.com Fri Apr 29 06:28:18 2005 From: ramon.aragues at gmail.com (ramon.aragues at gmail.com) Date: 29 Apr 2005 03:28:18 -0700 Subject: Persistent python object and the Web References: <1114107302.827987.230560@l41g2000cwc.googlegroups.com> <426924f0.244123250@news.oz.net> Message-ID: <1114770498.332741.133090@l41g2000cwc.googlegroups.com> Thanks to all for your help. My graphs are huge (and contain much more information than the list of nodes and their edges... I am working with protein-protein interaction networks) so I have decided to have a persistent object on the server. I first had to make my objects "pickable" (which was not obvious, since they also contain database connections) but I think now I am on the right way. The only problem I see is that the web interface will be slower, since it has to "load graph-process it -dump graph" after each command, but I guess that is the price I'll have to pay. Thanks a lot again! Ramon From lbates at syscononline.com Thu Apr 21 10:59:54 2005 From: lbates at syscononline.com (Larry Bates) Date: Thu, 21 Apr 2005 09:59:54 -0500 Subject: How can I verify that a passed argument is an interible collection? In-Reply-To: References: Message-ID: <4267BFEA.9070206@syscononline.com> Others may know better ways but the 2 I know of are: 1) If you know that the arguments will be lists or tuples you can use isinstance(). if not isinsance(arg, (list, tuple): print "arg must be list or tuple) 2) Or if you not you could see if the argument has next and __iter__ methods (more general solution) if hasattr(arg, 'next') and not hasattr(arg, '__iter__'): # perform work on iterable else: print "arg must be an iterable" Larry Bates Charles Krug wrote: > List: > > I'm working on some methods that operate on (mathematical) vectors as > in: > > def Convolution(x, y) > """Returns a list containing the convolution of vectors x and y""" > > Is there any way to determine at runtime that x and y are iterible > collections? > > Do I *coughs* simply *coughs* trap the exception created by: > > for v in x: > > when v is a scaler quantity? > > Thanks > > > Charles > From vishnu at acmet.com Mon Apr 25 05:57:56 2005 From: vishnu at acmet.com (Vishnu) Date: Mon, 25 Apr 2005 15:27:56 +0530 Subject: Changing a line in a text file In-Reply-To: <1114421951.029066.190120@g14g2000cwa.googlegroups.com> Message-ID: <001601c5497d$4304e0e0$0c00a8c0@vishnu> Hi, Here is the program for replacing 'line2' with 'newline'. inp_file.txt contains, line1 line2 line3 line4 EOF #-- Program starts #Get the inp file in to a list inp_file_list = [x for x in open('inp_file.txt')] #modify the desired line, Note: you should include newline inp_file_list[1] = 'xxx\n' #Open the same file write_to_file = open('inp_file.txt', 'w') #write the list in to the file write_to_file.writelines(inp_file_list) #close the file write_to_file.close() #-- Program ends Hope someone will give better idea. HTH, Vishnu -----Original Message----- From: python-list-bounces+vishnu=acmet.com at python.org [mailto:python-list-bounces+vishnu=acmet.com at python.org] On Behalf Of kah Sent: Monday, April 25, 2005 3:09 PM To: python-list at python.org Subject: Changing a line in a text file How do I change a line in a file?? For example I have the follwing text in my file: line1 line2 line3 line4 How do I replace 'line2' with 'newline'. Since the write operation in python will overwrite everything. Regards, Kah -- http://mail.python.org/mailman/listinfo/python-list From peter at engcorp.com Wed Apr 20 11:52:45 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 20 Apr 2005 11:52:45 -0400 Subject: Why Python does *SLICING* the way it does?? In-Reply-To: References: <1113976729.450677.261130@o13g2000cwo.googlegroups.com> <_Lm9e.23143$Xm3.17864@trndny01> Message-ID: Terry Hancock wrote: > However, I used to make "off by one" errors all the time in both C and Fortran, > whereas I hardly ever make them in Python. This should probably be the overriding concern in this case. I can't remember the last time I made an off-by-one error in Python (or, really, whether I ever have), whereas I can't remember the last C program I wrote which didn't have one. > So I like Python's slicing because it "bites *less*" than intervals in C or Fortran. +1 QOTW From fdreger at amiga.pl Wed Apr 27 06:53:18 2005 From: fdreger at amiga.pl (Filip Dreger) Date: Wed, 27 Apr 2005 12:53:18 +0200 Subject: Can .py be complied? References: <426ec8f7_2@rain.i-cable.com> <426f562f$1_3@rain.i-cable.com> Message-ID: U?ytkownik "monkey" napisa? w wiadomo?ci news:426f562f$1_3 at rain.i-cable.com... > If using Jython to complie, is the end-user need JRE instead of > Python > installed, or need both of them? Only JRE. Just like Java. >> I don't know the exact details, but try using the compiled Python >> scripts (bytecode). I believe they are semi-optimized and platform >> independent. They are the .pyc and .pyo files generated when the >> script >> is run. > Is that means a .py convert to .pyc or .pyo, without the need of > "make file" > as using py2exe? .pyc files are generated every time a module (any .py file can be a module) is imported. So if you have a program, say, example.py, you just start the python interpreter and write: >>> import example And then example.pyc will appear beside example.py. This new file does not require example.py (you can even delete it), and works on any computer with Python installed (on Windows you can just double-click it) If you start the Python interpreter using: python -OO (if you are using Windows, you shoud start the interpreter from the command line, probably something like: c: cd \ python24\python -OO) and then import your example.py, you will get a file example.pyo, which is also stripped of any documentation strings (a bit harder to decode). regards, Filip Dreger From grante at visi.com Wed Apr 27 12:12:37 2005 From: grante at visi.com (Grant Edwards) Date: Wed, 27 Apr 2005 16:12:37 -0000 Subject: Can .py be complied? References: <426ec8f7_2@rain.i-cable.com> <426f562f$1_3@rain.i-cable.com> <116v84ftiq01ucb@corp.supernews.com> <426fb233$1_2@rain.i-cable.com> Message-ID: <116vefldolc6p88@corp.supernews.com> On 2005-04-27, monkey wrote: >> py2exe has nothing to do with C or make files. You create a >> setup.py file containing a couple lines of python. You run >> that python program, and you end up with an .exe file and some >> associated .dll files. I typically use inno-setup to create >> an installer.exe that creates a desktop icon and start-menu >> entry, but that's optional. > > Is py2exe used to make a .exe file to install .py, or make the self-contain > .exe file of the program itself? The latter. It's not completely self contained, there is an ..exe and some dll files that need to be distributed together. It's explained very clearly by the py2exe web site: http://starship.python.net/crew/theller/py2exe/ Never used google before? Just go to www.google.com and type in py2exe. Click "search". It's the first hit. -- Grant Edwards grante Yow! Is something VIOLENT at going to happen to a visi.com GARBAGE CAN? From mwinrock at frontiernet.net Sat Apr 2 18:28:17 2005 From: mwinrock at frontiernet.net (Mark Winrock) Date: Sat, 02 Apr 2005 23:28:17 GMT Subject: instance name In-Reply-To: <99z3e.1157607$35.42889387@news4.tin.it> References: <99z3e.1157607$35.42889387@news4.tin.it> Message-ID: max(01)* wrote: > hi. > > is there a way to define a class method which prints the instance name? > > e.g.: > > >>> class class_1: > ... def myName(self): > ... ????what should i do here???? > ... > >>> instance_1 = class_1() > >>> instance_1.myName() > 'instance_1' > >>> > > bye > > macs macs, The object instance doesn't know about the identifier to which you assigned it (but see my example below using the inspect module). If you are just trying to identify different instances, you can get a unique instance identifier from hash() function hash(instance1) or self.__hash__(), or hash(self) from within the object The default __str__ for a class will normally return something similar with more information , so that when you print instance_1 you get a string in the following format: The following is a very, very, very weak example of how you might use inspect to get the information you want. This is not a robust example at all, and I imagine it could have many ways it will fail. The init uses inspect information to dip into the source file and parse out the info -- like I said, this is not a robust parse. # ------------------------ import os,sys class class_1(object): def __init__(self): import inspect self.lineno = inspect.currentframe().f_back.f_lineno self.filename = inspect.currentframe().f_back.f_code.co_filename self.initial_instance = None try: # i'm not sure if filename is full path or not at this time f=open(self.filename,'r') lines=f.readlines() s = lines[self.lineno-1] split = s.split() try: # find the assignment if possible i = split.index('=') self.initial_instance = split[i-1] except ValueError: pass finally: f.close() def myName(self): print 'my initial instance was \'%s\''%(self.initial_instance) if __name__ == '__main__': # two straight up examples instance_1 = class_1() instance_2 = class_1() instance_1.myName() instance_2.myName() # class_1().myName() c = instance_1 c.myName() # ----------------------------------------------- I got the following results: my initial instance was 'instance_1' my initial instance was 'instance_2' my initial instance was 'None' my initial instance was 'instance_1' Best-regards, Mark From programmer.py at gmail.com Mon Apr 25 22:30:18 2005 From: programmer.py at gmail.com (Jaime Wyant) Date: Mon, 25 Apr 2005 21:30:18 -0500 Subject: Pythonic way to do static local variables? In-Reply-To: <_xgbe.128633$cg1.54987@bgtnsc04-news.ops.worldnet.att.net> References: <_xgbe.128633$cg1.54987@bgtnsc04-news.ops.worldnet.att.net> Message-ID: Well, if you're a c++ programmer, then you've probably ran into `functors' at one time or another. You can emulate it by making a python object that is `callable'. class functor: def __init__(self): self.ordered_sequence = [1, 2, 3, 4, 5] def __call__(self, arg1, arg2): self.ordered_sequence.extend((arg1,arg2)) self.ordered_sequence.sort() >>> f = functor() >>> f(3,5) >>> f.ordered_sequence [1, 2, 3, 3, 4, 5, 5] Hope that helps some. jw On 4/25/05, Charles Krug wrote: > I've a function that needs to maintain an ordered sequence between > calls. > > In C or C++, I'd declare the pointer (or collection object) static at > the function scope. > > What's the Pythonic way to do this? > > Is there a better solution than putting the sequence at module scope? > > Thanks. > > -- > http://mail.python.org/mailman/listinfo/python-list > From greg at cosc.canterbury.ac.nz Thu Apr 21 21:29:48 2005 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Fri, 22 Apr 2005 13:29:48 +1200 Subject: Why Python does *SLICING* the way it does?? In-Reply-To: References: <1113976729.450677.261130@o13g2000cwo.googlegroups.com> <87r7h5lk5a.fsf@wilson.rwth-aachen.de> Message-ID: <3cr2cnF6locm6U2@individual.net> Roy Smith wrote: > What would actually be cool is if Python were to support the normal math > notation for open or closed intervals. > > foo = bar (1, 2) > foo = bar (1, 2] > foo = bar [1, 2) > foo = bar [1, 2] > > That would certainly solve this particular problem, but the cost to the > rest of the language syntax would be rather high :-) Not to mention the sanity of everyone's editors when they try to do bracket matching! -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From steffann at nederland.net Wed Apr 20 08:08:37 2005 From: steffann at nederland.net (Sander Steffann) Date: Wed, 20 Apr 2005 14:08:37 +0200 Subject: goto statement In-Reply-To: <8c7f10c6050420031238ecc69a@mail.gmail.com> Message-ID: <2B1A983EDCEC3447B22632B64F7264600B74B5@bill.office.computel.nl> On 4/20/05, praba kar wrote: > In Python what is equivalent to goto statement An old user-friendly cartoon that might be relevant: http://ars.userfriendly.org/cartoons/?id=20000506 Have fun :-) Sander From mwakabayashi at gmail.com Tue Apr 19 20:17:55 2005 From: mwakabayashi at gmail.com (Mike) Date: 19 Apr 2005 17:17:55 -0700 Subject: Writing to stdout and a log file Message-ID: <1113956275.697789.324730@o13g2000cwo.googlegroups.com> I would like my 'print' statements to send its output to the user's screen and a log file. This is my initial attempt: class StdoutLog(file): def __init__(self, stdout, name='/tmp/stdout.log', mode='w',bufsize=-1): super(StdoutLog, self).__init__(name,mode,bufsize) self.stdout = stdout def write(self, data): self.stdout.write(data) self.write(data) import sys sys.stdout = StdoutLog(sys.stdout) print 'STDOUT', sys.stdout When the program is run the string is written to the log file but nothing appears on my screen. Where's the screen output? It looks like the superclass's write() method is getting called instead of the StdoutLog instance's write() method. The python documentation says 'print' should write to sys.stdout.write() but that doesn't seem to be happening. Any idea what's going one? Or ideas on how to debug this? Thanks, Mike From peter at engcorp.com Fri Apr 22 17:41:00 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 22 Apr 2005 17:41:00 -0400 Subject: Python licence again In-Reply-To: <87fyxilehj.fsf@pobox.com> References: <1114197761.019100.38890@o13g2000cwo.googlegroups.com> <87fyxilehj.fsf@pobox.com> Message-ID: John J. Lee wrote: > I will never pronounce thorough 'thurrow', though. One must draw a > line. How *do* you pronounce it? "Thurrow" seems to match how I say the word, along with everyone else I've ever met (until now?). -Peter From jstroud at mbi.ucla.edu Fri Apr 15 00:58:08 2005 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 14 Apr 2005 21:58:08 -0700 Subject: question about functions In-Reply-To: <1113540288.415656.325750@l41g2000cwc.googlegroups.com> References: <1113540288.415656.325750@l41g2000cwc.googlegroups.com> Message-ID: <200504142158.08032.jstroud@mbi.ucla.edu> Just pass a list. E.g.: # start of ascript def my_funk(alist): print "the first argument: %s" % alist[1] print "the second argument: %s" % alist[2] mylist = ['wuzzup,','g?'] my_funk(mylist) # end of ascript Here is the output you expect: the first argument: wuzzup, the second argument: g? On Thursday 14 April 2005 09:44 pm, chris patton wrote: > Hi everyone. > > I have a question about passing arguments to python functions. Is there > any way to make this job act like Perl? > > sub my_funk { > > print "the first argument: $_[0]\n"; > print "the second argument: $_[1]\n"; } > > In other words, can I call the arguments from a list? -- James Stroud, Ph.D. UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From rkern at ucsd.edu Mon Apr 25 10:50:26 2005 From: rkern at ucsd.edu (Robert Kern) Date: Mon, 25 Apr 2005 07:50:26 -0700 Subject: New versions of numarray? In-Reply-To: <1hvp61ttgpa9fsplvm9vkrd7io9d60vum9@4ax.com> References: <1hvp61ttgpa9fsplvm9vkrd7io9d60vum9@4ax.com> Message-ID: Matt Feinstein wrote: > Hi-- > I notice that there are some new versions of numarray available for > download-- is there any documentation on what's new/fixed/broken? You could ask on the numarray list. When you do, you should specify what version you're coming from so you can get the appropriate answer. Or you can search Google Groups in comp.lang.python.announce for the numarray announcements. They contain the information you seek. http://groups-beta.google.com/group/comp.lang.python.announce -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From rdm at rcblue.com Wed Apr 13 05:06:11 2005 From: rdm at rcblue.com (Dick Moores) Date: Wed, 13 Apr 2005 02:06:11 -0700 Subject: Compute pi to base 12 using Python? Message-ID: <6.2.1.2.2.20050413020222.060a2eb0@rcblue.com> I need to figure out how to compute pi to base 12, to as many digits as possible. I found this reference, , but I really don't understand it well enough. Could someone show me how to do what I need? Thanks, Dick Moores rdm at rcblue.com From matthew_shomphe at countrywide.com Fri Apr 1 14:48:56 2005 From: matthew_shomphe at countrywide.com (Matt) Date: 1 Apr 2005 11:48:56 -0800 Subject: System bell References: <1112310983.885273.251200@f14g2000cwb.googlegroups.com> Message-ID: <1112384936.858123.291170@f14g2000cwb.googlegroups.com> Serves me right for blindlyrunning things from IDLE. This does work (tested on WinXP only): import os os.system('echo \a') From michele.simionato at gmail.com Mon Apr 4 01:00:09 2005 From: michele.simionato at gmail.com (Michele Simionato) Date: 3 Apr 2005 22:00:09 -0700 Subject: help with python-devel!!! In-Reply-To: References: <1112560641.532271.242920@g14g2000cwa.googlegroups.com> Message-ID: <1112590809.737371.194100@z14g2000cwz.googlegroups.com> Just give (as root) # urpmi python-devel (assuming you have configured urpmi properly, Google for "easy urpmi"). Michele Simionato From fredrik at pythonware.com Sun Apr 24 07:02:44 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 24 Apr 2005 13:02:44 +0200 Subject: python sizeof ? References: <1114333872.720156.255190@g14g2000cwa.googlegroups.com> Message-ID: "ajikoe at gmail.com" > How can I get the size of an object in python..? you can't, and the size in bytes is mostly meaningless. if you're looking for the size of a serialized/marshalled python object, use len(). > analog with c sizeof? Python's not C. for more discussion, see: http://www.artima.com/forums/flat.jsp?forum=181&thread=67617 From kent37 at tds.net Fri Apr 22 17:23:32 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 22 Apr 2005 17:23:32 -0400 Subject: xmlrpclib.Server - how to disconnect In-Reply-To: <1114195692.790677.204010@o13g2000cwo.googlegroups.com> References: <1114195692.790677.204010@o13g2000cwo.googlegroups.com> Message-ID: <42696707$1_3@newspeer2.tds.net> codecraig wrote: > Hi, > If I create a connection to a and XML-RPC server, how can the client > disconnect from the server? > > CLIENT: > url = "http://1.1.1.1:1234" > server = xmlrpclib.Server(url) > > server.doSomething() > > now how do i disconnect my client from the server? Are you sure this is a problem? xmlrpc uses HTTP/1.0 to connect. Looking at the code it seems to close the connection after each request. Kent From sjmachin at lexicon.net Sun Apr 10 21:46:20 2005 From: sjmachin at lexicon.net (John Machin) Date: Mon, 11 Apr 2005 11:46:20 +1000 Subject: Dictonary persistance weirdness References: Message-ID: <2uij515umrjnma9o0nhbv4arm3katvv6pj@4ax.com> On Sun, 10 Apr 2005 19:07:23 -0300, Gonzalo Sainz-Tr?paga (GomoX) wrote: >-- wrappers.py ------------------------- >class VarsWrapper: > def __init__(self,req): > self.fs = util.FieldStorage(req) > > def get_vars(): > d = {} > for each in self.fs.list: > self.d[x.name] = x.value > return d > Are you sure that is the code that you are executing? What is "x"? What is "self.d"? "each" is not used. Even if "x" and "self.d" do exist, the for loop will do nothing, and the method will return an empty dictionary. You weren't trying to "optimise" the references to self.d inside the loop, were you? Making the charitable assumptions that d and self.d are the same thing and so are "x" and "each": Assuming self.d does exist, why does it exist? I.e for what reason do you want the data to persist? Could its persistence be the cause of your problem? Are you sure you are not accidentally always referring to the same VarsWrapper instance? Is that all that VarsWrapper contains? Seems to me like an unnecessary and possibly confusing convolution. If you "own" util.FieldStorage, then giving it an as_dictionary() method might be a good idea. Otherwise a simple wrapper *function* that replaces your two-step __init__ and get_vars would be a not unreasonable idea; there's no law that says that everything must be a class. Are you sure you don't have a dict as a default arg somewhere, like in def handle(self, vars={}) ?? HTH, John From rkern at ucsd.edu Fri Apr 22 21:42:39 2005 From: rkern at ucsd.edu (Robert Kern) Date: Fri, 22 Apr 2005 18:42:39 -0700 Subject: Python licence again In-Reply-To: References: <42694858.1060702@geochemsource.com> Message-ID: John Machin wrote: > On Fri, 22 Apr 2005 17:26:19 -0700, Robert Kern > wrote: > > > >>While you can, sort of, and people have already pointed out the >>appropriate web page to you, I ask that you *don't* use the PSF License. >>The PSF License uses proper nouns that you will have to change[1]. > > > and don't forget the pronouns ... > > Seen in a too-hasty copy-paste-edit of the BSD licence: > > IN NO EVENT SHALL OR ITS CONTRIBUTORS BE > LIABLE ... Yes, I think I've been guilty of that from time to time, too. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From m at m.com Wed Apr 27 09:43:16 2005 From: m at m.com (monkey) Date: Wed, 27 Apr 2005 21:43:16 +0800 Subject: Can .py be complied? References: <426ec8f7_2@rain.i-cable.com> <1114569158.396231.45460@z14g2000cwz.googlegroups.com> <1114569525.807638.48640@l41g2000cwc.googlegroups.com> Message-ID: <426f96f4$1_2@rain.i-cable.com> > > But those files can be decompyled. > Hi, so which way to go? From bjourne at gmail.com Thu Apr 14 08:15:33 2005 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Thu, 14 Apr 2005 14:15:33 +0200 Subject: A little request about spam In-Reply-To: References: <1113416856.914310.63930@l41g2000cwc.googlegroups.com> Message-ID: <740c3aec05041405157cb90625@mail.gmail.com> Please do not reply to spam. Replying to spam makes it much harder for spam filters to catch all the spam or will produce very many false positives. Atleast that's how gmail's filter works. And if you must reply, please change the subject line. On 13 Apr 2005 17:50:06 -0500, "."@bag.python.org <"."@bag.python.org> wrote: > Nuf said. > -- > http://mail.python.org/mailman/listinfo/python-list > -- mvh Bj?rn From oren at REMOVETHIS1.hishome.net Mon Apr 18 14:39:48 2005 From: oren at REMOVETHIS1.hishome.net (Oren Tirosh) Date: 18 Apr 2005 11:39:48 -0700 Subject: Removing dictionary-keys not in a set? References: <1113824946.525441.285760@l41g2000cwc.googlegroups.com> Message-ID: "Tim N. van der Leeuw" wrote in message news:<1113824946.525441.285760 at l41g2000cwc.googlegroups.com>... > Hi, > > I'd like to remove keys from a dictionary, which are not found in a > specific set. Here's my magic English-to-Python translator: "I'd like to ... keys which ..." -> "for key in" "keys from a dictionary" -> "set(dictionary)" "not found in a specific set" -> "-specificset" "... remove keys ..." -> "del dictionary[key]" Putting it all together: >>> for key in set(dictionary)-specificset: ... del dictionary[key] Oren From fritoj at netscape.net Fri Apr 1 12:52:06 2005 From: fritoj at netscape.net (coffeebug) Date: 1 Apr 2005 09:52:06 -0800 Subject: numeric module References: <1112377090.192124.303640@o13g2000cwo.googlegroups.com> Message-ID: <1112377926.560904.99110@f14g2000cwb.googlegroups.com> I don't know much here...but is there an assumption you're making about the machine word size to be greather than 24 bits? Also, more to the point, does the function zeros() instantiate a two-dimensional table? If so, does it populate the table with any values? The error looks like tbl[ ][ ] doesn't get defined. Thanks for patience! From rpmuller at gmail.com Wed Apr 6 22:55:58 2005 From: rpmuller at gmail.com (RickMuller) Date: 6 Apr 2005 19:55:58 -0700 Subject: sorting a list and counting interchanges In-Reply-To: <7xr7hn8jba.fsf@ruckus.brouhaha.com> References: <1112826641.728979.278530@f14g2000cwb.googlegroups.com> <6p1951pop1pfh3j57r7gg568cn3bo4c7lg@4ax.com> <7xr7hn8jba.fsf@ruckus.brouhaha.com> Message-ID: <1112842558.389934.120030@z14g2000cwz.googlegroups.com> The combinatorics application is very close, since we use A(N) to represent fermions in quantum mechanics. From jepler at unpythonic.net Sun Apr 10 14:03:51 2005 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Sun, 10 Apr 2005 13:03:51 -0500 Subject: Why does StringIO discard its initial value? In-Reply-To: References: Message-ID: <20050410180350.GA19163@unpythonic.net> Maybe this short interactive session can give you an idea why. >>> from StringIO import StringIO >>> b = StringIO("123456789") >>> b.tell() 0 >>> b.write("abc") >>> b.getvalue() 'abc456789' >>> b.tell() 3 StringIO seems to operate like a file opened with "r+" (If I've got my modes right): it is opened for reading and writing, and positioned at the beginning. In my example, the write of 3 bytes overwrites the first 3 bytes of the file and leaves the rest intact. In your example your first write overwrote the whole initial contents of the file, so you couldn't notice this effect. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From lucio.torre at gmail.com Tue Apr 19 10:56:51 2005 From: lucio.torre at gmail.com (Lucio Torre) Date: 19 Apr 2005 07:56:51 -0700 Subject: ANN: Python 2.3.2 for PalmOS available In-Reply-To: References: <1113608405.558884.235890@f14g2000cwb.googlegroups.com> <1113830286.364709.164740@z14g2000cwz.googlegroups.com> Message-ID: <1113922611.915845.256360@o13g2000cwo.googlegroups.com> Klaus Alexander Seistrup wrote: > Lucio Torre wrote: > > Say, are floats implemented? Comparisons seem to work, but print'ing > doesn't: > > #v+ > > >>> 1.0 > 0.5 > True > >>> print 1.23 > %.*g > >>> > > I think thats a problem with the printf implementation. Im using one that came with codewarrior and maybe it doesnt parse %.*g .. (never seen that format before).. Lucio. From ritterhaus at yahoo.com Wed Apr 6 17:02:25 2005 From: ritterhaus at yahoo.com (ritterhaus at yahoo.com) Date: 6 Apr 2005 14:02:25 -0700 Subject: Python sleep doesn't work right in a loop? In-Reply-To: References: <1112814877.560518.229530@z14g2000cwz.googlegroups.com> <1112816991.860177.68420@l41g2000cwc.googlegroups.com> Message-ID: <1112821345.596432.255100@l41g2000cwc.googlegroups.com> Actually, I've tried ALL of these things, and none of them work. I HAVE run the simple for-print-sleep test code to try to determine if this issue was specific to wx (that's good troubleshooting, folks - you narrow down the problem) and even that didn't work, so I thought I'd start with the simple problem first. Sorry if you were mislead. As for wx, I HAVE used the for-setColour-refresh-update-sleep loop, still no dice. The last thing the I put in the loop works (again, as if all the changes are being queued) but the sleep just 'takes over' the loop and nothing happens until al the sleeps are done. With or without wx. Not good. From news at NOwillmcguganSPAM.com Thu Apr 14 06:36:25 2005 From: news at NOwillmcguganSPAM.com (Will McGugan) Date: Thu, 14 Apr 2005 11:36:25 +0100 Subject: Supercomputer and encryption and compression @ rate of 96% In-Reply-To: <1113470846.970773.4780@g14g2000cwa.googlegroups.com> References: <1113470846.970773.4780@g14g2000cwa.googlegroups.com> Message-ID: <425e47a9$0$26352$db0fefd9@news.zen.co.uk> c3poptuse at yahoo.com wrote: > Supercomputer and encryption and compression @ rate of 96% > > The bit sent would be 0 and the key code would be F1-24,k 1-24, > I 1-24,K 1-24,j24,j1,j12,j1,j6,j1,j3,j1,j2,j1 and would unzip or be new > encryption you could encrypt or compress 100 terabits down to 1 bit of > information. Now if you take this idea from my web site you could make > this allot more complex and unbreakable. Data encryption 360 degrees > rotation document 90 degrees and encrypt on every angel then 45 degrees > change it two binary code do it again and again and fold it over like a > piece of paper then having the one's and zero cancel each other out. In > theory you could send a 100 terabit program to someone's computer and > have it unzip and run and install or make > A computer processor like the new 64 bit AMD have the bit unzip into a > large ram drive and buffer use one half of the 64 bit processor decode > the message and the main 64 bit run the numbers. Another way of doing > this is to have a parallel computers with using one of the processes > run the compressed 1 bit of information give the uncompressed a address > on the ram drive to change and not even go threw the processor and then > with different information on each machine compare and run statistics > on information on a 45 tflops supercomputer and turn that 45 tflops > computer into a 1 bit = 100,000 terabits to infinite as long as you > have the ram for storage! with my calculations 45 tflops wouldn't > matter any more it would be how much data you have on a 32bit operating > system changing that to a 1 bit system it would be 32 * 45tflops would > = 1440 tflops Matter moves so fast that it intergreats and > deintergreats faster then any speed we can see it like water from a > hose at real close speed it moves in -------- lines. > Please implement this as a Python module. I would like to compress my mp3 collection to single bits. Will McGugan -- http://www.willmcgugan.com "".join( [ {'*':'@','^':'.'}.get(c,None) or chr(97+(ord(c)-84)%26) for c in "jvyy*jvyyzpthtna^pbz" ] ) From Serge.Orlov at gmail.com Sat Apr 2 02:52:15 2005 From: Serge.Orlov at gmail.com (Serge Orlov) Date: Sat, 2 Apr 2005 11:52:15 +0400 Subject: Installing Python on a Windows 2000 Server References: Message-ID: Mike Moum wrote: > Hi, > > I'm a civil engineer who also doubles as chief programmer for > technical applications at my company. Most of our software is written > in Visual Basic because our VP in charge of I.T. likes to have > "consistency", and at the moment we're a Microsoft shop. He has > assigned me the task of developing an new application, the exact > nature of which is not important for my question. I told him that, in > my opinion, that Visual Basic was not the best choice for developing > this application, and that I wanted to use Python. After a bit of > discussion of the pros and cons, he said to go ahead. I managed to > keep my jaw from hitting the floor. :>) > We have a central server array running Windows Server 2000 (I think > that's the right name; networking is not my specialty, but it's > definately Windows). Some of our workstations run Windows 2000; others > run Windows XP Pro. I would like to install Python on the server, and > run the application that I'll be developing from the workstations, > without having to install any Python components on the workstations > themselves. In other words, the Python executable, and the various > libraries, dll's, and what have you, as well as the application that > I'm developing, should all reside on the server. The only thing on the > workstations would be a shortcut to myapplication.py. > > Does anyone know whether it is possible to do this? I've done some > Google searching, with no conclusive results, and poked about on > python.org, but haven't really been able to find anything. Normally > I'd be happy to just try it out and see what happens, but we're > breaking new ground here (this is an amazingly big step for our > hide-bound IS department!), so I'd like everything to go as smoothly > as possible. Try Movable Python http://www.voidspace.org.uk/python/movpy/ When you will be creating a shortcut to you application it shouldn't point to yourapplication.py directly but rather at \\yourserver\movpy\movpyw.exe \\yourserver\yourapp\yourapplication.py Serge. From mylastnameruntogether at mycompanyname.com Mon Apr 11 13:29:58 2005 From: mylastnameruntogether at mycompanyname.com (Brandon J. Van Every) Date: Mon, 11 Apr 2005 17:29:58 GMT Subject: web authoring tools References: Message-ID: "Fredrik Lundh" wrote in news:mailman.1671.1113204815.1799.python-list at python.org: > Brandon J. Van Every wrote: > >> Ideally, I would like an open source website + html design tool >> implemented in Python > > didn't you just say that ideally, you wanted a tool written in lisp or > scheme? I honestly got a little tired of the tone of the answers I was getting from that crowd, about what an idiot I am. My query there is still ongoing and perhaps genuinely useful answers will arise, but in the interest of time I thought I'd initiate Plan B. The Python universe has a much larger cadre of web designers than the Lisp / Scheme universe, so I figured the answers here would be of a higher quality. I don't think Python is appropriate to all programming tasks, but it's definitely appropriate to web development and I wouldn't mind using / contributing to open source web development tools written in it. > did you try the one frank wrote for you? > > http://groups-beta.google.com/group/comp.lang.lisp/msg/6df9eb74bfd1 > 6310 No, because although it's amusing, it doesn't accomplish anything I wish to accomplish. Currently my website does exactly what I intend it to do. I want to see how long it is before I actually do something about it, and when people say "Your website is down" it actually amuses me. Plus reminds me that perhaps I should do something. > (for python tools, start here: http://www.python.org/topics/web/ ) Thanks! -- Cheers, www.indiegamedesign.com Brandon Van Every Seattle, WA "The pioneer is the one with the arrows in his back." - anonymous entrepreneur From jobs at google.com Fri Apr 1 03:09:03 2005 From: jobs at google.com (Google Jobs Autoresponder) Date: Fri, 1 Apr 2005 00:09:03 -0800 Subject: (SPAM: 50) Mail Delivery (failure jobs-bangalore@google.com) (VIRUS REMOVED) Message-ID: <200504010809.j31893dZ010696@cartman.corp.google.com> We want to thank you for your interest in joining the Google team. We received your email inquiry and look forward to the opportunity to review your background and experience. Unfortunately, we are unable to give a personal reply to every applicant. However, please know that we do review all resumes by hand so it takes us just a little bit longer to get back to applicants we feel might be a fit for one of our positions. If you do not hear from one of us, we may not have a position available for you at this time. We thank you for your patience and want to thank you again for your interest in Google. Google Staffing http://www.google.com/jobs.html From martin at -xx-blecket-xx-.org Mon Apr 4 09:46:58 2005 From: martin at -xx-blecket-xx-.org (Martin Magnusson) Date: Mon, 04 Apr 2005 15:46:58 +0200 Subject: Problems compiling PIL under Cygwin Message-ID: <1112622420.b10f3c33f4b325231e47d8cc95e09ded@teranews> Hi group, I'm trying to build PIL under Cygwin (for use with the Skencil vector graphics program), and I couldn't find a better forum for questions than this. I'm using Python 2.3.4, and when I run "python setup.py build_ext -i" I get the following output: running build_ext building '_imaging' extension gcc -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -DHAVE_LIBJPEG -DHAVE_LIBZ -I/usr/include/freetype2 -IlibImaging -I/usr/include -I/usr/local/include -I/usr/include/python2.3 -c libImaging/GifEncode.c -o build/temp.cygwin-1.5.12-i686-2.3/libImaging/GifEncode.o C:\cygwin\bin\python2.3.exe (1352): *** unable to remap C:\cygwin\bin\tk84.dll to same address as parent(0x760000) != 0xBB0000 4 [main] python 1984 sync_with_child: child 1352(0x238) died before initialization with status code 0x1 282 [main] python 1984 sync_with_child: *** child state child loading dlls error: Resource temporarily unavailable Does anybody know what could be done to solve this? / martin From paul at fxtech.com Thu Apr 28 15:19:02 2005 From: paul at fxtech.com (Paul Miller) Date: Thu, 28 Apr 2005 14:19:02 -0500 Subject: anonymous functions/expressions without lambda? In-Reply-To: References: Message-ID: Michael Hoffman wrote: > Dave Benjamin wrote: > >> I think you meant to write something like this: >> >> def attrsetter(obj, name, value): >> def _return_func(): >> return setattr(obj, name, value) >> return _return_func > > > Sure did. Sorry. You guys have been very helpful! While on the subject, is there an equivalent for "methodcaller"? ie. if I want to bind a function which calls a specific method of an object with a specific parameter? From steven.bethard at gmail.com Wed Apr 13 11:36:09 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 13 Apr 2005 09:36:09 -0600 Subject: Codig style: " or """ In-Reply-To: References: Message-ID: <6v-dnVnCJ7X7ocDfRVn-oA@comcast.com> Sara Khalatbari wrote: > Hi! > > Suppose you're writing a module & writing the > definition of each function in that module in " or > """. > for example: > a) "This function does this & that" > or: > b) """This function does blah blah blah""" > > What are the differences between " and """ ? > I'm using gedit & I wanna know a bit about coding > style. > > To be very honest: I have a very strict boss who looks > for bugs in my codes & he insists to know exactly > which 'CODING STYLE AUTHORITATIVE SOURCE' I've based > my coding style on when using " or """. > > Can anybody out there give me some hint? > Can anybody tell me where to find a document on python > coding style. PEP 8: http://www.python.org/peps/pep-0008.html and for docstrings, PEP 257: http://www.python.org/peps/pep-0257.html which says: For consistency, always use """triple double quotes""" around docstrings. STeVe From g.brandl at gmx.net Mon Apr 4 11:27:46 2005 From: g.brandl at gmx.net (Georg Brandl) Date: Mon, 04 Apr 2005 17:27:46 +0200 Subject: "specialdict" module In-Reply-To: References: <3bamhhF6j009lU1@individual.net> <3bb433F6fn6t3U1@individual.net> Message-ID: <3bd4mfF6eagcoU1@individual.net> Michael Spencer wrote: > Georg Brandl wrote: > >> >> I think I like Jeff's approach more (defaultvalues are just special >> cases of default factories); there aren't many "hoops" required. >> Apart from that, the names just get longer ;) > > Yes Jeff's approach does simplify the implementation and more-or-less eliminates > my complexity objection > > But why do you write: > > def __getitem__(self, key): > try: > return super(defaultdict, self).__getitem__(key) > except KeyError, err: > try: > return self.setdefault(key, > self._default[0](*self._default[1], > **self._default[2])) > except KeyError: > raise err > > rather than: > > def __getitem__(self, key): > return self.setdefault(key, > self._default[0](*self._default[1], > **self._default[2])) > > (which could catch AttributeError in the case of _default not set) > I'm sure there's a reason, but I can't see it. In your version, the default factory is called every time a value is retrieved, which might be a performance problem. >>>Alternatively, you could provide factory functions to construct the defaultdict. >>> Someone (Michele?) recently posted an implementation of this >> >> >> Yes, I think this could be reasonable. > > > ...though this would more naturally complement a fixed-default dictionary IMO > Your design permits - even encourages (by providing convenient setters) the > default to change over the lifetime of the dictionary. I'm not sure whether > that's good or bad, but it's a feature worth discussing. It's certainly more in the spirit of Python -- we're consenting adults, and so we are allowed to change the default. mfg Georg From mage at mage.hu Mon Apr 18 14:29:39 2005 From: mage at mage.hu (Mage) Date: Mon, 18 Apr 2005 20:29:39 +0200 Subject: packages Message-ID: <4263FC93.5090104@mage.hu> Hello, I read about modules and packages in the tutorial. I think I understand how to use packages and modules, even I know how to create a module (as far I understand it's a simple .py) file , but I don't know how can I create a package and when should I do it. Where should I look for more information? Mage From finite.automaton at gmail.com Fri Apr 29 15:18:57 2005 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: 29 Apr 2005 12:18:57 -0700 Subject: module exports a property instead of a class -- Evil? References: <1114797779.371054.189950@g14g2000cwa.googlegroups.com> Message-ID: <1114802337.216856.219870@l41g2000cwc.googlegroups.com> The property factory is nice, but have you considered subclassing property? class Mode(property): def __init__(self, *vals): if [v for v in vals if not isinstance(v,str)]: raise ValueError, 'Mode values must be strings' else: self.values = list(vals) property.__init__(self, self.get, self.set) def get(self, instance): ... def set(self, instance, value): ... From ksenia.marasanova at gmail.com Mon Apr 25 13:04:52 2005 From: ksenia.marasanova at gmail.com (Ksenia Marasanova) Date: Mon, 25 Apr 2005 19:04:52 +0200 Subject: web based file manager in python Message-ID: <130df19305042510046ea432ad@mail.gmail.com> Hi, I didn't suceed in finding any kind of standard web based file manager, written in Python. There are quite a lot for PHP (the nicest I found is phpXplorer: http://www.phpxplorer.org) , but I'd rather use Python. I don't mind installing one of the millions webframeworks for this (well, except for Zope) :) I know, it's not hard to write your own... I am just trying not re-inventing the wheel this time :) Any hints? Thanks! -- Ksenia From philippe at philippecmartin.com Sun Apr 24 12:48:53 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Sun, 24 Apr 2005 16:48:53 GMT Subject: [OT] Graphic editor within an MFC app. I have a wxPython prototype, that... References: Message-ID: Does that mean you are using C++/C# and not Python ? I also guess you do not wish MFC and wxWindows to coexist in the same .exe as the reasons for conflict are many (GDI port, main event loop .....) Then do you simply wish to "map" your wxindows calls to equivalent MFC calls with some kind of stub/glue? Regards, Philippe F. GEIGER wrote: > I have built a wxPython prototype of an app, that lets me place rectangles > o a wxPanel, move them and change their size. How the rects are added > and placed has to follow certain rules. > > The final goal is to merge this "graphical editor" into a MFC app. > Converting a standalone wxPython app into a wxWidget app ist not that > complicated. > > But how about merging it into a MFC app? Has anybody achieved that > already? > > All the functionality lies in my wxPanel-subclass "EditorWidget" and in > the few widgets I can place on it. So it boils down to place that > "EditorWidget" an a MFC-Panel. But what about the mainloops? > > If that's not possibel at all, I'd consider getting an ActiveX that offers > to me what I need. It does not need to be a full blown CAD ActiveX but > should be customizeable. Does anyone know a source for such things? > > Many thanks in advance and kind regards > Franz GEIGER From michele.simionato at gmail.com Tue Apr 26 04:17:12 2005 From: michele.simionato at gmail.com (Michele Simionato) Date: 26 Apr 2005 01:17:12 -0700 Subject: (PHP or Python) Developing something like www.tribe.net In-Reply-To: <1113835147.364885.304290@l41g2000cwc.googlegroups.com> References: <1113835147.364885.304290@l41g2000cwc.googlegroups.com> Message-ID: <1114503432.227799.52670@o13g2000cwo.googlegroups.com> Mir Nazim: > IMHO Zope3/Quixote seem to be the obvious choice here. > Though > functionality is not available on them but i think time > spent now will > be gained by gains in better design and maintainable code base. Well, you are comparing two frameworks that are just completely different. I suggest you to start evaluating Quixote first, since it is much simpler to grasp, and you can decide in a couple of days if it is the platform you want to program in or not. Zope 3 is a somewhat risky platform (i.e. you cannot leverage on the existing Zope 2 applications and not many developers are familiar with Zope 3 yet). Quixote too has a small number of developers, but at least it is easy and you don't need much help to work with it. Michele Simionato Michele Simionato From fredrik at pythonware.com Mon Apr 11 03:23:22 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 11 Apr 2005 09:23:22 +0200 Subject: web authoring tools References: Message-ID: Brandon J. Van Every wrote: > Ideally, I would like an open source website + html design tool implemented > in Python didn't you just say that ideally, you wanted a tool written in lisp or scheme? did you try the one frank wrote for you? http://groups-beta.google.com/group/comp.lang.lisp/msg/6df9eb74bfd16310 (for python tools, start here: http://www.python.org/topics/web/ ) From caneff at gmail.com Mon Apr 11 14:42:10 2005 From: caneff at gmail.com (ChinStrap) Date: 11 Apr 2005 11:42:10 -0700 Subject: Creating a new instance of a class by what is sent in? Message-ID: <1113244930.403334.66150@z14g2000cwz.googlegroups.com> I am sorry if this is obvious, but I am not seeing it. How would I go about creating a new type that is of the same type as a class sent into the function? new = foo.__init__() refers to the current foo, not a new fresh instance of my class. The only way I can think of is to make a large if-elif chain of isinstances, but that loses the generality I am after. Thank you for your help. From martijn at gamecreators.nl Thu Apr 14 10:53:57 2005 From: martijn at gamecreators.nl (martijn at gamecreators.nl) Date: 14 Apr 2005 07:53:57 -0700 Subject: Supercomputer and encryption and compression @ rate of 96% In-Reply-To: <1113470846.970773.4780@g14g2000cwa.googlegroups.com> References: <1113470846.970773.4780@g14g2000cwa.googlegroups.com> Message-ID: <1113490437.037734.158740@g14g2000cwa.googlegroups.com> And how do you get the data back ? 1+0=0 == 0+0=0 0+1=1 == 1+1=1 let's say you have the end key : 0 then you want to decompress it , but in what ? 0 0 or 1 0 ;) From modelnine at ceosg.de Sat Apr 9 05:48:27 2005 From: modelnine at ceosg.de (Heiko Wundram) Date: Sat, 9 Apr 2005 11:48:27 +0200 Subject: How to check whether a list have specific value exist or not? In-Reply-To: References: <20050409093226.96954.qmail@web8402.mail.in.yahoo.com> Message-ID: <200504091148.30320.modelnine@ceosg.de> Am Samstag, 9. April 2005 11:37 schrieb Michael Spencer: > praba kar wrote: > > I want to check a list have specific > > value or not. So If any one know regarding this > > mail me > A minute of two experimenting, would then lead you to: > >>> l = [1,2,3,4,5] > >>> l.index(3) > > 2 Or, if its that you just want to know whether a value is somewhere in an iterable: >>> l = [1,2,3,4,5] >>> 4 in l True See how there is special syntax to call the __contains__ method of the iterable automatically. -- --- Heiko. listening to: Pearl Jam - Rearviewmirror see you at: http://www.stud.mh-hannover.de/~hwundram/wordpress/ -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From mefjr75 at hotmail.com Sun Apr 17 06:03:46 2005 From: mefjr75 at hotmail.com (M.E.Farmer) Date: 17 Apr 2005 03:03:46 -0700 Subject: whitespace , comment stripper, and EOL converter In-Reply-To: <1113730429.336626.81360@g14g2000cwa.googlegroups.com> References: <2ab23d7a.0504120857.14ef094a@posting.google.com> <2ab23d7a.0504130738.622a3605@posting.google.com> <1113410094.102181.315080@l41g2000cwc.googlegroups.com> <1113680973.635576.310510@g14g2000cwa.googlegroups.com> <1113713669.255207.39580@f14g2000cwb.googlegroups.com> <1113726606.945042.71820@z14g2000cwz.googlegroups.com> <1113730429.336626.81360@g14g2000cwa.googlegroups.com> Message-ID: <1113732226.165477.295890@o13g2000cwo.googlegroups.com> Google has now 'fixed' there whitespace issue and now has an auto-quote issue argggh! The script is located at: http://bellsouthpwp.net/m/e/mefjr75/python/stripper.py M.E.Farmer From akineko at gmail.com Fri Apr 8 00:02:48 2005 From: akineko at gmail.com (akineko at gmail.com) Date: 7 Apr 2005 21:02:48 -0700 Subject: SWIG for Python - returning 64 bit value Message-ID: <1112932968.041275.231310@f14g2000cwb.googlegroups.com> Hello everyone, I'm very new to SWIG and I'm trying to use SWIG to interface my Python program to routines written in C. Only catch is it has to pass 40 bit data both ways. I found several postings in the Internet newsgroup related to such. My swig interface file is: %module ipc_msg %{ %} %typemap(in) unsigned long long cmd40b { $1 = (unsigned long long) PyLong_AsUnsignedLongLong($input); } %typemap(out) unsigned long long { $result = PyLong_FromUnsignedLongLong((unsigned long long) $1); } int open_ipc(void); void close_ipc(void); int update(int, unsigned long long cmd40b); unsigned long long capture(int); // Now I confirmed a Python Long value is correctly sent to a C routine. But I found the returned Python Long value from a C routine was truncated to a 32 bit value (upper 32 bit). After looking at the generated wrapper file, I found the reason. > result = (unsigned long long)capture(arg1); There is no prototype of the function capture in the generated wrapper code. Thus, the function was assumed to return an int (32 bit). I added a prototype of the function manually. > unsigned long long capture(int arg1); Then Python received a correct 64 bit value from a C routine. My question is: (1) Am I missing something in my interface file? The function prototype, unsigned long long capture(int); is already there. What else I need? (2) Is this a bug in SWIG? (3) Is there any work around rather than using a code insertion block ? I tried to find an answer to this by reading SWIG manual and searching the Internet, but so far not successful. // My platform is Solaris 9 (SUN Sparc) and I'm using Pthon 2.3 and Swig 1.3.24. Any comments will be greatly appreciated. Best regards, Aki Niimura From littlejohn.75 at news.free.fr Thu Apr 7 15:57:40 2005 From: littlejohn.75 at news.free.fr (F. Petitjean) Date: 07 Apr 2005 19:57:40 GMT Subject: How to name Exceptions that aren't Errors References: <3blfl8F6gt80jU1@individual.net> Message-ID: <425590b4$0$18707$636a15ce@news.free.fr> Le 7 Apr 2005 19:23:21 GMT, Leo Breebaart a ?crit : > I've recently become rather fond of using Exceptions in Python to > signal special conditions that aren't errors, but which I feel > are better communicated up the call stack via the exception > mechanism than via e.g. return values. > > For instance, I'm thinking of methods such as: > > > def run(self): > """ Feed the input file to the simulator. """ > > for linenr, line in enumerate(self.infile): > try: > current_values = self.parse_line(linenr, line) >==> except CommentLineException: > continue > results = self.do_one_simulation_step(current_values) > self.process_simulation_results(results) > > > which I use in order to discard comments from a file I'm parsing > line-by-line. > [snip] > 'Exception' prefix seems a bit redundant and pointless too. I > suppose I could just call the exception "CommentLine" and leave > it at that, but I don't know, maybe there's something better I'm > overlooking. You are overlooking the fact the flow of information is pretty much linear. The comments lines can be safely ignored (filtered out) on the fly. enumerate filter-out infile(producer) --------> linenr, line -----------> linenr, line ---> > > Any suggestions? From your parse_line() method extract the logic to detect a comment line put this code in a predicate function and use itertools.ifilter(pred, iterable). Much more explicit. parse_line() is simplified. The client code run() does not have to deal with bogus inputs anymore if you feed it with the filtered out stream. > From rkern at ucsd.edu Mon Apr 25 14:59:02 2005 From: rkern at ucsd.edu (Robert Kern) Date: Mon, 25 Apr 2005 11:59:02 -0700 Subject: Python documentation moronicities (continued) In-Reply-To: <1114454884.549187.122440@o13g2000cwo.googlegroups.com> References: <1113301533.054410.203710@z14g2000cwz.googlegroups.com> <1114454884.549187.122440@o13g2000cwo.googlegroups.com> Message-ID: Xah Lee wrote: > I have produced my doc. > ( http://xahlee.org/perl-python/python_re-write/lib/module-re.html ) > > isn't there a hundred dollars due to me? No. [Steve Holden] >>The condition for winning the prize is that at least five regular >>posters to c.l.py have to mail me and saythey think your version is >>better. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From rune.strand at gmail.com Tue Apr 12 18:48:59 2005 From: rune.strand at gmail.com (runes) Date: 12 Apr 2005 15:48:59 -0700 Subject: Python documentation moronicities (continued) In-Reply-To: References: <1113301533.054410.203710@z14g2000cwz.googlegroups.com> <1113340181.174797.132250@f14g2000cwb.googlegroups.com> Message-ID: <1113346139.139720.17510@o13g2000cwo.googlegroups.com> Thank you for being so friendly! I found the Howto through Google. Somehow I didn't see that link in the documentation. And please do not make any assumptions about my reading of manuals. From finite.automaton at gmail.com Wed Apr 20 14:52:18 2005 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: 20 Apr 2005 11:52:18 -0700 Subject: Faster os.walk() References: <1114011606.600970.43300@l41g2000cwc.googlegroups.com> Message-ID: <1114023138.082762.277630@g14g2000cwa.googlegroups.com> If you're trying to track changes to files on (e.g. by comparing current size with previously recorded size), fam might obviate a lot of filesystem traversal. http://python-fam.sourceforge.net/ From jbo at cannedham.ee.ed.ac.uk Wed Apr 13 09:28:51 2005 From: jbo at cannedham.ee.ed.ac.uk (Jim) Date: Wed, 13 Apr 2005 14:28:51 +0100 Subject: preallocate list In-Reply-To: References: Message-ID: Thanks for the suggestions. I guess I must ensure that this is my bottle neck. def readFactorsIntoList(self,filename,numberLoads): factors = [] f = open(self.basedir + filename,'r') line = f.readline() tokens = line.split() columns = len(tokens) if int(columns) == number: for line in f: factor = [] tokens = line.split() for i in tokens: factor.append(float(i)) factors.append(loadFactor) else: for line in f: tokens = line.split() factors.append([float(tokens[0])] * number) return factors OK. I've just tried with 4 lines and the code works. With 11000 lines it uses all CPU for at least 30 secs. There must be a better way. Jim From steven.bethard at gmail.com Mon Apr 4 11:23:29 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 04 Apr 2005 09:23:29 -0600 Subject: Silly question re: 'for i in sys.stdin'? In-Reply-To: References: Message-ID: Jeff Epler wrote: > On Sun, Apr 03, 2005 at 09:49:42PM -0600, Steven Bethard wrote: > >>Slick. Thanks! > > does isatty() actually work on windows? I'm a tiny bit surprised! Hmm... I was just talking about using iter(f.readline, ''), but it does appear that isatty returns True for sys.stdin in the interactive prompt: ActivePython 2.4.1 Build 245 (ActiveState Corp.) based on Python 2.4.1 (#65, Mar 30 2005, 09:33:37) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. py> os.isatty(sys.stdin.fileno()) True and at least some other things return False: py> os.isatty(file('temp.txt').fileno()) False STeVe From bokr at oz.net Wed Apr 20 04:22:54 2005 From: bokr at oz.net (Bengt Richter) Date: Wed, 20 Apr 2005 08:22:54 GMT Subject: Enumerating formatting strings References: <3cm9r2F6nif67U1@individual.net> Message-ID: <42660fc2.42093557@news.oz.net> On Wed, 20 Apr 2005 09:14:40 +0200, Peter Otten <__peter__ at web.de> wrote: >Greg Ewing wrote: > >> Steve Holden wrote: >> >>> I've been wondering whether it's possible to perform a similar analysis >>> on non-mapping-type format strings, so as to know how long a tuple to >>> provide, >> >> I just tried an experiment, and it doesn't seem to be possible. >> >> The problem seems to be that it expects the arguments to be >> in the form of a tuple, and if you give it something else, >> it wraps it up in a 1-element tuple and uses that instead. >> >> This seems to happen even with a custom subclass of tuple, >> so it must be doing an exact type check. > >No, it doesn't do an exact type check, but always calls the tuple method: > >>>> class Tuple(tuple): >... def __getitem__(self, index): >... return 42 >... >>>> "%r %r" % Tuple("ab") # would raise an exception if wrapped >"'a' 'b'" > >> So it looks like you'll have to parse the format string. > >Indeed. > Parse might be a big word for >> def tupreq(fmt): return sum(map(lambda s:list(s).count('%'), fmt.split('%%'))) .. >> tupreq('%s this %(x)s not %% but %s') (if it works in general ;-) Or maybe clearer and faster: >>> def tupreq(fmt): return sum(1 for c in fmt.replace('%%','') if c=='%') ... >>> tupreq('%s this %(x)s not %% but %s') 3 Regards, Bengt Richter From dave at pythonapocrypha.com Tue Apr 12 08:53:04 2005 From: dave at pythonapocrypha.com (Dave Brueck) Date: Tue, 12 Apr 2005 06:53:04 -0600 Subject: Can't Stop Process On Windows In-Reply-To: References: Message-ID: <425BC4B0.30000@pythonapocrypha.com> Dan wrote: > I have a python script running under Windows XP that I need to > terminate from the keyboard. A control-c works fine under Linux, but > not under Windows. I'm pretty sure that the culprit is 'select' that > I'm using to multiplex socket i/o, which seems to be blocking the > keyboard interrupt. Is there some way around this? Are you calling select with a long timeout? An alternative would be to call select with a much shorter timeout, but call it multiple times from a loop. From grante at visi.com Wed Apr 27 10:24:15 2005 From: grante at visi.com (Grant Edwards) Date: Wed, 27 Apr 2005 14:24:15 -0000 Subject: Can .py be complied? References: <426ec8f7_2@rain.i-cable.com> <426f562f$1_3@rain.i-cable.com> Message-ID: <116v84ftiq01ucb@corp.supernews.com> On 2005-04-27, monkey wrote: > Yes, I want more options. Since the python doc mentioned > py2exe only, and it is difficult to understand how it > work.(may be you guys know C and make file, but I am still > foolish here...) py2exe has nothing to do with C or make files. You create a setup.py file containing a couple lines of python. You run that python program, and you end up with an .exe file and some associated .dll files. I typically use inno-setup to create an installer.exe that creates a desktop icon and start-menu entry, but that's optional. > Is that means a .py convert to .pyc or .pyo, without the need > of "make file" as using py2exe? Huh? You don't need a make file for py2exe. -- Grant Edwards grante Yow! I'd like TRAINED at SEALS and a CONVERTIBLE on visi.com my doorstep by NOON!! From kent37 at tds.net Thu Apr 21 10:50:08 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 21 Apr 2005 10:50:08 -0400 Subject: Private class? In-Reply-To: <1114089182.676456.291810@o13g2000cwo.googlegroups.com> References: <1114089182.676456.291810@o13g2000cwo.googlegroups.com> Message-ID: <4267b959$1_3@newspeer2.tds.net> codecraig wrote: > class EventListener: > def eventOccurred(self, eventType): pass > The EventListener class is not needed in Python; you can include it for its documentation value if you like but Python does not require interfaces the way Java does. > class EventBus: > EVENT_GROW_LEAVES = 0 > > __listeners = {} > > def register(listener, eventType): > if __listeners.has_key(eventType): > curListeners = __listeners.get(eventType) > curListeners.append(listener) > else: > __listeners[eventType] = [listener] > > def fire(eventType): > if __listeners.has_key(eventType): > x = __listeners.get(eventType) > for l in x: > l.eventOccurred(eventType) > > ...so that is what I am thinking. However, i guess my issue is how to > make EventBus a singleton or prevent it from being instaniated and > making it's methods statically accessible. One way to do this is to make an EventBus module and make __listeners, register() and fire() be module attributes. Your client code would look like import EventBus ... EventBus.register(...) EventBus.fire(...) Kent From northstar.eight at verizon.net Sun Apr 10 08:41:06 2005 From: northstar.eight at verizon.net (Dhruva Hein) Date: Sun, 10 Apr 2005 08:41:06 -0400 Subject: Help understanding code Message-ID: <42591EE2.9040203@verizon.net> Hi. I am trying to understand a section of code written for Plone and I am having problems understanding the Python syntax in a few of the following lines. I'd be grateful if someone could help me understand what's happening in the lines I've marked. I can't see how the dictionary is built or how the lists ['bytype'][cytype] make sense in python. Thanks in advance. class Stats: def getContentTypes(self): """ Returns the number of documents by type """ pc = getToolByName(self, "portal_catalog") # call the catalog and loop through the records results = pc() <=== what is the difference between pc and pc()? numbers = {"total":len(results),"bytype":{},"bystate":{}} <=== This is hard to understand for result in results: # set the number for the type ctype = str(result.Type) num = numbers["bytype"].get(ctype, 0) <==== where does .get come from? and what is the string 'bytype' doing? num += 1 numbers["bytype"][ctype] = num <====== is this some kind of an array? # set the number for the state state = str(result.review_state) num = numbers["bystate"].get(state, 0) num += 1 numbers["bystate"][state] = num return numbers From sabbey at u.washington.edu Fri Apr 15 19:45:55 2005 From: sabbey at u.washington.edu (Brian Sabbey) Date: Fri, 15 Apr 2005 16:45:55 -0700 Subject: pre-PEP: Suite-Based Keywords Message-ID: Here is a pre-PEP for what I call "suite-based keyword arguments". The mechanism described here is intended to act as a complement to thunks. Please let me know what you think. Suite-Based Keyword Arguments ----------------------------- Passing complicated arguments to functions is currently awkward in Python. For example, the typical way to define a class property winds up polluting the class's namespace with the property's get/set methods. By allowing keyword arguments to be defined in a suite following a function call, complicated arguments can be passed in a cleaner, easier way. Examples ======== Using suite-based keyword arguments, the code f(x = 1) is equivalent to f(): x = 1 In general, a suite following a function call creates a new scope. The bindings created in this scope get passed to the function as keyword arguments. Suite-based keyword arguments can be mixed with regular arguments: f(1, 2, y = 4): x = 1 Motivation ========== One motivation for suite-based keywords is to allow cleaner definitions of properties. Currently, properties are typically define as in this example: class C(object): def getx(self): return self.__x def setx(self, value): self.__x = value def delx(self): del self.__x x = property(getx, setx, delx, "I'm the 'x' property.") The 'getx', 'setx', and 'delx' methods get defined in the namespace of the class even though one wants only to pass them to 'property'. Ideally, one would want these methods to be defined in their own namespace. Also, it would be helpful when reading the code if the layout of the code gave visual indication that their only purpose is to be used in a property. Using suite-based keyword arguments, and without any changes to the 'property' type, this code can be written as: class C(object): x = property(): doc = "I'm the 'x' property." def fget(self): return self.__x def fset(self, value): self.__x = value def fdel(self): del self.__x Here, 'fget', 'fset' and 'fdel' do not wind up as methods of the class, and it is visually clear that they are methods only for the 'x' property. Also, this code is less bug-prone since the name of each method need appear only once. Passing callbacks in other situations is made similarly easier and cleaner: setHandlers(): def success(): print 'success' def failure(): print 'an error has occured' def apocalypse(): print 'a serious error has occured' a = [1,3,2] a.sort(): def cmpfunc(x,y): return cmp(x,y) Situations that do not require callbacks can also be better organized using suite-based keywords. For example, here is code as it would currently be written in Python: if a: x = 1 else: x = 2 f(x=x) When reading this code, one reaches the 'if' statment without knowing what its purpose is-- layout of the code does not indicate that the 'if' statement is calculating an argument to 'f'. Also, it requires a binding that serves no purpose other than to hold an argument to 'f', yet this binding persists for the rest of the surrounding function. Here is the same code using suite-based keyword arguments f(): if a: x = 1 else: x = 2 When reading this code, it is easy to skip over everything that is involved in calling 'f', if one so desires. Since the suite has its own namespace, one does not have to worry that the suite creates some bindings that will be important later in the function. From codecraig at gmail.com Wed Apr 20 17:05:33 2005 From: codecraig at gmail.com (codecraig) Date: 20 Apr 2005 14:05:33 -0700 Subject: Define Constants Message-ID: <1114028999.275836.37290@z14g2000cwz.googlegroups.com> Hi, I have a question about how to define constants. My directory structure looks like... C:\ --> abc.py --> utils --> __init__.py --> CustomThing.py Ok, CustomThing looks like... TOP = 0 LEFT = 1 class CustomThing: def __init__(self): self.foo = "foo" so, from abc.py I have from utils.CustomThing import CustomThing print CustomThing.TOP but i get an error: AttributeError: class 'CustomThing' has no attribute 'TOP' How can I access those?? Thanks. From greg at cosc.canterbury.ac.nz Thu Apr 21 21:29:35 2005 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Fri, 22 Apr 2005 13:29:35 +1200 Subject: Why Python does *SLICING* the way it does?? In-Reply-To: References: <1113976729.450677.261130@o13g2000cwo.googlegroups.com> <87r7h5lk5a.fsf@wilson.rwth-aachen.de> Message-ID: <3cr2caF6locm6U1@individual.net> Antoon Pardon wrote: > > This is nonsens. table[i] = j, just associates value j with key i. > That is the same independend from whether the keys can start from > 0 or some other value. Also, everyone, please keep in mind that you always have the option of using a *dictionary*, in which case your indices can start wherever you want. You can't slice them, true, but you can't have everything. :-) -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From max2 at fisso.casa Sat Apr 2 10:43:07 2005 From: max2 at fisso.casa (max(01)*) Date: Sat, 02 Apr 2005 15:43:07 GMT Subject: redundant importr In-Reply-To: <1MudnZ0j7M-bIdDfRVn-sA@powergate.ca> References: <3avnh3F6cekgkU1@individual.net> <1MudnZ0j7M-bIdDfRVn-sA@powergate.ca> Message-ID: Peter Hansen wrote: > max(01)* wrote: > >> Peter Hansen wrote: >> >>> Not required except for performance reasons. If the .pyc >>> files don't exist, the .py files are recompiled and the >>> resulting bytecode is simply held in memory and not cached >>> and the next startup will recompile all over again. >> >> >> but the other files *are* compiled, right? > > > Yes, definitely. I did say that. > >> so the initial question remains unanswered: > > > No it doesn't. I thought I was clear, but I can reword > it for you: the files are compiled *in-memory* and the > results are never written to disk. > > > *if* they are compiled, where are they put, if the > >> corresponding *.py files are on a non-writeable directory? > > > They are not put anywhere. Compilation is a process > by which the source is converted to executable bytecodes. > This says nothing about where either the source or the > compiled result resides. The actual compilation works > on a long series of bytes in memory, and the result is > just another long series of bytes. Nothing requires that > either of these things are even stored in a file. ok, maybe it is an implementation-dependent issue after all. i am working on a debian woody platform with the standard python2.3 package. consider this: max2 at 172.17.1.201:~/tmp/import-enigma$ ll total 8 -rw-r--r-- 1 max2 max2 36 2005-04-02 17:44 imported.py -rw-r--r-- 1 max2 max2 33 2005-04-02 17:44 importer.py max2 at 172.17.1.201:~/tmp/import-enigma$ cat importer.py import imported imported.fun_1() max2 at 172.17.1.201:~/tmp/import-enigma$ cat imported.py def fun_1(): print "I am fun_1()" max2 at 172.17.1.201:~/tmp/import-enigma$ python importer.py I am fun_1() max2 at 172.17.1.201:~/tmp/import-enigma$ ll total 12 -rw-r--r-- 1 max2 max2 36 2005-04-02 17:44 imported.py -rw-r--r-- 1 max2 max2 307 2005-04-02 17:45 imported.pyc -rw-r--r-- 1 max2 max2 33 2005-04-02 17:44 importer.py max2 at 172.17.1.201:~/tmp/import-enigma$ see? bye macs From shama.bell at gmail.com Fri Apr 1 12:38:10 2005 From: shama.bell at gmail.com (shama.bell at gmail.com) Date: 1 Apr 2005 09:38:10 -0800 Subject: numeric module Message-ID: <1112377090.192124.303640@o13g2000cwo.googlegroups.com> Hello, What's the problem with this code? I get the following error message: File "test.py", line 26, in test print tbl[wi][bi] IndexError: index must be either an int or a sequence ---code snippet---- from Numeric import * tbl = zeros((32, 16)) def test(): val = testme() wi = crc >> 4 bi = crc & 0xFL print wi print bi print tbl[wi][bi] def testme(): val = 0xFFFFFFL val >>= 23 return val if __name__ == '__main__': test() Thanks, -SB From gdamjan at gmail.com Wed Apr 20 13:07:52 2005 From: gdamjan at gmail.com (Damjan) Date: Wed, 20 Apr 2005 19:07:52 +0200 Subject: using locales References: <1114013918.059442.30770@l41g2000cwc.googlegroups.com> Message-ID: <42668c5c_2@x-privat.org> > Is there some sort of tutorial on locales or the locale module? > > I can't seem to find a list showing all possible locales. I think this depends on the platform > Anyway, I'd love to have a method called get_available_locales to tell > me what I can use on my machine, or something like that. > > Can anyone tell me how I *do* get these names? In linux (glibc) you can see all locales with "locale -a". -- damjan From finite.automaton at gmail.com Tue Apr 26 17:13:23 2005 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: 26 Apr 2005 14:13:23 -0700 Subject: Pythonic way to do static local variables? References: <_xgbe.128633$cg1.54987@bgtnsc04-news.ops.worldnet.att.net> Message-ID: <1114550003.643140.142900@f14g2000cwb.googlegroups.com> A quick, hackish way to keep a static variable is to declare it as a parameter and give it a default value. The parameter list is evaluated when the function is compiled, not when it is called. The underscores are added as per convention to indicate that the variable is special/private. Example- def cumulative_sum(arg, __static__ = []): __static__.append(arg) return reduce(lambda a,b: a + b, __static__) #------------------- >>> cumulative_sum(1) 1 >>> cumulative_sum(1) 2 >>> cumulative_sum(1) 3 From vincent at visualtrans.de Wed Apr 13 02:31:00 2005 From: vincent at visualtrans.de (vincent wehren) Date: Wed, 13 Apr 2005 08:31:00 +0200 Subject: Doubt regarding sorting of a list specific field References: Message-ID: "praba kar" schrieb im Newsbeitrag news:mailman.1817.1113371391.1799.python-list at python.org... | Dear All, | | I have doubt regarding sorting. I have a list | that list have another list (eg) | | list = [[1234,'name1'],[2234,'name2'],[0432,'name3']] -> Be careful, 0432 is octal notation for 282. | | I want to sort only numeric value having array field. | How I need to do for that. You may want use the decorate-sort-undecorate idiom. I othere words, you isolate the index you want to sort by, sort on the indices, than get rid of the indices again. Something like: def sortSeqOfSeqs(seq, idx): tmp = sorted([(elem[idx], elem) for elem in seq]) return [elem[1] for elem in tmp] seq = [[1234,'name1'],[2234,'name2'],[1432,'name3']] print sortSeqOfSeqs(seq, 0) # prints [[1234, 'name1'], [1432, 'name3'], [2234, 'name2']] # Or to sort by the name index print sortSeqOfSeqs(seq, 1) # prints [[1234, 'name1'], [2234, 'name2'], [1432, 'name3']] Is this what you we're looking for? -- Vincent Wehren | | with regards | Prabahar | | | | | | | ________________________________________________________________________ | Yahoo! India Matrimony: Find your life partner online | Go to: http://yahoo.shaadi.com/india-matrimony From nyamatongwe+gravity at gmail.com Tue Apr 12 02:51:21 2005 From: nyamatongwe+gravity at gmail.com (Neil Hodgson) Date: Tue, 12 Apr 2005 06:51:21 GMT Subject: I've broken PythonWin2.4 - Dialogs don't pop up! References: <1112815685.437815.285680@f14g2000cwb.googlegroups.com> <1113262755.407761.92730@f14g2000cwb.googlegroups.com> Message-ID: Michael Murdock: > Rebooting does not help. I uninstalled and removed everything from > c:\python2.4 and then downloaded and installed the latest version. > Right after installing it, everything worked fine. But when I rebooted, > the problem came back. Do you have a copy of win32ui.pyd on the system path? Neil From codecraig at gmail.com Fri Apr 15 11:51:57 2005 From: codecraig at gmail.com (codecraig) Date: 15 Apr 2005 08:51:57 -0700 Subject: py2exe - create one EXE In-Reply-To: References: <1113579012.150708.118990@o13g2000cwo.googlegroups.com> Message-ID: <1113580317.027071.183640@z14g2000cwz.googlegroups.com> must have missed it on py2exe front page....and for google i didnt try that search exactly. Thanks though. I was trying like "one executable py2exe", etc. From bill.mill at gmail.com Wed Apr 20 13:09:17 2005 From: bill.mill at gmail.com (Bill Mill) Date: Wed, 20 Apr 2005 13:09:17 -0400 Subject: Troll? was: Re: goto statement In-Reply-To: References: <20050420092359.81900.qmail@web8409.mail.in.yahoo.com> <87vf6hlkix.fsf@wilson.rwth-aachen.de> <70sc615akd7mfdkmrjls956o1u5rglm74t@4ax.com> Message-ID: <797fe3d40504201009182c45c6@mail.gmail.com> On 4/20/05, Robert Kern wrote: > Maxim Kasimov wrote: > > Andr? Roberge wrote: > > > >> Maxim Kasimov wrote: > >> > >>> > >>> by the way, "goto" statement will be useful for writing more powerful > >>> obfuscators > >>> > >> Let me get that clear: you want a goto to help with debugging. > >> > >> And you want to obfuscate your code even more? > >> > >> !? > >> > >> Perhaps you need to write in Perl, or some other similar language. > >> > >> Writing in Python is for those that seek clarity (not obfuscation) and > >> less bugs. Which is why a goto statement should definitely never be > >> part of Python! > >> > >> Andr? > >> > > > > so insulting to me - you asking i'm a troll, only becose i'm saing that > > goto maybe sometimes usefull. > > No, because you said that it was useful for obfuscating code. > Obfuscating code is generally not a desirable feature of a language > construct. > I believe he meant obfuscating bytecode for a commercial product, to try and avoid decompilation, which is often a desirable function for commercial entities. (Not that I have the technical knowledge to agree or disagree with what he said, I'm just trying to help clear up what's become a fairly bogged-down argument.) Peace Bill Mill bill.mill at gmail.com > -- > Robert Kern > rkern at ucsd.edu > > "In the fields of hell where the grass grows high > Are the graves of dreams allowed to die." > -- Richard Harter > > -- > http://mail.python.org/mailman/listinfo/python-list > From thys at sentechsa.com Tue Apr 12 18:41:16 2005 From: thys at sentechsa.com (Thys Meintjes) Date: Wed, 13 Apr 2005 00:41:16 +0200 Subject: defining extern variables in pyrex Message-ID: <1113345676.10043.39.camel@localhost.localdomain> Hi All, I've inherited a c library and is the process of wrapping it using Pyrex. The library code is a state machine and remembers previous values in order to determine new values on, for example, a decode() call. These "state-full" variables were all implemented using 'extern' in the c code. My wrapper works fine if I have only one instance of my new type myclass. However, when I create more than one instance of myclass it seems that the different instances each share the same extern variables. And of course when one method call on a instance manipulates the internal state machine it invalidates the other instance's state. I guess this makes sense... So, how do I define variables in the pyrex wrapper that is visible as extern c values but are private to a instance ? Take a look at the example, both val2 and val1 are defined as extern in some .h or .c files in the library, val2 is visible but not private to myclass, val1 is private to myclass but when I import myclasslib I get undefined symbol errors like these: ImportError: ./codex/efr/src/libgsmefr.so: undefined symbol: past_gain example: cdef short val2 cdef class myclass: cdef short val1 I reckon that if I can define all the state-full vars in the same scope as val1 and convince Pyrex (and the linker, I guess) that these are the elusive externs I wouldn't need to go through the pain of passing these state-full vars down each method call, Do I have any hope of doing it this way ? regards Thys From ricardo at nospam Tue Apr 12 14:01:08 2005 From: ricardo at nospam (Ricardo) Date: Tue, 12 Apr 2005 19:01:08 +0100 Subject: Embedding threaded Python Message-ID: <17z9xcflpzk5z$.ao7hpt7phqfu$.dlg@40tude.net> If I embed Python in a C app and the Python code is threaded, but the C code isn't, do I need to call PyEval_InitThreads() ? - or do you only need to do that if the C code is threaded ? From ajikoe at gmail.com Thu Apr 21 14:18:24 2005 From: ajikoe at gmail.com (ajikoe at gmail.com) Date: 21 Apr 2005 11:18:24 -0700 Subject: __del__ and reference count problem In-Reply-To: <97O9e.70365$mL3.4834342@phobos.telenet-ops.be> References: <97O9e.70365$mL3.4834342@phobos.telenet-ops.be> Message-ID: <1114107504.036833.109360@z14g2000cwz.googlegroups.com> Your problem can be simplified : class A: pop = 11 def __del__(self): print A.pop if __name__ == '__main__': objA = A() Exception exceptions.AttributeError: "'NoneType' object has no attribute 'pop'" in > ignored I got the same error message, and I don't know why ? it looks like the class variable can't be accessed from __del__? Pujo From jerf at jerf.org Wed Apr 27 17:46:20 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Wed, 27 Apr 2005 17:46:20 -0400 Subject: creating very small types References: Message-ID: On Wed, 27 Apr 2005 22:17:07 +0200, andrea wrote: > I was thinking to code the huffman algorithm and trying to compress > something with it, but I've got a problem. > How can I represent for example a char with only 3 bits?? > I had a look to the compression modules but I can't understand them much... > > Thank you very much > Any good link would be appreciated of course :) I think the answer to this question very much depends on why you want to do this. Easy and fast are pretty opposed in this particular domain in Python (IMHO anyways, it's an easy bit-bashing language but it's slow for that), and you're in one of the rare domains where it matters. The answers strongly vary if you're trying to create something performant, or just for your learning purposes. Or homework purposes... ;-) From neuhauser+python-list#python.org at sigpipe.cz Fri Apr 22 03:30:20 2005 From: neuhauser+python-list#python.org at sigpipe.cz (Roman Neuhauser) Date: Fri, 22 Apr 2005 09:30:20 +0200 Subject: Noobie Question: Using strings and paths in mkdir (os.mkdir("/test/"a)) In-Reply-To: References: Message-ID: <20050422073020.GA74505@isis.sigpipe.cz> # smacpher at gmail.com / 2005-04-22 00:13:05 -0700: > Hello! > > I can't seem to get paths and variables working together: > > import os > a = 'books' > os.chdir( '/test') > os.mkdir("/test/"a) > > the last line does not seem to work. os.mkdir(a) makes the directory > books, but i want this directory as a subdirectory of test. > > I also tried: os.mkdir("/test/",a), and trying to make b = 'test' and > then os.mkdir(a b). > > Does someone have any ideas or a link they can give me, I looked under > strings in the python tutorial and library manual but I guess not in > the right spot. http://docs.python.org/ref/string-catenation.html -- How many Vietnam vets does it take to screw in a light bulb? You don't know, man. You don't KNOW. Cause you weren't THERE. http://bash.org/?255991 From lee at example.com Sun Apr 17 16:48:58 2005 From: lee at example.com (Lee Harr) Date: Sun, 17 Apr 2005 20:48:58 GMT Subject: pysvn install on freebsd References: Message-ID: <_Yz8e.1669$LX3.762@news02.roc.ny> On 2005-04-17, Timothy Smith wrote: > has anyone used or installed this on fbsd > the install for it is totally redundant. i get this error for it > > make -f freebsd.mak clean all test > cd ../Source && make -f pysvn_freebsd_py.mak clean > make: cannot open pysvn_freebsd_py.mak. > *** Error code 2 > > Stop in /usr/home/timothy/pysvn-1.1.2/Extension/Builder. > Have you tried /usr/ports/devel/subversion-python/ ? From swaroopch at gmail.com Fri Apr 1 09:47:03 2005 From: swaroopch at gmail.com (Swaroop C H) Date: Fri, 1 Apr 2005 20:17:03 +0530 Subject: Unzipping Files In-Reply-To: <424D5E3E.3040506@novasyshealth.com> References: <424D5E3E.3040506@novasyshealth.com> Message-ID: <351e887105040106475b845943@mail.gmail.com> On Apr 1, 2005 8:14 PM, Greg Lindstrom wrote: > How do I read the data from a file in a zip archive? http://www.devshed.com/c/a/Python/Python-UnZipped Regards, -- Swaroop C H Blog: http://www.swaroopch.info Book: http://www.byteofpython.info From pinard at iro.umontreal.ca Wed Apr 6 09:59:20 2005 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Wed, 6 Apr 2005 09:59:20 -0400 Subject: Best editor? In-Reply-To: References: <1112725379.514651.66540@l41g2000cwc.googlegroups.com> Message-ID: <20050406135920.GB23620@alcyon.progiciels-bpi.ca> [Mike L.G.] > Emacs may seem awkward at first, but the payoff was amazing for me. Same here. A good editor may tremendously increase your productivity. However, nowadays, good editors abound, to the point that people are not so astonished by them. I've been around for many years, and a good while ago, people were not stumbling on good editors as they do nowadays. At that time, something like Emacs was quite a breakthrough. I guess that Python is extraordinary wonderful, or not that much, depending on your background. Younger people are exposed to many good languages, so they all seem more natural to them. If I compare Python to FORTRAN, COBOL or Assembler, the change is impressive. If I only could have had something like Python when I started, years ago, and considering all the work invested, where would I be today! :-) -- Fran?ois Pinard http://pinard.progiciels-bpi.ca From __peter__ at web.de Wed Apr 6 14:06:16 2005 From: __peter__ at web.de (Peter Otten) Date: Wed, 06 Apr 2005 20:06:16 +0200 Subject: formatting file References: Message-ID: SPJ wrote: > test1????1.1-1???installed > test1????1.1-1???update > test2????2.1-1???installed > test2????2.1-2???update > > I want the file to be formatted in the following way: > > test1????1.1-1???1.1-2 > test2????2.1-1???2.1-2 The following program expects a sorted input file: import itertools from operator import itemgetter def pivot(infile, outfile, getkey=itemgetter(0), getvalue=itemgetter(1), sep="\t"): if not hasattr(infile, "read"): infile = file(infile) if not hasattr(outfile, "write"): outfile = file(outfile, "w") records = (line.split() for line in infile) for key, items in itertools.groupby(records, getkey): out_record = [key] out_record.extend(getvalue(item) for item in items) print >> outfile, sep.join(out_record) if __name__ == "__main__": import sys infile, outfile = sys.argv[1:] if infile == "-": infile = sys.stdin if outfile == "-": outfile = sys.stdout pivot(infile, outfile) From jstroud at mbi.ucla.edu Sat Apr 23 22:30:12 2005 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 23 Apr 2005 19:30:12 -0700 Subject: Variables In-Reply-To: <426B0283.40602@cloudthunder.com> References: <426B0283.40602@cloudthunder.com> Message-ID: <200504231930.12851.jstroud@mbi.ucla.edu> I think, strictly speaking, foo would be a "name" in python. >>> foo Traceback (most recent call last): File "", line 1, in ? NameError: name 'foo' is not defined On Saturday 23 April 2005 07:20 pm, so sayeth Richard Blackwood: > To All: > > Folks, I need your help. I have a friend who claims that if I write: > > foo = 5 > > then foo is NOT a variable, necessarily. If you guys can define for me > what a variable is and what qualifications you have to back you, I can > pass this along to, hopefully, convince him that foo is indeed a variable. > > Thanks all! > > Richard B. -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From __peter__ at web.de Tue Apr 26 18:19:42 2005 From: __peter__ at web.de (Peter Otten) Date: Wed, 27 Apr 2005 00:19:42 +0200 Subject: kdialog and unicode References: <8d7dabda.0504261239.37952804@posting.google.com> Message-ID: dumbkiwi wrote: > I'd be interested to see what your default encoding is, ascii > and why your output was different. If only I knew. > Anyway, from your post, I've done some more digging, and found the > command: > > sys.setappdefaultencoding() That is an alias for sys.setdefaultencoding() created by your IDE (Eric), and therefore may not always be available. Peter From fperez.net at gmail.com Tue Apr 5 03:37:59 2005 From: fperez.net at gmail.com (Fernando Perez) Date: Tue, 05 Apr 2005 01:37:59 -0600 Subject: Gnuplot.py and, _by far_, the weirdest thing I've ever seen on my computer References: <1112649790.752371.98360@g14g2000cwa.googlegroups.com> Message-ID: syd wrote: > I don't even know where to begin. This is just bizarre. I just picked > up the Gnuplot.py module (a light interface to gnuplot commands) and > was messing around with it today. > > I've got a tiny script, but it only works from the command line about > half the time! In the python interpreter, 100%. Ipython, 100%. I'm > not kidding. Nothing strange about it. When run standalone, the python interpreter quits and cleans up after itself, possibly deleting temp files before gnuplot gets a chance to use them. You can put a time.sleep(5) before exiting, or even safer, a full safety check: while 1: if os.path.isfile(your_plot_filename): break time.sleeep(1) Best, f From remi at cherrypy.org Thu Apr 28 07:11:02 2005 From: remi at cherrypy.org (remi at cherrypy.org) Date: 28 Apr 2005 04:11:02 -0700 Subject: (PHP or Python) Developing something like www.tribe.net References: <1113835147.364885.304290@l41g2000cwc.googlegroups.com> <1114503432.227799.52670@o13g2000cwo.googlegroups.com> <1114587592.260950.181990@l41g2000cwc.googlegroups.com> <1114587846.011299.125420@g14g2000cwa.googlegroups.com> <1114663336.926935.97910@f14g2000cwb.googlegroups.com> <1114665613.879362.75100@l41g2000cwc.googlegroups.com> Message-ID: <1114686654.011511.306570@l41g2000cwc.googlegroups.com> > CherryPy and Quixote are for programming in the small May I ask why you say that ? Just because a framework is light and easy doesn't mean it doesn't scale well ... > I have not idea how they scale in the large. Well, I do :-) Among many other sites, CherryPy powers the BackOffice system of a big cinema chain in the UK. The web app gets hammered all day long by hundreds of users whose work is completely dependent on this web app. It has 500 different web forms (everything is data driven) and the code is about 30K lines of python/cherrypy code (if the code wasn't data-driven it would be a *lot* more ...). If it gets accepted, there will be a talk about this system at EuroPython ... Remi. From auch-ich-m at g-kein-spam.com Tue Apr 5 02:42:16 2005 From: auch-ich-m at g-kein-spam.com (=?ISO-8859-1?Q?Andr=E9?= Malo) Date: Tue, 5 Apr 2005 08:42:16 +0200 Subject: re module non-greedy matches broken References: <1153658nrs82j13@corp.supernews.com> Message-ID: * "lothar" wrote: > no - in the non-greedy regex > <1st-pat>*? > > <1st-pat>, and are arbitrarily complex patterns. The "not" is the problem. Regex patterns are expressed positive by definition (meaning, you can say, what you expect, but not what you don't expect). In other words, regexps were invented to define (uh... regular) sets, nothing more (especially you can't define "non-sets"). So the usual way is to define the set you've called '*?' and describe it as regex. Modern regular expression engines (which are no longer regular by the way ;-) allow shortcuts like negative lookahead assertions and the like. I want to make clear, that it isn't, that nobody _wants_ to give an advice how to express your pattern in general. The point is, that there's no real syntax for it. It depends on how your <1st-pat> and look like. Chances are, that's even not expressable in one regex (depends on the complexity and kind of the set they define). Each pattern you write is special to the particular use case. Said that, there are some common patterns on how to write some specific forms of regexes. I also suggest Friedl's book. Look for the C-comment-example, where your problem (more or less) is discussed execessively. Though I really recommend to read the book from start to end. It's more like a story, but a good one ;-) > with character classes and negative character classes you do not need > non-greediness anyway. AFAICS one needs non-greedy regexps very very rarely at all. I'm playing with regular expressions for about ten years now and I've actually used them, say, two or three times -- and only for quick hacks. I've never actually _needed_ them. nd From rdm at rcblue.com Fri Apr 15 13:16:49 2005 From: rdm at rcblue.com (Dick Moores) Date: Fri, 15 Apr 2005 10:16:49 -0700 Subject: Compute pi to base 12 using Python? Message-ID: <6.2.1.2.2.20050415101522.06d3b560@rcblue.com> M.E.Farmer wrote at 23:18 4/14/2005: >Nice collection of unix tools, Cygwin not needed. >http://unxutils.sourceforge.net/ Thank you! But a question. I've download both UnxUtils.zip and UnxUpdates.zip. I'm planning to put the contents of UnxUtils.zip in a directory and then move the contents of UnxUpdates.zip, which has many of the same filenames, to the same directory. Should I just let Windows replace the old files with the updated ones? This seems obvious, but I wanted to make sure. I'm using Win XP Pro. Thanks, Dick Moores From mahs at telcopartners.com Sun Apr 3 16:25:53 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Sun, 03 Apr 2005 13:25:53 -0700 Subject: "specialdict" module In-Reply-To: <3bamhhF6j009lU1@individual.net> References: <3bamhhF6j009lU1@individual.net> Message-ID: Georg Brandl wrote: > Hello, > > in follow-up to the recent "dictionary accumulator" thread, I wrote a > little module with several subclassed dicts. > > Comments (e.g. makes it sense to use super), corrections, etc.? Is this > PEP material? > > Docstrings, Documentation and test cases are to be provided later. > > mfg > Georg > Georg: A few reactions: 1. Given that these are specializations, why not have: class defaultvaluedict(dict): ... class defaultfactorydict(dict): ... rather than having to jump through hoops to make one implementation satisfy both cases 2. I would really prefer to have the default value specified in the constructor I realize that this is tricky due to the kw arguments of dict.__init__, but I would favor either breaking compatibility with that interface, or adopting some workaround to make something like d= defaultvaluedict(__default__ = 0) possible. One worksaround would be to store the default in the dict, not as an attribute of the dict. By default the default value would be associated with the key "__default__", but that keyname could be changed for the (I guess very few) cases where that key conflicted with non-default content of the dict. Then dict.__init__ would simply take __default__ = value as a keyword argument, as it does today, and __getitem__ for a missing key would return dict.__getitem__(self, "__default__") Alternatively, you could provide factory functions to construct the defaultdict. Someone (Michele?) recently posted an implementation of this 3. Can you work in the tally and listappend methods that started this whole thread off? 4. On super, no I don't think it's necessary or particularly desirable. These specializations have a close association with dict. dict.method(self,...) feels more appropriate in this case. Michael From sjmachin at lexicon.net Fri Apr 22 16:57:00 2005 From: sjmachin at lexicon.net (John Machin) Date: Sat, 23 Apr 2005 06:57:00 +1000 Subject: Python licence again References: <1114197761.019100.38890@o13g2000cwo.googlegroups.com> Message-ID: <7loi61dq62m6gjutqoj52lgkaf2j4qm0g0@4ax.com> On 22 Apr 2005 12:22:41 -0700, "fuzzylollipop" wrote: >try spelling license correctly next time Yup, pesky furriners, can't spell 'Merican prop'ly like God intended; they shouldn't be allowed on the net, sheriff should run 'em right out o' the county ... > and heading Would that be like heading a soccer ball? >the google >suggestions that probably looked like "didn't you mean : Python License" You might find, were you to try it, that it makes no such suggestions. From radam2 at tampabay.rr.com Fri Apr 29 12:12:13 2005 From: radam2 at tampabay.rr.com (Ron Adam) Date: Fri, 29 Apr 2005 16:12:13 GMT Subject: Can'r run BLT twice? In-Reply-To: <1114717764.808143.317510@o13g2000cwo.googlegroups.com> References: <1114717764.808143.317510@o13g2000cwo.googlegroups.com> Message-ID: Todd Krein wrote: > I'm running PythonWin on XP. When I run my plotter program the first > time, it works fine. The second time I run it, I get the following > error. If I exit PythonWin, and restart, I can again run it once. Any > ideas? > > Error: 1 > TclError Exception in Tk callback > Function: instance at 0x0127AC60>> (type: ) > Args: () > Traceback (innermost last): > File "C:\Python24\lib\Pmw\Pmw_1_2\lib\PmwBase.py", line 1747, in > __call__ > None > File > "C:\NBU\perforce\hardware\test\home_survey\data\home_007\raw_data\KitchenToDen\AMPLITUDE\PathEval.py", > line 89, in doOpenTrace > self.doPlotTrace() # go plot the thing > File > "C:\NBU\perforce\hardware\test\home_survey\data\home_007\raw_data\KitchenToDen\AMPLITUDE\PathEval.py", > line 117, in doPlotTrace > self.graph = Pmw.Blt.Graph(tkRoot) # make a new > graph area > File "C:\Python24\lib\Pmw\Pmw_1_2\lib\PmwBlt.py", line 260, in > __init__ > None > File "C:\Python24\lib\lib-tk\Tkinter.py", line 1861, in __init__ > self.tk.call( > TclError: invalid command name "::blt::graph" > I had that problem also at one time, but I can't remember just what I did to solve it. :-( It is fixable though. I know that's not much help. I'll look at how I use it in my program and see if that rings any bells. Ron Adam From tjreedy at udel.edu Fri Apr 8 16:54:51 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 8 Apr 2005 16:54:51 -0400 Subject: Can dictionary values access their keys? References: Message-ID: "Matthew Thorley" wrote in message news:d36bpj$s59$1 at vegh.ks.cc.utah.edu... > I must say I am *very* suprised that python does not have a way to look > up what key is pointing to a given object But it does. Of course, there could be zero to many keys in any dictionary pointing to any particular value object >--without scanning the whole list that is. That's one way. Another is a reverse dict (for hashable values turned into keys) with the value being a list of zero to many keys. A third (and fastest of these) is to keep the key with the value. >Is that what list.index() does under-the-hood? I mean is > list.index(y) just the same as > > itemnum = 0 > for item in list: > if y == item: > return itemnum > else: > itemnum = itemnum+1 More or less, yes. If your list is sorted, you can use binary search in the bisect module. Terry J. Reedy From ojokimu at yahoo.co.uk Mon Apr 4 14:54:53 2005 From: ojokimu at yahoo.co.uk (John Ridley) Date: Mon, 4 Apr 2005 19:54:53 +0100 (BST) Subject: help with python-devel!!! Message-ID: <20050404185454.93863.qmail@web26806.mail.ukl.yahoo.com> * Michele Simionato wrote: > Just give (as root) > > # urpmi python-devel The OP mentioned that urpmi couldn't find a package by that name. So it might be worth querying for "libpython" if that fails: [user at home]$ urpmq libpython The following packages contain libpython: libpython2.3 libpython2.3-devel John Ridley Send instant messages to your online friends http://uk.messenger.yahoo.com From michele.simionato at gmail.com Tue Apr 12 12:36:26 2005 From: michele.simionato at gmail.com (Michele Simionato) Date: 12 Apr 2005 09:36:26 -0700 Subject: IPython - problem with using US international keyboard input scheme on W2K In-Reply-To: <3bv5mgF6jbil9U1@individual.net> References: <3bv5mgF6jbil9U1@individual.net> Message-ID: <1113323786.737140.184800@o13g2000cwo.googlegroups.com> Me too :-( I have already submitted my issues with the Italian keyboard on WinXP with no great success. It works on Linux, but this is not of a big help since my plan was to use ipython -p pysh on Windows as a replacement of the shell :-( Michele Simionato From ville at spammers.com Mon Apr 25 16:33:48 2005 From: ville at spammers.com (Ville Vainio) Date: 25 Apr 2005 23:33:48 +0300 Subject: What's do list comprehensions do that generator expressions don't? References: <86ll77pgqz.fsf@guru.mired.org> Message-ID: >>>>> "Jeremy" == Jeremy Bowers writes: Jeremy> On Sun, 24 Apr 2005 22:59:12 -0700, Robert Kern wrote: >> Never. If you really need a list >> >> list(x*x for x in xrange(10)) >> >> Sadly, we can't remove list comprehensions until 3.0. Jeremy> Why "remove" them? Instead, we have these things called Jeremy> "comprehensions" (which, now that I say that, seems a Jeremy> rather odd name), and you can control whether they result Jeremy> in a list or a generator with () or []. Still, list comprehensions should be implemented in terms of genexps to get rid of the LC variable that is visible outside the scope of the LC. Jeremy> should be relatively simple), it's not worth breaking that Jeremy> code. Well, the code that relies on the dangling variable deserves to break. -- Ville Vainio http://tinyurl.com/2prnb From andrea.gavana at agip.it Mon Apr 11 04:59:05 2005 From: andrea.gavana at agip.it (andrea.gavana at agip.it) Date: Mon, 11 Apr 2005 10:59:05 +0200 Subject: Avoiding DOS Window... Message-ID: Hello NG, I don't know if this is the right place to post this question, but noting that it is os-related probably someone will have some nice idea. I have built an application using Python+wxPython, and I have compiled it into an exe file using py2exe. In my app, I use a call: self.process = os.spawnl(os.P_NOWAIT, MyCommand) where MyCommand is a call to an external exe file. When I run my application (without the DOS window), a new DOS window is created for every call to os.spawnl. This is something I would like to avoid because I don't need to have 50 DOS windows opened on my PC. Moreover, I need to keep a reference to self.process, because I woule like to be able to kill the process when the user decides to kill it. In order to kill it, I use a command like: if self.process is not None: if wx.Platform == '__WXGTK__': try: status = os.kill(self.process, 9) except: pass else: try: win32api.TerminateProcess(self.process,0) except: pass status = 0 self.process = None I thought I could use os.popen* things, but it seems to me that they do not return something that could be killed using os.kill() or win32api.TerminateProcess(). Am I missing something about the os things? Does anyone have a better solution? Thanks to you all. Andrea. ------------------------------------------------------------------------------------------------------------------------------------------ Message for the recipient only, if received in error, please notify the sender and read http://www.eni.it/disclaimer/ From peter at engcorp.com Thu Apr 14 09:57:49 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 14 Apr 2005 09:57:49 -0400 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Apr 11) In-Reply-To: <3c670tF6jdeqrU1@individual.net> References: <3c670tF6jdeqrU1@individual.net> Message-ID: Greg Ewing wrote: > (Darn. I finally say something that gets into Quote of the > Week, and it's attributed to someone else! :-) :-) :-) +1 on this for meta-QOTW, solving both problems... From steven.bethard at gmail.com Tue Apr 5 15:35:03 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 05 Apr 2005 13:35:03 -0600 Subject: Propagating poorly chosen idioms In-Reply-To: References: Message-ID: Skip Montanaro wrote: > Unittest's API is difficult enough for me to remember (at least the initial > framework I need to put together) that I generally hunt down some previous > unittest usage, clone it and start from there. I no longer have any idea > what the original unittest example was that got me started using it in the > first place (probably something in the distro's docs). I can only hope it > was a good example. That's a really good point. I do the exact same thing. It's not like Unittest is all that complicated, but it's just complicated enough that I can't remember all the details when I want to write a new one... I've been putting off looking into py.test for a while, but maybe I need to finally do so... STeVe From jarrod.roberson at gmail.com Fri Apr 15 16:26:25 2005 From: jarrod.roberson at gmail.com (fuzzylollipop) Date: 15 Apr 2005 13:26:25 -0700 Subject: How to fix this error in the example in 6.1.4 Files and Directories In-Reply-To: References: <1113583932.703797.118610@o13g2000cwo.googlegroups.com> Message-ID: <1113596785.783631.45380@g14g2000cwa.googlegroups.com> I am running 2.3.5 From martin at v.loewis.de Thu Apr 21 01:34:09 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 21 Apr 2005 07:34:09 +0200 Subject: Array of Chars to String In-Reply-To: References: Message-ID: <42673B51.4040804@v.loewis.de> James Stroud wrote: > astr = "Bob Carol Ted Alice" > letters = "adB" Apparently nobody has proposed this yet: >>> filter(letters.__contains__, astr) 'Bad' >>> filter(set(letters).__contains__, astr) 'Bad' Regards, Martin From srm at netverk.com.ar Mon Apr 25 14:09:43 2005 From: srm at netverk.com.ar (Gonzalo) Date: 25 Apr 2005 11:09:43 -0700 Subject: C++ app. with python scripting IDE ? Message-ID: <1114452583.238627.62000@z14g2000cwz.googlegroups.com> Hi everyone! I want to develop a C++ application, which must be scriptable (I'm considering to use Python or Lua). The end users should develop and run their scripts in an IDE, and the scripting language must be extended with specific functions related to my application. The IDE should have debugging capabilities (step by step execution, breakpoints, watching variables, etc. ) What would be the best option in order to develop this using Python as the scripting language (scheme, configuration, IDE, free/commercial tools, etc)? What language is more suitable for this project, Python or Lua? Thanks in advance. From peter at engcorp.com Thu Apr 14 13:35:39 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 14 Apr 2005 13:35:39 -0400 Subject: smtplib does not send to all recipients In-Reply-To: <1113487680.752215.194840@l41g2000cwc.googlegroups.com> References: <1113244721.415164.81290@f14g2000cwb.googlegroups.com> <1113246181.843652.158520@o13g2000cwo.googlegroups.com> <1113421803.445281.3660@l41g2000cwc.googlegroups.com> <1113487680.752215.194840@l41g2000cwc.googlegroups.com> Message-ID: <9Y-dndpOXf1sNMPfRVn-sA@powergate.ca> dccarson at gmail.com wrote: > OK, I've discovered the lost messages, but I'm still slightly confused > as to why they ended up there. The messages were being delivered to > the local machine, box1.domain.com, even though I was addressing them > to @domain.com. The address is irrelevant with SMTP. What matters is what server you connect to, and how it is configured to handle the envelope you give it. Mail forwarders ought to query a DNS for the "MX" record (on Linux, "dig domain.com mx" for that info) and forward the mail to one of the specified mail exchangers for that domain, regardless of what server you actually connected to for the initial delivery. Not sure this is relevant in your case, but it seems a likely candidate, since smtplib.py does not (and should not) be looking up MX records for you, as far as I know, while the "mail" utility might. -Peter From me at privacy.net Thu Apr 14 22:31:39 2005 From: me at privacy.net (Unknown User) Date: Thu, 14 Apr 2005 23:31:39 -0300 Subject: Is Python appropriate for web applications? Message-ID: I am a Python programmer and I'm thinking about learning PHP, which is similar to C++ (quite different from Python). I want to start writing web applications. Do you think if I learn PHP I'll develop faster? Does PHP have more features? How about the speed of execution? What are the pros and cons? Our server can run both Python, Perl and PHP, so I have the choice. Thanks for your opinion, -- Using Opera's revolutionary e-mail client: http://www.opera.com/mail/ From corey.coughlin at comcast.net Wed Apr 13 18:17:43 2005 From: corey.coughlin at comcast.net (corey.coughlin at comcast.net) Date: 13 Apr 2005 15:17:43 -0700 Subject: build flow? SCons? AAP? process creation? In-Reply-To: <425d7a08$1@news.uni-ulm.de> References: <1113420994.118316.245190@g14g2000cwa.googlegroups.com> <425d7a08$1@news.uni-ulm.de> Message-ID: <1113430663.410239.101560@f14g2000cwb.googlegroups.com> good point, I hadn't checked the docs too closely. Shame it's only in 2.4 though, we're still running 2.2 around here, but it would be nice to have a reason to upgrade, anyway. Thanks for the pointer! From apardon at forel.vub.ac.be Thu Apr 21 07:20:35 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 21 Apr 2005 11:20:35 GMT Subject: Why Python does *SLICING* the way it does?? References: <1113976729.450677.261130@o13g2000cwo.googlegroups.com> <3cpc8oF6n6g9bU1@individual.net> <3cpeu5F64gp32U1@individual.net> Message-ID: Op 2005-04-21, Reinhold Birkenfeld schreef : > Antoon Pardon wrote: >> Op 2005-04-21, Reinhold Birkenfeld schreef : >>> Antoon Pardon wrote: >>> >>>> I sometimes think python should have been more explicite here, >>>> using a marker for the start-index and end-index, may '^' and >>>> '$'. So if you wanted the last element you had to write: >>>> >>>> lst[$] >>>> >>>> And for the next to last element: >>>> >>>> lst[$ - 1] >>>> >>>> >>>> This would make accessing list elements counted from the rear >>>> almost just as easy as it is now but wouldn't interfere with >>>> the ask forgiveness programming style. >>> >>> How would you pass this argument to __getitem__? >> >> Well assuming lst.last, was the last index of lst, __getitem__ >> would get lst.last and lst.last - 1 passed. > > Then it would be an alias for len(lst)-1 ? In the context of current python lists yes. But if you would go further and allow lists to start from an other index than 0 then not. >>> What would be allowed, only '$-x' or also '$+x' or what else? >> >> Any expression where an int is allowed. > > Okay. > >>> What type would '$' be? >> >> It would be an int. > > Where would it be allowed? Only in subscriptions? Yes, the idea would be that the brackets indicate a scope where $ would be the last index and ^ would be the first index. So if you wanted the middle element you could do: lst[(^ + $) // 2] But outsides the brackets the scope where this has any meaning wouldn't be present. Not that I think this idea has any chance. Already I can hear people shout that this is too perlish. But here is another idea. Sometime ago I read about the possibility of python acquiring a with statement. So that instead of having to write: obj.inst1 ... obj.inst2 ... obj.inst1 ... You could write: with obj: .inst1 ... .inst2 ... .inst1 ... If this would get implemented we could think of a left bracked as implicitely exucting a with statement. If we then had a list like class where the start-index could be different from zero and which had properties first and last indicating the first and last index we could then write something like: lst[.last] for the last element or lst[.last - 1] for the next to last element. lst[.first] for the first element lst[(.first + .last) // 2] for the middle element Maybe this makes the proposal again pythonic enough to get a little consideration. -- Antoon Pardon From ivoras at _-_fer.hr Sun Apr 24 19:25:59 2005 From: ivoras at _-_fer.hr (Ivan Voras) Date: Mon, 25 Apr 2005 01:25:59 +0200 Subject: HTML cleaner? Message-ID: Is there a HTML clean/tidy library or module written in pure python? I found mxTidy, but it's a interface to command-line tool. What I'm searching is something that will accept a list of allowed tags and/or attributes and strip the rest from HTML string. From steve at holdenweb.com Tue Apr 26 08:37:50 2005 From: steve at holdenweb.com (Steve Holden) Date: Tue, 26 Apr 2005 08:37:50 -0400 Subject: how to pass an array to a VB array via COM In-Reply-To: <1114515084.138728.26180@g14g2000cwa.googlegroups.com> References: <1114515084.138728.26180@g14g2000cwa.googlegroups.com> Message-ID: jelle wrote: > Hi, > > I'm trying to script Rhino -the nurbs modeller, not the server soft- > via COM. > Which is good fun, except i cant seem to pass arrays to the program. > I suppose its expecting VB arrays, and is not to keen when i send a > tuple: > > RS.AddCurve(((1,2,3),(4,5,6),(7,8,9)),3) > --- > Traceback (most recent call last): > File " ", line 1, in ? > File "c:\Python23\lib\site-packages\jf\interface\RhinoScript.py", > line 48, > in AddCurve > return self._ApplyTypes_(77, 1, (12, 0), ((12, 0), (12, 16)), > 'AddCurve', None,vaPoints, vaDegree) > File "c:\Python23\lib\site-packages\win32com\client\__init__.py", > line > 446, in _ApplyTypes_ > return self._get_good_object_( > com_error: (-2147352567, 'Exception occurred.', (6, 'RhinoScript_m', > 'Type > mismatch in parameter. One-dimensional array required.', 'C:\\Program > Files\\Rhinoceros 3.0\\RhinoScript_m.HLP', 393222, 0), None) > --- > > This is somewhat puzzling, since when i define points in the > application, these are returned as a tuple of tuples: > > > >>>>s = RS.GetPoints() >>>>print s > > ((-7.0, -30.0, 0.0), (15.0, -24.0, 0.0), (-7.0, 12.0, 0.0), (14.0, > 29.0, > 0.0), (28.0, 10.0, 0.0), (20.0, 1.0, 0.0)) > > I've been searching this list for a solution, but didnt find anything i > could use. Any ideas? > Have you tried wrapping them? One of the win32all modules lets you wrap a Python object so it can be accessed by COM interfaces. Not sure whether this will help, but it's a possibility. regards Steve -- Steve Holden +1 703 861 4237 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ From kretino at net.hr Thu Apr 21 03:50:49 2005 From: kretino at net.hr (jozo) Date: 21 Apr 2005 00:50:49 -0700 Subject: Lex References: Message-ID: I NEED HELP!!! From tim.golden at viacom-outdoor.co.uk Fri Apr 15 10:24:06 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Fri, 15 Apr 2005 15:24:06 +0100 Subject: Get OS name Message-ID: <9A28C052FF32734DACB0A288A3533991EBB778@vogbs009.gb.vo.local> [codecraig] | where can I get wmi module, it doesnt come with Python right? | Sorry, should have said. http://timgolden.me.uk/python/wmi.html TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From jfj at freemail.gr Fri Apr 1 19:26:43 2005 From: jfj at freemail.gr (jfj) Date: Fri, 01 Apr 2005 16:26:43 -0800 Subject: StopIteration in the if clause of a generator expression In-Reply-To: References: Message-ID: <424DE6C3.9020305@freemail.gr> Peter Otten wrote: > To confuse a newbies and old hands alike, Bengt Richter wrote: got me for one:) > > To make it a bit clearer, a StopIteration raised in a generator expression > silently terminates that generator: *any* exception raised from a generator, terminates the generator jfj From tjreedy at udel.edu Sun Apr 24 01:44:49 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 24 Apr 2005 01:44:49 -0400 Subject: Variables References: <426B0283.40602@cloudthunder.com> <426B083A.70104@cloudthunder.com> <426B22CD.60208@cloudthunder.com> Message-ID: >>In mathematics, the word 'variable' is generally an undefined meta-term >>that is *notorious* for having multiple possible meanings and shades of >>meaning. One mathematician/linguist once claimed to have discerned >>somewhere around 15 different meanings and shades thereof. >> > What is his/her name? Wish I could remember but this was some decades ago. But you should be able to think a few yourself. Terry J. Reedy From ville at spammers.com Fri Apr 22 10:14:17 2005 From: ville at spammers.com (Ville Vainio) Date: 22 Apr 2005 17:14:17 +0300 Subject: Regular Expressions - Python vs Perl References: <1114092105.964664.211430@l41g2000cwc.googlegroups.com> Message-ID: >>>>> "Ilpo" == Ilpo Nyyss?nen writes: Ilpo> Of course it caches those when running. The point is that it Ilpo> needs to recompile every time you have restarted the Ilpo> program. With short lived command line programs this really Ilpo> can be a problem. I didn't imagine it could be longer than 1 second overhead - and if you have so many regexps, it must do something so nontrivial that 1 second doesn't matter. Perhaps I have a different mindset about this :-). Ilpo> And yes, I have read the source of sre.py and I have made an Ilpo> ugly module that digs the compiled data and pickles it to a Ilpo> file and then in next startup it reads that file and puts Ilpo> the stuff back to the cache. What's so ugly about it? The fact that you need to rewrite the cache when you change some of the regexps? I can't imagine you change more than, say, 10 of the regexps a day (compiling of which is an insignificant performance hit) and when you "ship" the script, you will freeze the regexps anyway. -- Ville Vainio http://tinyurl.com/2prnb From skip at pobox.com Tue Apr 5 13:20:47 2005 From: skip at pobox.com (Skip Montanaro) Date: Tue, 5 Apr 2005 12:20:47 -0500 Subject: Propagating poorly chosen idioms Message-ID: <16978.51439.878409.497671@montanaro.dyndns.org> Peter> unitttest is surely not the be all and end all of Python unit Peter> testing frameworks... but it's one of the batteries included in Peter> the standard distribution, and it's pretty trivial to get started Peter> using it, unless maybe you try to go by the documentation instead Peter> of by the examples... This reminded me of something I noticed awhile ago. If you're learning something new, there is a tendency to find a working example to start from, then modify it to suit your needs. This is fine as far as it goes, however, if the idioms used in the code you're cloning are suboptimal, they get cloned. Unittest's API is difficult enough for me to remember (at least the initial framework I need to put together) that I generally hunt down some previous unittest usage, clone it and start from there. I no longer have any idea what the original unittest example was that got me started using it in the first place (probably something in the distro's docs). I can only hope it was a good example. >From that standpoint the simpler API of py.test seems attractive. Skip From rkern at ucsd.edu Sat Apr 16 23:17:54 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sat, 16 Apr 2005 20:17:54 -0700 Subject: new to mac OS10 In-Reply-To: <4261C311.8070502@acm.org> References: <1113571800.485209.169320@z14g2000cwz.googlegroups.com> <4261C311.8070502@acm.org> Message-ID: Maurice LING wrote: > Hi Thomas, > > It seems that you've cleanly killed the Apple-installed Python, which > isn't too bad a thing after all. What I can suggest you do is this... > Copy the entire /System/Library/Frameworks/Python.framework directory > from someone and drop it into your system (same place of course). I will > not suggest installing Python 2.4.1 until the Apple-installed Python is > sorted out. My reasons being, > > 1. I have no idea what Mac OSX uses Python for. Although symlink may get > you through most of the time but I cannot be sure that none of OSX's > stuffs are hardcoded to use the Python in > /System/Library/Frameworks/Python.framework. I believe Apple only uses it for their fax utilities. There's also the CoreGraphics wrapper (which the fax stuff uses), but that's pretty useless as it is. > 2. Installing another Python may or may not be a precise remedy. It may > just worsen things and I won't want to bet on that. The 2.4.1 build by Bob Ippolito is designed to work alongside the system-installed Python. It certainly won't replace it, but it shouldn't worsen anything. > 3. Apple-installed Python's command line tools are symlinked from > /usr/bin to /System/Library/Frameworks/Python.framework but the OSX > installer for Python 2.4.1 places the commandline tools in > /usr/local/bin and symlinked to /Library/Frameworks/Python.framework. So > it seems to me that Python 2.4.1 (installed using OSX installer for > Python 2.4.1) is not a precise replacement of Apple-installed Python... Bingo. It's not intended to be one. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From michele.simionato at gmail.com Tue Apr 12 08:51:09 2005 From: michele.simionato at gmail.com (Michele Simionato) Date: 12 Apr 2005 05:51:09 -0700 Subject: singleton objects with decorators In-Reply-To: References: <1113300588.335527.26290@o13g2000cwo.googlegroups.com> Message-ID: <1113310269.596284.136100@f14g2000cwb.googlegroups.com> Uwe Mayer wrote: > "Singleton" is simple (like the wheel), but that does not make it stupid. > There are two aspects that are important: > > 1. a Singleton has one, very simple property and virtually everyone knows > what you talk about when you explain that you used a "Singleton". In this > case its just a technical term. We need technical terms. No. Not everybody knows about Singleton. It is an acquired knowledge. The reason why I am so opposed to Singletons is that a while ago I was in the condition of not knowing what a Singleton was. However, everybody was talking about Singletons, posting recipes of how to implement them in Python, etc. So I figured out it was a very important concept and that I was missing something, since I was incapable of understand its relevance. It was only after many months that I understood that there was really nothing more to it. I am the kind of person that can learn easily even very hard concept, if I can see and use/interest for them. However, I find extremely difficult to learn even simple concepts if they do not make sense for me. Singleton did not make sense for me since I did not have an use case for it. Now, I have some use case for it, but still I think these use cases are much better managed by memoize. BTW, when I first heard about memoize, I understood it instantenously, since I had tons of cases where I had implemented it in my own code without knowing the technique was called memoize. There is so much to know. I don't want to waste my time with concepts that are not worth it. IMO, Singleton is not worth the fuss, and we would be better off without a fancy name for it (just tell what it is: a class returning always the same instance). Let us reserve fancy names to worthy concepts. In my lectures at Oxford next week I have carefully expunged anything referring to Singletons ;) > 2. the property of a Singleton, i.e. there is only one, is important - you > use it yourself through memoize. That is just a more flexible > implementation of having one instance of whatever you memoize. IMNSHO, the property "there is only one" is not important enough to deserves a name. The property "if you have already called this callable with the same arguments you don't need to recompute it" instead is quite worthy and subsumes the other concept as a special case. It also gives you plenty of use case to illustrate it, even to beginner programmers. Michele Simionato From bokr at oz.net Sat Apr 16 11:24:49 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 16 Apr 2005 15:24:49 GMT Subject: pre-PEP: Simple Thunks References: Message-ID: <4260bc72.67216001@news.oz.net> On Fri, 15 Apr 2005 16:44:58 -0700, Brian Sabbey wrote: >Here is a first draft of a PEP for thunks. Please let me know what you >think. If there is a positive response, I will create a real PEP. > >I made a patch that implements thunks as described here. It is available >at: > http://staff.washington.edu/sabbey/py_do > >Good background on thunks can be found in ref. [1]. UIAM most of that pre-dates decorators. What is the relation of thunks to decorators and/or how might they interact? > >Simple Thunks >------------- > >Thunks are, as far as this PEP is concerned, anonymous functions that >blend into their environment. They can be used in ways similar to code >blocks in Ruby or Smalltalk. One specific use of thunks is as a way to >abstract acquire/release code. Another use is as a complement to >generators. "blend into their environment" is not very precise ;-) If you are talking about the code executing in the local namespace as if part of a suite instead of apparently defined in a separate function, I think I would prefer a different syntax ;-) > >A Set of Examples >================= > >Thunk statements contain a new keyword, 'do', as in the example below. The >body of the thunk is the suite in the 'do' statement; it gets passed to >the function appearing next to 'do'. The thunk gets inserted as the first >argument to the function, reminiscent of the way 'self' is inserted as the >first argument to methods. > >def f(thunk): > before() > thunk() > after() > >do f(): > stuff() > >The above code has the same effect as: > >before() >stuff() >after() Meaning "do" forces the body of f to be exec'd in do's local space? What if there are assignments in f? I don't think you mean that would get executed in do's local space, that's what the thunk call is presumably supposed to do... But let's get on to better examples, because this is probably confusing some, and I think there are better ways to spell most use cases than we're seeing here so far ;-) I want to explore using the thunk-accepting function as a decorator, and defining an anonymous callable suite for it to "decorate" instead of using the do x,y in deco: or do f(27, 28): format. To define an anonymous callable suite (aka thunk), I suggest the syntax for do x,y in deco: suite should be @deco (x, y): # like def foo(x, y): without the def and foo suite BTW, just dropping the def makes for a named thunk (aka callable suite), e.g. foo(x, y): suite which you could call like foo(10, 4) with the local-where-suite-was-define effect of x = 10 y = 4 suite BTW, a callable local suite also makes case switching by calling through locals()[xsuitename]() able to rebind local variables. Also, since a name is visible in an enclosing scope, it could conceivably provide a mechanism for rebinding there. E.g., def outer(): xsuite(arg): x = arg def inner(): xsuite(5) x = 2 print x # => 2 inner() print x # => 5 But it would be tricky if outer returned inner as a closure. Or if it returned xsuite, for that matter. Probably simplest to limit callable suites to the scope where they're defined. > >Other arguments to 'f' get placed after the thunk: > >def f(thunk, a, b): > # a == 27, b == 28 > before() > thunk() > after() > >do f(27, 28): > stuff() I'm not sure how you intend this to work. Above you implied (ISTM ;-) that the entire body of f would effectively be executed locally. But is that true? What if after after() in f, there were a last statment hi='from last statement of f' Would hi be bound at this point in the flow (i.e., after d f(27, 28): stuff() )? I'm thinking you didn't really mean that. IOW, by magic at the time of calling thunk from the ordinary function f, thunk would be discovered to be what I call an executable suite, whose body is the suite of your do statement. In that case, f iself should not be a callable suite, since its body is _not_ supposed to be called locally, and other than the fact that before and after got called, it was not quite exact to say it was _equivalent_ to before() stuff() # the do suite after() In that case, my version would just not have a do, instead defining the do suite as a temp executable suite, e.g., if instead we make an asignment in the suite, to make it clear it's not just a calling thing, e.g., do f(27, 28): x = stuff() then my version with explict name callable suite would be def f(thunk, a, b): # a == 27, b == 28 before() thunk() after() set_x(): x = stuff() # to make it plain it's not just a calling thing f(set_x, 27, 28) # x is now visible here as local binding but a suitable decorator and an anonymous callable suite (thunk defined my way ;-) would make this @f(27, 28) (): x = stuff() > >Thunks can also accept arguments: > >def f(thunk): > thunk(6,7) > >do x,y in f(): > # x==6, y==7 > stuff(x,y) IMO @f (x, y): stuff(x, y) # like def foo(x, y): stuff(x, y) is clearer, once you get used to the missing def foo format > >The return value can be captured > This is just a fallout of f's being an ordinary function right? IOW, f doesn't really know thunk is not an ordinary callable too? I imagine that is for the CALL_FUNCTION byte code implementation to discover? >def f(thunk): > thunk() > return 8 > >do t=f(): > # t not bound yet > stuff() > >print t >==> 8 That can't be done very well with a decorator, but you could pass an explicit named callable suite, e.g., thunk(): stuff() t = f(thunk) > >Thunks blend into their environment ISTM this needs earlier emphasis ;-) > >def f(thunk): > thunk(6,7) > >a = 20 >do x,y in f(): > a = 54 >print a,x,y > >==> 54,6,7 IMO that's more readable as def f(thunk): thunk(6, 7) @f (x, y): # think def foo(x, y): with "def foo" missing to make it a thunk a = 54 print a,x,y IMO we need some real use cases, or we'll never be able to decide what's really useful. > >Thunks can return values. Since using 'return' would leave it unclear >whether it is the thunk or the surrounding function that is returning, a >different keyword should be used. By analogy with 'for' and 'while' loops, >the 'continue' keyword is used for this purpose: Gak ;-/ > >def f(thunk): > before() > t = thunk() > # t == 11 > after() > >do f(): > continue 11 I wouldn't think return would be a problem if the compiler generated a RETURN_CS_VALUE instead of RETURN_VALUE when it saw the end of the callable suite (hence _CS_) (or thunk ;-) Then it's up to f what to do with the result. It might pass it to after() sometimes. > >Exceptions raised in the thunk pass through the thunk's caller's frame >before returning to the frame in which the thunk is defined: But it should be possible to have try/excepts within the thunk, IWT? > >def catch_everything(thunk): > try: > thunk() > except: > pass # SomeException gets caught here > >try: > do catch_everything(): > raise SomeException >except: > pass # SomeException doesn't get caught here because it was >already caught > >Because thunks blend into their environment, a thunk cannot be used after >its surrounding 'do' statement has finished: > >thunk_saver = None >def f(thunk): > global thunk_saver > thunk_saver = thunk > >do f(): > pass > >thunk_saver() # exception, thunk has expired Why? IWT the above line would be equivalent to executing the suite (pass) in its place. What happens if you defined def f(thunk): def inner(it): it() inner(thunk) do f(): x = 123 Of course, I'd spell it @f (): x = 123 Is there a rule against that (passing thunk on to inner)? > >'break' and 'return' should probably not be allowed in thunks. One could >use exceptions to simulate these, but it would be surprising to have >exceptions occur in what would otherwise be a non-exceptional situation. >One would have to use try/finally blocks in all code that calls thunks >just to deal with normal situations. For example, using code like > >def f(thunk): > thunk() > prevent_core_meltdown() > >with code like > >do f(): > p = 1 >return p > >would have a different effect than using it with > >do f(): > return 1 > >This behavior is potentially a cause of bugs since these two examples >might seem identical at first glance. I think less so with decorator and anonymous callable suite format @f (): return 1 # as in def foo(): return 1 -- mnemonically removing "def foo" > >The thunk evaluates in the same frame as the function in which it was >defined. This frame is accessible: > >def f(thunk): > frame = thunk.tk_frame # no connection with tkinter, right? Maybe thunk._frame would also say be careful ;-) assert sys._getframe(1) is frame # ?? when does that fail, if it can? > >do f(): > pass > >Motivation >========== > >Thunks can be used to solve most of the problems addressed by PEP 310 [2] >and PEP 288 [3]. > >PEP 310 deals with the abstraction of acquire/release code. Such code is >needed when one needs to acquire a resource before its use and release it >after. This often requires boilerplate, it is easy to get wrong, and >there is no visual indication that the before and after parts of the code >are related. Thunks solve these problems by allowing the acquire/release >code to be written in a single, re-usable function. > >def acquire_release(thunk): > f = acquire() > try: > thunk(f) > finally: > f.release() > >do t in acquire_release(): > print t > That could be done as a callable suite and decorator @acquire_release (t): print t # like def foo(t): print t except that it's a thunk (or anonymous callable suite ;-) BTW, since this callable suite definition is not named, there is no name binding involved, so @acquire_release as a decorator doesn't have to return anything. >More generally, thunks can be used whenever there is a repeated need for >the same code to appear before and after other code. For example, > >do WaitCursor(): > compute_for_a_long_time() > >is more organized, easier to read and less bug-prone than the code > >DoWaitCursor(1) >compute_for_a_long_time() >DoWaitCursor(-1) That would reduce to @WaitCursor (): compute_for_a_long_time() > >PEP 288 tries to overcome some of the limitations of generators. One >limitation is that a 'yield' is not allowed in the 'try' block of a >'try'/'finally' statement. > >def get_items(): > f = acquire() > try: > for i in f: > yield i # syntax error > finally: > f.release() > >for i in get_items(): > print i > >This code is not allowed because execution might never return after the >'yield' statement and therefore there is no way to ensure that the >'finally' block is executed. A prohibition on such yields lessens the >suitability of generators as a way to produce items from a resource that >needs to be closed. Of course, the generator could be wrapped in a class >that closes the resource, but this is a complication one would like to >avoid, and does not ensure that the resource will be released in a timely >manner. Thunks do not have this limitation because the thunk-accepting >function is in control-- execution cannot break out of the 'do' statement >without first passing through the thunk-accepting function. > >def get_items(thunk): # <-- "thunk-accepting function" > f = acquire() > try: > for i in f: > thunk(i) # A-OK > finally: > f.release() > >do i in get_items(): > print i @get_items (i): print i But no yields in the thunk either, that would presumably not be A-OK ;-) > >Even though thunks can be used in some ways that generators cannot, they >are not nearly a replacement for generators. Importantly, one has no >analogue of the 'next' method of generators when using thunks: > >def f(): > yield 89 > yield 91 > >g = f() >g.next() # == 89 >g.next() # == 91 > >[1] see the "Extended Function syntax" thread, >http://mail.python.org/pipermail/python-dev/2003-February/ >[2] http://www.python.org/peps/pep-0310.html >[3] http://www.python.org/peps/pep-0288.html It's interesting, but I think I'd like to explore the decorator/callable suite version in some real use cases. IMO the easy analogy with def foo(args): ... for specifying the thunk call parameters, and the already established decorator call mechanism make this attractive. Also, if you allow named thunks (I don't quite understand why they should "expire" if they can be bound to something. The "thunk-accepting function" does not appear to "know" that the thunk reference will turn out to be a real thunk as opposed to any other callable, so at that point it's just a reference, and should be passable anywhere -- except maybe out of its defining scope, which would necessitate generating a peculiar closure. For a named callable suite, the decorator would have to return the callable, to preserve the binding, or change it to something else useful. But without names, I could envisage a stack of decorators like (not really a stack, since they are independent, and the first just uses the thunk to store a switch class instance and a bound method to accumulate the cases ;-) @make_switch (switch, case): pass @case(1,2,3,5) (v): print 'small prime: %s'% v @case(*'abc') (v): print 'early alpha: %r'% v @case() (v): print 'default case value: %r'%v and then being able to call switch('b') and see early alpha: 'b' Not that this example demonstrates the local rebinding capability of thunks, which was the whole purpose of this kind of switch definition ;-/ Just substitute some interesting suites that bind something, in the place of the prints ;-) Regards, Bengt Richter From tzot at sil-tec.gr Wed Apr 20 11:20:14 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 20 Apr 2005 18:20:14 +0300 Subject: random number between 0 and 20 References: <1114010102.027562.150840@z14g2000cwz.googlegroups.com> Message-ID: On 20 Apr 2005 08:15:02 -0700, rumours say that aleksander.helgaker at gmail.com might have written: >How can I generate a random number between 0 - 20 and store the number >in nrrandom? Just choose a random number yourself, eg. nrrandom=17 (just kidding :) import random nrrandom = random.randint(0,20) See also the random.randrange function. -- TZOTZIOY, I speak England very best. "Be strict when sending and tolerant when receiving." (from RFC1958) I really should keep that in mind when talking with people, actually... From bokr at oz.net Fri Apr 22 11:43:52 2005 From: bokr at oz.net (Bengt Richter) Date: Fri, 22 Apr 2005 15:43:52 GMT Subject: How to run Python in Windows w/o popping a DOS box? References: <7xekd66ra3.fsf@ruckus.brouhaha.com> <4265d7b4.27743873@news.oz.net> <7xk6mvh5cn.fsf@ruckus.brouhaha.com> Message-ID: <42690932.237021939@news.oz.net> On 21 Apr 2005 20:12:40 -0700, Paul Rubin wrote: >bokr at oz.net (Bengt Richter) writes: > >> I would try right-clicking the shortcut icon and selecting >> properties, then select the shortcut tab and edit the target string >> with s/python/pythonw/ and then click ok. >> >> Then try double clicking the shortcut icon again. If that does it, >> you're home ;-) If not, post more symptoms. > >Hmm, I clicked properties and the word python doesn't appear in the >shortcut string. The shortcut string simply points to the .py file. Ok, in that caseput \pythonw.exe in front of that. If you need to have current working directory some place particular, there is a "Start in" slot for that on the same property tab. >I think Windows knows to run Python because of some registry entry >that maps the .py extension to python.exe. I don't know which entry >and changing it sounds a little bit dangerous. Right, but you don't have to. > >I did see that I could select a button launch the dos box minimized, >so it doesn't clutter up the screen. That mostly solves the immediate >problem. A more complete solution (eliminate dos box altogether) >would be nice, but I can live with an auto-minimized box. > As someone else suggested, you could also change the extension on your script from .py to .pyw (and make that change in your shortcut too (or delete it and make a new shortcut to the renamed script), or it won't find the renamed script ;-). If you type assoc .py in a cmd console window, you should get what category of file the windows registry thinks .py files are. (it uses an intermediate category classification so that the category can be associated with a program -- e.g., many extensions might be categorized as text files beside .txt and wind up starting notepad). To find what's associated with the file category (sorry, type), type ftype categoryname For .py and .pyw on my system, you get this: [ 8:30] C:\pywk\clp>assoc .py .py=Python.File [ 8:30] C:\pywk\clp>assoc .pyw .pyw=Python.NoConFile [ 8:30] C:\pywk\clp>ftype python.File python.File=d:\python23\python.exe "%1" %* [ 8:30] C:\pywk\clp>ftype python.NoConFile python.NoConFile=D:\Python23\pythonw.exe "%1" %* To get the whole list of assocs, type it without arg then pipe to more or window's grep aka findstr (qgrep might be avail too) [ 8:30] C:\pywk\clp>assoc | findstr py .py=Python.File .pyc=Python.CompiledFile .pyo=Python.CompiledFile [ 8:30] C:\pywk\clp>ftype | findstr py Python.CompiledFile=D:\Python23\python.exe "%1" %* Python.File=d:\python23\python.exe "%1" %* Python.NoConFile=D:\Python23\pythonw.exe "%1" %* (I'm not running py24 via association, and in fact rarely let the system do it, since I need to run python explictly to pipe script input or output due to broken windows piping in file-associated script execution on my system). NB: If you type assoc or ftype with the "=" assignment string in format that it shows you, (e.g. assoc .py=Python.File ) you will non-gui-wise be setting the association in the registry, assuming you have privilege, so BE CAREFUL with that ;-) -->> Especially don't mess with .exe association! That was tricky to recover from. (I actually did that accidentally via Netscape's gui file association thing long ago, not from the command window ;-) (Start>run>browse can find you regedt32.exe and you can do anything you want to the registry from there, if you have the information and privilege. The information part is harder to get that privilege in most cases ;-) BTW you can do a whole bunch of stuff in the target slot of a shortcut. E.g., my main one to start a "DOS box" from the start menu[1] has %SystemRoot%\system32\cmd.exe /x /k prompt [$T$H$H$H$H$H$H] $P$G& d:\vc98\bin\vcvars32.bat & home.cmd & title C++ Which starts cmd.exe with /x options and /k to keep it displayed, changes the prompt, runs the .bat script to set environment for MSVC++, runs a little command script I made called home.cmd, which enables me easily to come back to various project "home" directories, and sets a title in the title bar, so my window is ready to go. A different one can set me up to use Borland's Delphi command line object pascal compiler, etc., settting appropriate path and other environment variables, so the right set of command utilities are accessible, and others that might have the same name are not. [1](which uses shortcuts you can get at via start>settings>taskbar>start-menu-programs> etc) Hm, I need to set my computer clock ... Regards, Bengt Richter From rbt at athop1.ath.vt.edu Wed Apr 13 08:22:47 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Wed, 13 Apr 2005 08:22:47 -0400 Subject: Python documentation moronicities (continued) In-Reply-To: <1113388891.512839.111250@f14g2000cwb.googlegroups.com> References: <1113301533.054410.203710@z14g2000cwz.googlegroups.com> <1113346139.139720.17510@o13g2000cwo.googlegroups.com> <1113388891.512839.111250@f14g2000cwb.googlegroups.com> Message-ID: runes wrote: > Generally: I have got my experiences with the Python Manual over the > the last 30 months Python beeing my preferred language. One of them is > that I have to look elsewhere. I've gotten great help from this newsgroup. By following these steps: 1. Read the docs at http://docs.python.org/modindex.html 2. Trail & Error testing. 3. If 2 doesn't work or if I don't fully understand how it's working, I post a message here asking for help and clarification. I've never been disappointed with the help I've received here. There will always be a few wise guys who like to make snide remarks and give arrogant answers, but it has been my experience that 95% of the people who answer do so with a very helpful, encouraging attitude. From steve at holdenweb.com Sat Apr 9 02:22:45 2005 From: steve at holdenweb.com (Steve Holden) Date: Sat, 09 Apr 2005 02:22:45 -0400 Subject: Thoughts on some stdlib modules In-Reply-To: References: Message-ID: Ron_Adam wrote: > On Fri, 08 Apr 2005 05:15:23 -0400, vegetax > wrote: > > >>Are those issues being considered right now? i cant find any PEP addressing >>the issue especifically, at least cooking it for python 3000. >> >>specific topics could be: >> >>grouping related modules. >>removing useless legacy modules. >>refactoring duplicated functionality. >>removing/redesigning poorly written modules. >>adding a module versioning system. > > > I've been thinking that the lib directory could be better named and > rearranged a bit. I sometimes mistakenly open the libs directory > instead of lib because of the name similarity. > > An alternative might be to use the name "packs" or "packages" in place > of "lib", which would emphasize the use of packages as the primary > method of extending python. The standard library could then be a > package called "stdlib" within this directory. Third party packages > would then be along side "stdlib" and not within a directory that is > within the standard library. > > It would be mostly a cosmetic change, but I believe it would be worth > doing if it could be done without breaking programs that may have hard > coded path references to the library. :-/ > > Ron > Ron: You do a lot of thinking, don't you? :-) This is a *very large* change, not a cosmetic one, requiring changes to many installation routines (including, probably, distutils) and causing problems for software that attempts to operate with multiple versions of Python - and those projects have problems enough as it is despite Python's quite fine record of careful development. This seems a rather high price to pay just to avoid having you mistakenly avoid opening "libs" instead of "lib" - a distinction that is only meaningful on Windows platforms anyway, I believe. You are correct in suggesting that the library could be better organized than it is, but I felt we would be better off deferring such change until the emergence of Python 3.0, which is allowed to break backwards compatibility. So, start working on your scheme now - PEP 3000 needs contributions. My own current favorite idea is to have the current standard library become the "stdlib" package, but I'm sure a lot of people would find that suggestion at least as half-baked as yours. {If an idea is more-half-baked than something exactly half-baked is it 0.4-baked or 0.6-baked? Does "more half-baked" actually mean "less baked"?) regards Steve -- Steve Holden +1 703 861 4237 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ From juggs at dfgt.com Thu Apr 21 17:07:45 2005 From: juggs at dfgt.com (ionic) Date: Thu, 21 Apr 2005 22:07:45 +0100 Subject: New line References: <42680a8a_1@mk-nntp-2.news.uk.tiscali.com> <42680edf_3@mk-nntp-2.news.uk.tiscali.com> <1114116277.575910.172080@f14g2000cwb.googlegroups.com> Message-ID: <426816a1_2@mk-nntp-2.news.uk.tiscali.com> Got it now thanks all -- "It's all in fun or life isn't worth it!" "wittempj at hotmail.com" wrote in message news:1114116277.575910.172080 at f14g2000cwb.googlegroups.com... > okay, you type your code in idle, and run your code by hitting the F5 > key? > From erikober at gmail.com Fri Apr 29 14:34:04 2005 From: erikober at gmail.com (erikober at gmail.com) Date: 29 Apr 2005 11:34:04 -0700 Subject: tkinter OptionMenu column break Message-ID: <1114799644.189218.307370@g14g2000cwa.googlegroups.com> I'm creating a OptionMenu button for a gui and I'm having a problem where the drop down list is so long that most of the options are off screen. The correct behavior would be that another drop down menu list would be created next to it with the continued options. Here is the small code snippet that I have now: myOptionList = ....... OMcreate = "OptionMenu(frame, myVar, \"%s\", command=myOMCB)"%(myOptionList) I was thinking that there must be some variable to do this. Any help would be much appreciated. Thanks! From radam2 at tampabay.rr.com Sat Apr 2 19:03:54 2005 From: radam2 at tampabay.rr.com (Ron_Adam) Date: Sun, 03 Apr 2005 00:03:54 GMT Subject: Docorator Disected References: <4p9t419ockcg8578g6guse3a14t16orebf@4ax.com> <424f04d0.137947037@news.oz.net> Message-ID: On Sat, 02 Apr 2005 21:28:36 GMT, bokr at oz.net (Bengt Richter) wrote: >I think it might help you to start out with very plain decorators rather than >decorators as factory functions that return decorator functions that wrap the >decorated function in a wrapper function. E.g., (this could obviously be >parameterized as a single decorator factory, but I wanted to show the simplest level >of decorator functionality) Thanks for the examples of stacked decorators! :-) I think I pretty much got it now, I had never needed to pass arguments to nested "defined" functions before and none of the documentation I have, ever mentioned that alternative. So I didn't know I could do this: def foo(a1): def fee(a2): return a1+a2 return fee fum = foo(2)(6) <------ !!! # fum is 8 The interesting thing about this is the 'return fee' statement gets the (6) apparently appended to it. So it becomes 'return fee(6). That subtle action is confusing if you don't already know about it, which I didn't. In this example. def foo(a1): def fee(a2): return a1+a2 return fee fum = foo(2) There is no second set of arguments to append to 'return fee', so the name fum is pointed to object fee instead and fee is not evaluated. This second subtle action, is also confusing if you aren't aware of it. Since the two look the same when you examine the def statements. So there is no reason to think they would not act the same, both returning an function object. Now, add in the @decorator syntax to the mix. Which hides the extra argument sets that are passed to the nested defined functions and the obscuration is complete. There then is no visual indication of where the function calls get their arguments from, and this is what I believe caused me to have so much trouble with this. Another inconsistency, although not a bad one, is that nested 'defined' function share scope, but nested function calls do not. Now what this means, is it will be very difficult for some people to put it all together. I would have gotten it sooner or later, but I really happy to have help from comp.lang.python. on this one. :) >I like annotated code walk-throughs. But as others have pointed out, >it's still a bit buggy ;-) It helped a lot, but notice that it took me several tries. That's a strong indicator that decorators are more implicit than explicit and that goes against the "Explicit is better than Implicit" guideline that python tries to follow. Maybe there are ways to make decorators -and- nested function calls a bit more explicit? I think a having indicators on the return statements that are meant to return a value vs object would help readability and take some of the mystery out as far as the un initiated are concerned. def foo(a1): def fee(a2): def fiddle(a3): pass return a3 return fee # Always return a function object. # Error, if argument is passed to it. # and return fee(a2) # always require an argument, # error if none is passed to it. Or some other way if this breaks something. But it will make it more apparent what nested function should do. And give clearer feed back when trying to use or write decorators. I'm not sure what might make @decorator more explicit. Maybe allowing all the function to be specified as an option. Maybe it is already(?) @decorator(a1)(foo) def foo(): pass So we will have: def foo(a1): def fee(a2): def fiddle(a3): pass return a3 return fee # Object always returned here or # or error if argument is received. @decorator(a1)(fum) # Last argument optional. def fum(a3): return a3 These I think are small changes that might be acceptable. A little more aggressive alterations would be: Requiring the 'function' argument may have a use when using stacked decorators. Then it could be inserted into a sequence? @deco3(postcalc) @deco2(fum) @deco1(precalc) def fum(pointxyz): return translatepoint(pointxyz) ... and that reversed order... (yuck!), is it really necessary? Readability is important, and it is a big reason people don't jump ship for some other language. Why the exceptions here? Ok, don't mean to grip. :-) I'm sure there's been plenty of that in past discussions. Cheers, Ron From michael.kearns at REMOVEsaaconsultants.com Tue Apr 12 06:35:42 2005 From: michael.kearns at REMOVEsaaconsultants.com (Michael Kearns) Date: Tue, 12 Apr 2005 11:35:42 +0100 Subject: Python 2.4 killing commercial Windows Python development ? In-Reply-To: References: <1113264839.497914.210170@z14g2000cwz.googlegroups.com> <425b8cf7$0$38043$bed64819@news.gradwell.net> Message-ID: <425ba44e$0$38038$bed64819@news.gradwell.net> Fredrik Lundh wrote: > Michael Kearns wrote: >>I would guess from the responses so far that Python 2.4 just isn't used within commercially >>shipping products > > that kind of unfounded hyperbole only makes you look silly. As no-one had replied that they had found it fine to use in a commercial sense, or pointed to other product that may use it, I'm not entirely sure how it makes me look any sillier than I normally do in real life. >>I don't know. > > exactly. now calm down, and go read the replies to this thread again. or consult > a lawyer, and make it clear to him that you're not actually *using* the MSVCR71 > component yourself, *and* that the Python application you are using (and passing > on to your users) is adding significant and primary functionality to the MSCVR71 > library. I apologise if my writing suggests a lack of calm. I have fully read the replies, and although there are many fine suggestions of shipping additional products, none seems to address the lack of legality regarding the windows distribution other than "It's not the Python developers problem". Again, if I paraphrased incorrectly, I'm sorry. As for consulting a lawyer, this is exactly what I'm trying to avoid. My usage of python in a commercial sense is as a small utility - a helper, if you will. It has no business value whatsoever, compared to the product that it ships with, and certainly does not warrant any investment regarding legal advice. I would agree that Python is adding significant value to the library. Unfortunately, the Microsoft Redistribution document, from what I read, does not allow an end-user to further redistribute the library. I am that end-user, of Python. The whole situation is already becoming far more work than if I'd used a different technology for what I had to achieve, and as such I have no desire to pursue it further. I'm once more running 2.3, and happy with that. With respect, Michael. From quantumcheesedog at gmail.com Wed Apr 6 20:41:01 2005 From: quantumcheesedog at gmail.com (python newbie) Date: Thu, 07 Apr 2005 00:41:01 GMT Subject: Harvestman install not working References: <1112811970.231676.122830@g14g2000cwa.googlegroups.com> Message-ID: First of all, please disregard the extra posts, Anand, I need to really really get a new newsreader. It kept on giving me an error, making me think that each sendbutton click wasnt' working. My mistake, I use the Harvestman.Py in the main folder, of course. It works fine. Thanks again. "Anand" wrote in message news:1112811970.231676.122830 at g14g2000cwa.googlegroups.com... > Hi > > Latest version of py2exe does not support the option > --force-imports anymore I think. You can edit the .bat file to remove > that option. It should work. > > -Anand > From beliavsky at aol.com Sun Apr 3 09:11:05 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 3 Apr 2005 06:11:05 -0700 Subject: text analysis in python References: Message-ID: <1112533865.277154.241930@o13g2000cwo.googlegroups.com> The book "Text Processing in Python" by David Mertz, available online at http://gnosis.cx/TPiP/ , may be helpful. From steve at holdenweb.com Sat Apr 30 11:11:06 2005 From: steve at holdenweb.com (Steve Holden) Date: Sat, 30 Apr 2005 11:11:06 -0400 Subject: Tkinter app=App(root) problem In-Reply-To: <1114870083.651218.160450@l41g2000cwc.googlegroups.com> References: <1114870083.651218.160450@l41g2000cwc.googlegroups.com> Message-ID: snoylr at gmail.com wrote: > This is my first day working with Tkinter. I'm using python2.3 on > WindowsXP. I found this program and entered it. > > from Tkinter import * > > class App: > def _init_(self,master): ^^^^^^ This should be __init__ (the underscores should be doubled). Python "magic methods" are all named in this way. > frame = Frame(master) > frame.pack() > > self.button = Button(frame, text = "Quit", fg = "red", command > =frame.quit) > self.button.pack(side=LEFT) > > self.hi_there = Button(frame, text = "Hello", command = > self.say_hi) > self.hi_there.pack(side=LEFT) > > def say_hi(self): > print "hi there, everyone!" > > root = Tk() > app = App(root) > root.mainloop() > > When I run the code in IDLE I get the initial frame but no buttons with > the following error: > > Traceback (most recent call last): > File "C:\Documents and Settings\INTERNET\Desktop\hello2.py", line 18, > in ? > app = App(root) > TypeError: this constructor takes no arguments > > I have also tried to save the program as with a pyw extension. Nothing > happens when I try to run it with that extension. > That's not strictly true. Nothing *appears* to happen, because the same error message is produced but there's no windows console to display it in. regards Steve -- Steve Holden +1 703 861 4237 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ From tjreedy at udel.edu Thu Apr 14 13:37:53 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 14 Apr 2005 13:37:53 -0400 Subject: String manipulation References: Message-ID: "vincent wehren" wrote in message news:d3ktct$h5m$1 at news2.zwoll1.ov.home.nl... > "Nicholas Graham" > | Any suggestions? > Take a look at the built-in functions ord() and chr() > -- Chapter 2.1 of the manual. And more generally, read all of Chap.2 of the Library Reference on builtin functions and types. Later chapters, most of them, are 'look up when you need to' type stuff, but C.2 is core material that everyone should read after the tutorial. Terry J. Reedy From ionel.mc at gmail.com Mon Apr 4 22:38:04 2005 From: ionel.mc at gmail.com (ionel) Date: Tue, 5 Apr 2005 04:38:04 +0200 Subject: raw sockets please Message-ID: anyone got any idea how the get raw sockets working on win32 ? (on python 2.4) -- ionel. From mage at mage.hu Sat Apr 23 16:14:11 2005 From: mage at mage.hu (Mage) Date: Sat, 23 Apr 2005 22:14:11 +0200 Subject: Handling lists In-Reply-To: <1114285850.091749.188680@f14g2000cwb.googlegroups.com> References: <1114285850.091749.188680@f14g2000cwb.googlegroups.com> Message-ID: <426AAC93.9040808@mage.hu> superprad at gmail.com wrote: >I have a question on python lists. >Suppose I have a 2D list >list = [[10,11,12,13,14,78,79,80,81,300,301,308]] >how do I convert it so that I arrange them into bins . >so If i hvae a set of consecutive numbers i would like to represent >them as a range in the list with max and min val of the range alone. >I shd get something like >list = [[10,14],[78,81],[300,308]] > > > Maybe: list = [10,11,12,13,14,78,79,80,81,300,301,308] new_list = [] start = 0 for i in range(1,len(list) + 1): if i == len(list) or list[i] - list[i-1] <> 1: new_list.append([list[start],list[i-1]]) start = i print new_list From martin at v.loewis.de Mon Apr 11 17:51:01 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 11 Apr 2005 23:51:01 +0200 Subject: Thoughts on some stdlib modules In-Reply-To: References: <1113121254.874488.111250@f14g2000cwb.googlegroups.com> <42595E3D.7080301@v.loewis.de> Message-ID: <425AF145.8030400@v.loewis.de> Fredrik Lundh wrote: > I can help build an infrastructure that makes it easier to create a more > complete standard distribution, sure. (and since this isn't exactly a new > idea, I'm 100% confident that I don't have to do all the work myself.) > > if this is needed is something for the PSF to decide, I suppose. I can't get a clear picture what precisely would have to be done, and how you would imagine to transition from where we are now. However, my initial reaction would be that the PSF traditionally stays out of any kind of technical decision on the Python source code and distribution (*). It is to support the development of Python, not to control it. So my intuition is that perhaps you could just start. If you need to arrange something on python.org, you could well do so. If you want to change the way in which Python is released, you would have to convince the release manager (primarily) of doing things differently - if your plan involves changes to the way Python is released. So in the end, I think this sort of change will require some convincing, which, in turn, may require to fill paper of what the proposed changes are and how they could come about. Regards, Martin (*) Atleast formally. Informally, the opinion of the PSF members (not the formal vote of the directors) clearly does have impact on the future of Python - as many of the PSF members are also contributors to Python. From gtg856h at mail.gatech.edu Sat Apr 9 00:12:15 2005 From: gtg856h at mail.gatech.edu (Brian Kazian) Date: Sat, 9 Apr 2005 00:12:15 -0400 Subject: Python Equivalent to Java Interfaces? Message-ID: I want to insure that all subclasses implement a certain method, but could not find anything that would do this for me. Is there anyway in Python to implement this check? Thanks! From xah at xahlee.org Tue Apr 5 01:58:38 2005 From: xah at xahlee.org (Xah Lee) Date: 4 Apr 2005 22:58:38 -0700 Subject: EOL created by .write or .encode Message-ID: <1112680718.843606.126860@o13g2000cwo.googlegroups.com> Why is that some of my files written out by outF.write(outtext.encode('utf-8')) has ascii 10 as EOL, while others has ascii 13 as EOL? both of these files's EOL are originally all ascii 10. If i remove the EOL after the tt below in the place string, then this doesn't happen. findreplace = [ (ur'', ur'''tt '''), ] ... inF = open(filePath,'rb') s=unicode(inF.read(),'utf-8') inF.close() for couple in findreplace: outtext=s.replace(couple[0],couple[1]) s=outtext outF = open(tempName,'wb') outF.write(outtext.encode('utf-8')) outF.close() thanks. Xah xah at xahlee.org ? http://xahlee.org/PageTwo_dir/more.html ? From mauriceling at acm.org Thu Apr 28 22:37:51 2005 From: mauriceling at acm.org (Maurice LING) Date: Fri, 29 Apr 2005 12:37:51 +1000 Subject: New Python website References: <1114735502.510591.6360@f14g2000cwb.googlegroups.com> Message-ID: <42719DFF.5080504@acm.org> lpe wrote: > http://www.pycode.com > > I was kinda suprised when I could not find any good sites with 3rd > party modules (other than the Vaults of Parnassus, where you must host > files elsewhere), so I decided to write one myself :) > It is brand new and might still be buggy, but hopefully it will be > usefull to some people. Feel free to join and upload any of your code. > thanks > Hi, Just yesterday, I was frustrated waiting for replies from Catelog-SIG about the possibilities of a package management system that works like Fink (fink.sf.net). Basically, the problems I see is that C extension modules aren't portable across major Python revisions and there is no easy way to maintain the installed packages in site-packages directory. My scenario is that a system admin has to maintain 50 different libraries and their dependencies... So I've decided to write something myself... and call it 'centipyde'. Modelled against Fink and Darwinports (darwinports.opendarwin.org) (obviously I'm a Mac user), information (in text file) are in a folder (centipyde/pkginfo/) as .info files. Each package will have a .info file which tells the system (centipyde) where to download the source tar (or zip) and how to install the package, as well as the dependecies, maintaining the installed packages etc etc. No difference from other package managers (a goal)... It is still very rough at this moment, so please bear with me. Basically, the user will have to cvs checkout the system and just run it. I've checked it into Sourceforge, under IB-DWB project (which is abandoned) as 'centipyde'. But for some reason, I still can't view it in ViewCVS yet. Anyway, the directory layout is ../centipyde ../centipyde/centipyde.py ../centipyde/pgkinfo ../centipyde/pgkinfo/ply15.info ply15.info contains the following text (pretty much modelled against Fink): package=ply15 maintainer=. dependencies=. downloadurl=http://systems.cs.uchicago.edu/ply/ply-1.5.tar.gz prebuildscript=tar zxvf ply-1.5.tar.gz sourcedir=ply-1.5 buildscript=python setup.py build installscript=sudo python setup.py install centipyde.py is the following: ===================================================== """ Author: Maurice H.T. Ling Copyright (c) 2005 Maurice H.T. Ling Date created : 28th April 2005 """ PKGINFOPATH = 'pkginfo' INSTALL_LOG = 'install.log' import os import string import sys def install_package(package_name): f = open(os.getcwd() + os.sep + PKGINFOPATH + os.sep + package_name + '.info', 'r') install_info = {} for line in f.readlines(): line = string.split(line, '=') if line[1][-1] == os.linesep: install_info[line[0]] = string.strip(line[1][:-1]) else: install_info[line[0]] = string.strip(line[1]) f.close() print "Package Installation Information: " + str(install_info) os.system('curl -O ' + str(install_info['downloadurl'])) preinstall = [] preinstall = string.split(install_info['prebuildscript'], ';') for cmd in preinstall: os.system(cmd) cwd = os.getcwd() print cwd os.chdir(os.path.join(os.getcwd(), install_info['sourcedir'])) print os.getcwd() buildscript = [] buildscript = string.split(install_info['buildscript'], ';') for cmd in buildscript: os.system(cmd) installscript = [] installscript = string.split(install_info['installscript'], ';') for cmd in installscript: os.system(cmd) if sys.argv[1] == 'install': install_package(sys.argv[2]) ===================================================== When I run "python centipyde.py install ply15", PLY1.5 gets downloaded from David Beazley's website, uncompressed and installed into the site-package as shown here: znichols-maurice:~/MyProjects/ib-dwb/centipyde mauriceling$ ls -alltotal 8 drwxr-xr-x 5 mauricel mauricel 170 28 Apr 17:37 . drwxr-xr-x 10 mauricel mauricel 340 28 Apr 16:21 .. drwxr-xr-x 5 mauricel mauricel 170 28 Apr 17:33 CVS -rw-r--r-- 1 mauricel mauricel 1385 28 Apr 23:47 centipyde.py drwxr-xr-x 4 mauricel mauricel 136 28 Apr 17:36 pkginfo znichols-maurice:~/MyProjects/ib-dwb/centipyde mauriceling$ sudo python centipyde.py install ply15 Package Installation Information: {'maintainer': '.', 'sourcedir': 'ply-1.5', 'package': 'ply15', 'downloadurl': 'http://systems.cs.uchicago.edu/ply/ply-1.5.tar.gz', 'installscript': 'sudo python setup.py install', 'dependencies': '.', 'buildscript': 'python setup.py build', 'prebuildscript': 'tar zxvf ply-1.5.tar.gz'} % Total % Received % Xferd Average Speed Time Curr. Dload Upload Total Current Left Speed 100 69278 100 69278 0 0 7746 0 0:00:08 0:00:08 0:00:00 31811 ply-1.5/ ply-1.5/doc/ ply-1.5/doc/ply.html ply-1.5/CHANGES ply-1.5/COPYING ..... [snipped] ..... ply-1.5/test/yacc_uprec.exp ply-1.5/test/yacc_uprec.py /sw/lib/python2.3/distutils/dist.py:213: UserWarning: 'licence' distribution option is deprecated; use 'license' warnings.warn(msg) running build running build_py creating build creating build/lib copying lex.py -> build/lib copying yacc.py -> build/lib /sw/lib/python2.3/distutils/dist.py:213: UserWarning: 'licence' distribution option is deprecated; use 'license' warnings.warn(msg) running install running build running build_py running install_lib znichols-maurice:~/MyProjects/ib-dwb/centipyde mauriceling$ ================================ I think there are some obvious ways that we might work together... Cheers Maurice From nszabolcs at gmail.com Wed Apr 27 17:22:32 2005 From: nszabolcs at gmail.com (Szabolcs Nagy) Date: 27 Apr 2005 14:22:32 -0700 Subject: PyGTK vs. wxPython References: <1114444582.909431.245450@f14g2000cwb.googlegroups.com> <1114616192.342452.178720@o13g2000cwo.googlegroups.com> <1114626660.172481.303090@z14g2000cwz.googlegroups.com> Message-ID: <1114636952.944082.233220@f14g2000cwb.googlegroups.com> I forgot to mention in my previous post that the best thing in wxPython is the wxPython demo. It helped me a lot. Browsing through the examples usually faster than browsing through the api doc. About XRCed: I put every static components of the window layout in an xml file with XRCed (not static components: buttons moving around, changing labels ...) Generally my code looks like: import wx import wx.xrc class Frame(wx.Frame): def __init__(self, parent, resource): w = resource.LoadFrame(parent, 'FrameName') self.PostCreate(w) self.SetIcon(wx.Icon('myapp.ico', wx.BITMAP_TYPE_ICO)) ... #lots of init code here ... #event handlers here class App(wx.App): def OnInit(self): resource = wx.xrc.XmlResource('myapp.xrc') self.f = Frame(None, resource) self.f.Show() return True if __name__ == '__main__': app = App() app.MainLoop() From ville at spammers.com Fri Apr 1 07:55:58 2005 From: ville at spammers.com (Ville Vainio) Date: 01 Apr 2005 15:55:58 +0300 Subject: Case-insensitive dict, non-destructive, fast, anyone? References: Message-ID: >>>>> "Daniel" == Daniel Dittmar writes: Daniel> Ville Vainio wrote: >> I need a dict (well, it would be optimal anyway) class that >> stores the keys as strings without coercing the case to upper >> or lower, but still provides fast lookup (i.e. uses hash >> table). Daniel> Store the original key together with the value and use a Daniel> lowercase key for lookup. That's what I thought initially, but the strings take most of the space in dict and I didn't feel like doubling the size. It would be the "simplest thing that could possibly work", though. -- Ville Vainio http://tinyurl.com/2prnb From codecraig at gmail.com Mon Apr 18 16:09:26 2005 From: codecraig at gmail.com (codecraig) Date: 18 Apr 2005 13:09:26 -0700 Subject: Tkinter & Tkconstants Message-ID: <1113854966.648882.235040@l41g2000cwc.googlegroups.com> Hi, I was reading through the Tkinter tutorial at http://www.pythonware.com/library/tkinter/introduction/index.htm ...and it mentions that by doing, from Tkinter import * you have access to the constants in Tkconstants, since Tkinter imports it automatically. However, in the shell if I do.. from Tkinter import * print Tkinter.HORIZONTAL I get an error..NameError: Tkinter is not defined any ideas? However, if I do, import Tkconstants print Tkconstants.HORIZTONAL I get what i expect. but according to the tutorial i should only need Tkinter. Thanks. From grante at visi.com Fri Apr 8 00:04:00 2005 From: grante at visi.com (Grant Edwards) Date: Fri, 08 Apr 2005 04:04:00 -0000 Subject: Sockets References: <36qb5199613lai084brifj8judpoummv6n@4ax.com> Message-ID: <115c0lg17silfcd@corp.supernews.com> On 2005-04-08, Dan wrote: > On Thu, 7 Apr 2005 21:52:11 -0500, jepler at unpythonic.net wrote: > >>Python strings always carry their length, and can have embedded NULs. >> s.write("\0\1\2\3") >>should write 4 bytes to the socket 's'. > > I'm taking binary data from a database, so it's not really a Python > string. Is there an easy way to convert it? The struct module. -- Grant Edwards grante Yow! I want to read my new at poem about pork brains and visi.com outer space... From codecraig at gmail.com Fri Apr 15 13:03:05 2005 From: codecraig at gmail.com (codecraig) Date: 15 Apr 2005 10:03:05 -0700 Subject: py2exe - create one EXE In-Reply-To: <1113582492.351604.257570@z14g2000cwz.googlegroups.com> References: <1113579012.150708.118990@o13g2000cwo.googlegroups.com> <1113580317.027071.183640@z14g2000cwz.googlegroups.com> <1113582492.351604.257570@z14g2000cwz.googlegroups.com> Message-ID: <1113584585.082256.246110@z14g2000cwz.googlegroups.com> oh and Fredrik, i tried the SingleInstaller link....which points to a script using NSIS. I followed those instructions which generated an .exe. HOwever, when i run the .exe nothing happens (meaning no process starts, no output, no errors, nothing). any ideas on that? have ever used it? From jason.mobarak at gmail.com Tue Apr 26 23:24:25 2005 From: jason.mobarak at gmail.com (Jason Mobarak) Date: 26 Apr 2005 20:24:25 -0700 Subject: How remove directories with the content in the platform independent way? In-Reply-To: <7_adnZLgfvS1YPPfRVn-rg@comcast.com> References: <7_adnZPgfvQeYfPfRVn-rg@comcast.com> <7_adnZLgfvS1YPPfRVn-rg@comcast.com> Message-ID: <1114572265.625931.221840@l41g2000cwc.googlegroups.com> There's also the shutil module, which is platform independant. http://docs.python.org/lib/module-shutil.html ...see the rmtree function From jfj at freemail.gr Thu Apr 28 11:45:53 2005 From: jfj at freemail.gr (jfj) Date: Thu, 28 Apr 2005 18:45:53 +0300 Subject: Can .py be complied? In-Reply-To: <1114696910.862093.100690@z14g2000cwz.googlegroups.com> References: <426ec8f7_2@rain.i-cable.com> <1114696910.862093.100690@z14g2000cwz.googlegroups.com> Message-ID: <42710531.6060006@freemail.gr> beliavsky at aol.com wrote: > IMO the fact that so many people ask > > "How can I create executables in Python on Windows" > > indicates that standard "batteries included" Windows Python > distribution is missing a vital battery. There are tools such as > py2exe, but this functionality should be built-in, so that a newbie to > Python can just download it, type > > python -o foo.exe foo.py > > at the command line, and get an executable, without any further effort. > Since this is about windows and windows users just want everything in ".exe" form (no matter if it also contains spyware), and they don't care about the size of it (they just want the damn exe) and since there is zero chance that python will be included in the next windows distribution but these people still want the exe (they do, really), I think I have a convenient solution to give it to them. /* small program in C in self extracting archive */ if (have_application ("Python")) { have_python: system ("python.exe my_application.py") } else { printf ("This software requires python. Wait until all the necessary components are being installed\n"); download_python_from_python_org(); system ("install_python.exe"); goto have_python; } Seriously, people who want executables wouldn't notice the difference. jfj From nyamatongwe+gravity at gmail.com Wed Apr 6 17:16:03 2005 From: nyamatongwe+gravity at gmail.com (Neil Hodgson) Date: Wed, 06 Apr 2005 21:16:03 GMT Subject: I've broken PythonWin2.4 - Dialogs don't pop up! References: <1112815685.437815.285680@f14g2000cwb.googlegroups.com> Message-ID: Michael Murdock: > I have broken PythonWin and I don't know how or why. It worked great > until recently. I have installed / removed several apps since it worked > last. I could have a virus unknown to my antivirus program, I guess. > I'm stumped. You have tried rebooting? PythonWin can be upset by another non- responding application. A simple thing to try is to remove and reinstall in case you have modified one of the files in Pythonwin. Neil From roy at panix.com Fri Apr 22 13:22:09 2005 From: roy at panix.com (Roy Smith) Date: 22 Apr 2005 13:22:09 -0400 Subject: Why Python does *SLICING* the way it does?? References: <1113976729.450677.261130@o13g2000cwo.googlegroups.com> <3csdegF6p6jpnU1@individual.net> <3csphpF6es7iuU1@individual.net> Message-ID: In article <3csphpF6es7iuU1 at individual.net>, Reinhold Birkenfeld wrote: >Roy Smith wrote: > >>>Other possibility, probably faster when almost all keys in the range are in >>>the dictionary: >>> >>>class sdict(dict): >>> def __getitem__(self, index): >>> if isinstance(index, slice): >>> d = {} >>> for key in xrange(slice.start, slice.stop, slice.step): >>> if key in self: >>> d[key] = self[key] >>> return d >>> else: >>> return dict.__getitem__(self, index) >> >> The problem with that is it requires the keys to be integers. > >Yes, but wasn't it thought as a replacement for a list? Originally, yes. I went off on a tangent with string-keyed slices. From vze4rx4y at verizon.net Mon Apr 18 20:13:16 2005 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Tue, 19 Apr 2005 00:13:16 GMT Subject: Behaviour of str.split References: <4263cf31$0$26348$db0fefd9@news.zen.co.uk> <24a8619qhstqjrfi6vdit27bo8r4afd5nf@4ax.com> Message-ID: [Will McGugan] > >I'm curious about the behaviour of the str.split() when applied to empty > >strings. > > > >"".split() returns an empty list, however.. > > > >"".split("*") returns a list containing one empty string. [John Machin] > You are missing a perusal of the documentation. Had you done so, you > would have noticed that the actual behaviour that you mentioned is > completely the reverse of what is in the documentation! Nuts! I've got it from here and will get it fixed up. str.split() has to be one of the most frequently revised pieces of documentation. In this case, the two statements about splitting empty strings need to be swapped. Previously, all the changes occured because someone/somewhere would always find a way to misread whatever was there. In the absence of reading the docs, a person's intuition seems to lead them to guess that the behavior will be different than it actually is. Unfortunately, one person's intuition is often at odds with another's. Raymond Hettinger From evenprimes at gmail.com Thu Apr 14 08:16:05 2005 From: evenprimes at gmail.com (Chris Cioffi) Date: Thu, 14 Apr 2005 08:16:05 -0400 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Apr 11) In-Reply-To: <8c7f10c605041401491b7dd900@mail.gmail.com> References: <3c670tF6jdeqrU1@individual.net> <8c7f10c605041401491b7dd900@mail.gmail.com> Message-ID: +1 on _that_ being a QOTW! On 4/14/05, Simon Brunning wrote: [snip] > > Try and think of something else witty to say over the next day or two > - I'm sure I can squeeze you into next week's. ;-) -- "I was born not knowing and have had only a little time to change that here and there." -- Richard Feynman From mwh at python.net Tue Apr 5 05:42:18 2005 From: mwh at python.net (Michael Hudson) Date: Tue, 5 Apr 2005 09:42:18 GMT Subject: Simple thread-safe counter? References: <7x3bu9ss22.fsf_-_@ruckus.brouhaha.com> <7xy8c1hic8.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin writes: > Tim Peters writes: > > The GIL is your friend here: > > > > import itertools > > f = itertools.count().next > > Thanks, I was hoping something like this would work but was not sure I > could rely on it. > > > A similar thing can be done with xrange. But either way sucks if you > > call it often enough to exceed the size of a Python short int > > (platform C long). The obvious way with an explicit mutex doesn't > > have that problem. > > Xrange, of course :). I don't need to exceed the size of a short int, > so either of these should work fine. I wonder what measures the Pypy > implementers will take (if any) to make sure these things keep > working, but for now I won't worry about it. Well, for now we don't support threads. Easy! Cheers, mwh (no, really, this is for the future) -- Two things I learned for sure during a particularly intense acid trip in my own lost youth: (1) everything is a trivial special case of something else; and, (2) death is a bunch of blue spheres. -- Tim Peters, 1 May 1998 From franz.steinhaeusler at utanet.at Thu Apr 28 03:41:13 2005 From: franz.steinhaeusler at utanet.at (Franz Steinhaeusler) Date: Thu, 28 Apr 2005 09:41:13 +0200 Subject: Which IDE is recommended? References: <426f90ac$1_2@rain.i-cable.com> Message-ID: On Wed, 27 Apr 2005 10:17:13 -0400, Bill Mill wrote: >On 4/27/05, monkey wrote: >> Read through python site for programming tool, really plenty of choices :-) >> (For c++, I just can't breath with very very limited choices) >> >> Tried Spe, it come with wxGlade built-in very nice(is Spe still actively >> develop?). But seem that Boa Constructor and PyDev(the plug-in for Eclipse) >> also worth looking. Actually which one are you guys using? and why? I think >> it is also valuable for those who are new to python as me. >> > >Believe it or not, this has been discussed before :) But nevertheless interesting again and again :) -- Franz Steinh?usler http://drpython.sourceforge.net/ http://mitglied.lycos.de/drpython/ From littlejohn.75 at news.free.fr Fri Apr 1 17:01:25 2005 From: littlejohn.75 at news.free.fr (F. Petitjean) Date: 01 Apr 2005 22:01:25 GMT Subject: that is it is not it (logic in Python) References: <424d0be1$0$2882$626a14ce@news.free.fr> Message-ID: <424dc4b4$0$18707$636a15ce@news.free.fr> Le Fri, 1 Apr 2005 13:39:47 -0500, Terry Reedy a ?crit : > > "F. Petitjean" wrote in message > news:424d0be1$0$2882$626a14ce at news.free.fr... > >>>>> iterable = range(10) >>>>> it = iter(iterable) >>>>> that = iter(it) >>>>> that is it >> True # Good! >>>>> that is it is not it > > This is equivalent to '(that is it) and (it is not it)' which is clearly > false. > >> False # What ? > > Reread the ref manual on chained comparison operators. And see the date of the post :-) that is it isn't it ? > > Terry J. Reedy > > > From mauriceling at acm.org Thu Apr 7 21:10:24 2005 From: mauriceling at acm.org (Maurice LING) Date: Fri, 08 Apr 2005 11:10:24 +1000 Subject: text processing problem References: <1112915641.663333.175260@f14g2000cwb.googlegroups.com> <1112922056.365893.307550@f14g2000cwb.googlegroups.com> Message-ID: Matt wrote: > I'd HIGHLY suggest purchasing the excellent href="http://www.oreilly.com/catalog/regex2/index.html">Mastering > Regular Expressions by Jeff Friedl. Although it's mostly geared > towards Perl, it will answer all your questions about regular > expressions. If you're going to work with regexs, this is a must-have. > > That being said, here's what the new regular expression should be with > a bit of instruction (in the spirit of teaching someone to fish after > giving them a fish ;-) ) > > my_expr = re.compile(r'(\w+)\s*(\(\1\))') > > Note the "\s*", in place of the single space " ". The "\s" means "any > whitespace character (equivalent to [ \t\n\r\f\v]). The "*" following > it means "0 or more occurances". So this will now match: > > "there (there)" > "there (there)" > "there(there)" > "there (there)" > "there\t(there)" (tab) > "there\t\t\t\t\t\t\t\t\t\t\t\t(there)" > etc. > > Hope that's helpful. Pick up the book! > > M@ > Thanks again. I've read a number of tutorials on regular expressions but it's something that I hardly used in the past, so gone far too rusty. Before my post, I've tried my_expr = re.compile(r'(\w+) \s* (\(\1\))') instead but it doesn't work, so I'm a bit stumped...... Thanks again, Maurice From rune.strand at gmail.com Mon Apr 18 14:18:28 2005 From: rune.strand at gmail.com (runes) Date: 18 Apr 2005 11:18:28 -0700 Subject: Behaviour of str.split In-Reply-To: <1113847387.862751.61780@f14g2000cwb.googlegroups.com> References: <4263cf31$0$26348$db0fefd9@news.zen.co.uk> <1113838796.626344.309630@l41g2000cwc.googlegroups.com> <1113847387.862751.61780@f14g2000cwb.googlegroups.com> Message-ID: <1113848308.429271.147840@f14g2000cwb.googlegroups.com> [Tim N. van der Leeuw] > Fortunately, this is easy to write as: list("mystring"). Sure, and map(None, "mystring") Anyways, I have settled with this bevaviour, more or less ;-) Rune From johan at pulp.se Wed Apr 6 12:46:24 2005 From: johan at pulp.se (Johan Lindberg) Date: 6 Apr 2005 09:46:24 -0700 Subject: HTML editor component? References: <3a6b56F665r0lU1@individual.net> <3a6demF6aadf4U1@individual.net> Message-ID: <1112805984.613082.9460@l41g2000cwc.googlegroups.com> You could try the (very) simple HTML editor I use for my CM project. It can only handle B, I, U and A, but then again, it was never meant to do more. It's written in wxPython, based on Scintilla and can probably be extended to fit your needs. You can find it here: http://sourceforge.net/project/showfiles.php?group_id=72786&package_id=138707 BR /Johan Lindberg From sutram at gmail.com Fri Apr 15 16:01:15 2005 From: sutram at gmail.com (Mahesh) Date: 15 Apr 2005 13:01:15 -0700 Subject: Python 2.4.1 hang Message-ID: <1113595275.615168.189790@o13g2000cwo.googlegroups.com> Hi, This is on WinXP SP1. I needed to get to the POST body and while I was trying out various regular expressions, one of them caused Python to hang. The Python process was taking up 100% of the CPU. I couldn't even see the "Max recursion depth exceeded message". Is this a bug? Code below: import re s = \ """POST /TradeManagement-RT3/ReportController.Servlet HTTP/1.1 Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */* Referer: https://dummy.com/TradeManagement-RT3/PrelimReportSearch.jsp Accept-Language: en-us Content-Type: application/x-www-form-urlencoded Accept-Encoding: gzip, deflate User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR 1.0.3705) Host: dummy.com Content-Length: 267 Connection: Keep-Alive Cache-Control: no-cache Cookie: SMSESSION=RNwINGbjtRijIplKDE8EZ79NtSJREhKu4OogQqQD1PTukTIE3pclwfkkj2b5YSFscbW97A8QQxk1066rmtqwatlBQsnxr2h6fvAPiazYWex297WmDDjPd05RjXNhVqiPmhxSN9nOVP6Pq1igcFC5b3R4AFHWFcz+lW1QyUz+1yeaLfupKDkwaV7jP0qgPbccioWUpEmn762OyqCnehjuVBJ9hDBGO07Bx8Pv/tHd0l6xjFOt6YbtHG9IfMaKhrnPwmdtyo8c/4trmRNO84BoqwhtOzhrJTVuPjzYN2uxg04ZgAt+j75gSA9OPYYymirfwx5zBnhHvQz7ezGQqUPe45l3CvnRhkFVM/kOAYdY2Cdlv+15EMCVqJLT+2cMRCPPY+vlqlgsY30h5V9NWiG+AdXKQ8LEUnPEhnSYhyIo1a3FzB1yr+E/CZfXkNi1lMrG0HiwU+NJVK7rY0deee7gFeiq8T0660eq2WOVF7USMESTOAbSDsR6Ejo+rRscvHfX7uzvu1pRw0Phw7ffF0pr/nBhunq4v7/dW6WXOzvWAEocBXK9/Hl5Ua63X/UxXVs8g6psI0mqoRziFWw+O4t4jjn1fS2e1YvvtAGRPIcNeEEPSCgqEhSUKoGz1qysPoK87MgflIaHt/PsOeRCYSS/53B87RH9RrcaJEgrHyIBZNuzEjD1AG4Uud5oKi88902RW3IATHnH1E4UntvEdo/NbCcNbgN/dGWEvBnBzLn6KYxd4PxG0pQ3vr3qDDa7v0i9eXq9t6++tlM1tIS/XIHZc4bfGKPdZC30Dtw7HwUc7bl74/SHVEEcgzgXJPkCH2zSHaxyot3sqGHCwDa3AmuUkaPSC+iviVHlTe3Uk4KsOnnG94UIwB4yv+mlkXqnw0JwausWVuetCIm+cDIuvZXgRYghjZnNcNsji0k15ddr8j4=; CCTMRT3=O0PVLBMWBVD2115CLLS4REI EntrySourceDescription=All&SEARCHReportType=All&SEARCHReportStatus=All&available=IC&SEARCHReportCommodity=All&SortContract_Year=1&SortTrade_Price=&SortOrder_Type=&SortBuy_Sell_Ind=&SortAccount_Number=&SortExternal_TradeId=&GroupBy=contract&command=PrelimReportCommand""" #pattern_str = "^POST.*\\r\\n\\r((\\n)|(\\n[^\r]*))" #pattern_str = "^POST.*\\n((\\n)|(\\n[^\r]*&))" pattern_str = "^POST(.*\\n*)+\\n\\n" # <--- Offending pattern pattern = re.compile(pattern_str) match = pattern.match(s); if match: print match.groups() From gsakkis at rutgers.edu Sat Apr 9 14:35:43 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 9 Apr 2005 11:35:43 -0700 Subject: Puzzling OO design problem References: <1113003772.020556.69550@l41g2000cwc.googlegroups.com> <1113010854.638038.173460@g14g2000cwa.googlegroups.com> <1113018015.535852.53250@z14g2000cwz.googlegroups.com> <1113043759.765568.9920@o13g2000cwo.googlegroups.com> Message-ID: <1113071743.646134.218180@l41g2000cwc.googlegroups.com> > Have you considered a 'macro' solution composing source? If I were handling so > many versions, I would want a complete class definition for each version rather > than having to scan many sources for each implementation. Can you elaborate on this a little ? You mean something like a template-based code generating script that creates all the boilerplate code for each version before you start customising it ? This could be an option, though you'd better be pretty sure that the template is frozen; you don't want to go back and fill in the template more than once ! George From skip at pobox.com Mon Apr 11 16:35:07 2005 From: skip at pobox.com (Skip Montanaro) Date: Mon, 11 Apr 2005 15:35:07 -0500 Subject: smtplib does not send to all recipients In-Reply-To: <1113246181.843652.158520@o13g2000cwo.googlegroups.com> References: <1113244721.415164.81290@f14g2000cwb.googlegroups.com> <1113246181.843652.158520@o13g2000cwo.googlegroups.com> Message-ID: <16986.57211.324056.463303@montanaro.dyndns.org> dccarson> I changed debuglevel to 1 and looked at the response on the dccarson> recipient names. They are BOTH accepted, but still only my id dccarson> (d123456) receives the e-mail. The long id (d1234567890) dccarson> never gets the e-mail. Here is the excerpt of the exchange. ... dccarson> reply: '250 2.1.5 ... Recipient ok\r\n' ... dccarson> reply: '250 2.1.5 ... Recipient ok\r\n' Sorta makes it look like it's not an smtplib problem, doesn't it? ;-) Skip From lpe at pycode.com Thu Apr 28 20:45:02 2005 From: lpe at pycode.com (lpe) Date: 28 Apr 2005 17:45:02 -0700 Subject: New Python website Message-ID: <1114735502.510591.6360@f14g2000cwb.googlegroups.com> http://www.pycode.com I was kinda suprised when I could not find any good sites with 3rd party modules (other than the Vaults of Parnassus, where you must host files elsewhere), so I decided to write one myself :) It is brand new and might still be buggy, but hopefully it will be usefull to some people. Feel free to join and upload any of your code. thanks From vvikram at stanford.edu Fri Apr 1 02:16:19 2005 From: vvikram at stanford.edu (Vikram) Date: Thu, 31 Mar 2005 23:16:19 -0800 Subject: what's the use of __repr__?when shall I use it? In-Reply-To: References: Message-ID: __repr__ should return something that when eval'ed yields an identical object (if possible). essentially it should represent the programmer/debug view of the object. __str__ should mostly return a highly user-friendly string (note: str(obj) will use __repr__ if __str__ doesn't exist) you might also be interested in this thread covering the same topic: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/d10731049459726f/2a8f62f478057abd?q=python+__repr__+__str__+difference&rnum=6#2a8f62f478057abd thanks, Vikram From jason.w.kane at gmail.com Thu Apr 14 17:21:27 2005 From: jason.w.kane at gmail.com (Kane) Date: 14 Apr 2005 14:21:27 -0700 Subject: changing colors in python In-Reply-To: <1113511856.510914.103960@z14g2000cwz.googlegroups.com> References: <1113511856.510914.103960@z14g2000cwz.googlegroups.com> Message-ID: <1113513687.028969.316020@o13g2000cwo.googlegroups.com> To convert ansi escape sequences into text colors you need a terminal that understands what you are doing. Linux does this by default; dos and windows do not. You need to have an extra program in memory. The conventional approach is the "ANSI.SYS" driver which probably still ships with Windows (link below). I've included a link to nansi.com but haven't used it with any windows version > 3.1. If memory serves it is significantly faster. http://support.microsoft.com/default.aspx?scid=kb;en-us;Q101875 http://alumnus.caltech.edu/~dank/nansi/ From danb_83 at yahoo.com Thu Apr 21 02:59:06 2005 From: danb_83 at yahoo.com (Dan Bishop) Date: 20 Apr 2005 23:59:06 -0700 Subject: Why Python does *SLICING* the way it does?? References: <1113976729.450677.261130@o13g2000cwo.googlegroups.com> <_Lm9e.23143$Xm3.17864@trndny01> <1114003997.778676.144950@z14g2000cwz.googlegroups.com> Message-ID: <1114066746.568467.95730@z14g2000cwz.googlegroups.com> beliavsky at aol.com wrote: > What languages besides Python use the Python slicing convention? Java uses it for the "substring" method of strings. > In C starting at > 0 may be justified because of the connection between array subscripting > and pointer arithmetic, but Python is a higher-level language where > such considerations are less relevant. Maybe less relevant, but relevant nonetheless. First, there's the desire for familiarity. Many Python programmers are also C programmers, and that fact has had an influence on the development of the language. That's why we write "x += 0x20" rather than "x := x + $20". Why not array indexing as well? More importantly, there are reasons for counting from zero that have nothing to do with pointers. The biggest reason involves modular arithmetic: r=n%d satifies 0 <= r < d, which conveniently matches Python's array syntax. DAY_NAMES = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] def weekday_name(date): return DAY_NAMES[date.toordinal() % 7] Modular arithmetic's preference for 0-based counting goes beyond array indexing. For example, consider our notation for time, from 00:00:00 to 23:59:59. def time_add(time, delta): """ time = an (hour, minute, second) tuple for a time of day delta = an (hour, minute, second) tuple for an amount of time Returns time+delta, as an (hour, minute, second) tuple. """ hour = time[0] + delta[0] minute = time[1] + delta[1] second = time[2] + delta[2] # Normalize the time second = ((hour * 60) + minute) * 60 + second minute, second = divmod(second, 60) hour, minute = divmod(minute, 60) hour %= 24 return hour, minute, second Imagine that the time notation went from 01:01:01 to 24:60:60. Try writing a time_add function for that. The only simple way I can think of is to temporarily convert to zero-based notation! def time_add(time, delta): # Add like terms and convert to zero-based notation. hour = time[0] + delta[0] - 1 minute = time[1] + delta[1] - 1 second = time[2] + delta[2] - 1 # Normalize the time second = ((hour * 60) + minute) * 60 + second minute, second = divmod(second, 60) hour, minute = divmod(minute, 60) hour %= 24 # Convert back to one-based notation on output return hour + 1, minute + 1, second + 1 > Along the same lines, I think the REQUIREMENT that x[0] rather than > x[1] be the first element of list x is a mistake. At least the > programmer should have a choice, as in Fortran or VBA. If you really want 1-based arrays, just do what most BASIC programmers do: Ignore x[0]. >>> months = [None, "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] >>> print months[4] Apr From tim.golden at viacom-outdoor.co.uk Tue Apr 19 06:27:44 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Tue, 19 Apr 2005 11:27:44 +0100 Subject: Name/ID of removable Media: how? Message-ID: <9A28C052FF32734DACB0A288A3533991EBB78A@vogbs009.gb.vo.local> [Heiko Selber] | I am trying to find out (using Python under windows) the name | of a CD that | is currently in the drive specified by a path name. | | And while I am at it, I'd also like to know whether the | specified drive | contains a CD at all, and whether the drive is actually a CD drive. Try this: import wmi c = wmi.WMI () for i in c.Win32_CDROMDrive (): print i.Caption, i.VolumeName, i.VolumeSerialNumber I haven't answered all your questions, but I'm willing to bet that you can do pretty much what you want with WMI. There are also the pywin32 functions which give you some of this (maybe all, don't know; haven't tried). More info here: http://timgolden.me.uk/python/wmi.html and here: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wmisdk/wmi/win32_cdromdrive.asp and here: http://pywin32.sf.net TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From rschroev_nospam_ml at fastmail.fm Tue Apr 26 07:42:39 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Tue, 26 Apr 2005 11:42:39 GMT Subject: what is the best way to determine system OS? In-Reply-To: <86acnln8wi.fsf@guru.mired.org> References: <1114436211.942212.203790@f14g2000cwb.googlegroups.com> <868y37osc7.fsf@guru.mired.org> <86y8b6o8pw.fsf@guru.mired.org> <1114487173.272526.13670@o13g2000cwo.googlegroups.com> <86acnln8wi.fsf@guru.mired.org> Message-ID: Mike Meyer wrote: >>In that case, it seems to be a better idea to check the version of >>vmstat that's on the system. At least, I presume that such differences >>in behaviour can be deduced from the vmstat version string. > > > Hmm. That doesn't seem to work here: > > guru% vmstat --version > vmstat: illegal option -- - > usage: vmstat [-aimsz] [-c count] [-M core [-N system]] [-w wait] > [-n devs] [disks] The version on Debian Woody uses -V: $ vmstat -V procps version 2.0.7 Apparently it is quite a different program than yours; the -V option is cleary labeled in the man page, and it supports much less options: $ vmstat --help usage: vmstat [-V] [-n] [delay [count]] -V prints version. -n causes the headers not to be reprinted regularly. delay is the delay between updates in seconds. count is the number of updates. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From matt at mondoinfo.com Mon Apr 25 15:23:58 2005 From: matt at mondoinfo.com (Matthew Dixon Cowles) Date: Mon, 25 Apr 2005 14:23:58 -0500 Subject: Is this a bug? References: Message-ID: <426d43cd$0$613$804603d3@auth.newsreader.iphouse.com> On 2005-04-24 10:52:36 -0500, "Fredrik Lundh" said: > > mapping += to extend is a design mistake (I guess someone got a > little carried away). I agree. I think that + and += should be the same except for the target of the assignment. But I discussed that with the Timbot a little while ago and he disagrees. Regards, Matt From steven.bethard at gmail.com Wed Apr 13 11:34:30 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 13 Apr 2005 09:34:30 -0600 Subject: sort of a beginner question about globals In-Reply-To: <1113405724.301516.232000@f14g2000cwb.googlegroups.com> References: <1113354531.380490.81190@z14g2000cwz.googlegroups.com> <3aOdnX8D67t5PcHfRVn-qQ@comcast.com> <1113403451.556360.116630@f14g2000cwb.googlegroups.com> <1113405724.301516.232000@f14g2000cwb.googlegroups.com> Message-ID: <6v-dnV7CJ7WZocDfRVn-oA@comcast.com> fred.dixon wrote: > how would i use the following if OPTIONS was in a module ? > ----------------------- > from optparse import OptionParser > > usage = "usage: %prog [options] arg" > parser = OptionParser(usage) > > parser.add_option("-d", "--debug", ction="store_true", dest="verbose") > (OPTIONS = parser.parse_args() Just have this code update the options module: import options ... opts, args = parser.parse_args() options.__dict__.update(opts.__dict__) STeVe From adomas.paltanavicius at gmail.com Fri Apr 22 14:12:08 2005 From: adomas.paltanavicius at gmail.com (Adomas) Date: 22 Apr 2005 11:12:08 -0700 Subject: Python logos Message-ID: <1114193528.576352.162680@z14g2000cwz.googlegroups.com> Hi all, this question has nothing to do with Python syntax, or libraries, however... I'm looking for the so well-known python logo -- not the boring "Python Powered", but the image of small snake. However, the only such I could found was 32x32 or alike (windows icon size.) Does anybody know where could I find a better-resolution image, or yet better SVG/EPS? Thanks in advance, Adomas From fredrik at pythonware.com Tue Apr 12 13:57:40 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 12 Apr 2005 19:57:40 +0200 Subject: [perl-python] Python documentation moronicities (continued) References: <1113301533.054410.203710@z14g2000cwz.googlegroups.com> Message-ID: Peter Hansen wrote: > Joe Smith wrote: > > Xah Lee wrote: > >> of motherf***ing irrevalent drivel? > > > > I am greatly amused. > > A troll impersonating Xah Lee has made xah look like a total moron. > > LOL > > Sorry, Joe, but why do you think this wasn't Xah? why do you think "Joe" and "Xah" are two different persons? ;-) From prabapython at yahoo.co.in Thu Apr 7 07:38:52 2005 From: prabapython at yahoo.co.in (praba kar) Date: Thu, 7 Apr 2005 12:38:52 +0100 (BST) Subject: doubt regarding main function In-Reply-To: 6667 Message-ID: <20050407113852.51725.qmail@web8401.mail.in.yahoo.com> Dear All, I have doubt regarding main function in Python. In Python we can create a function and we can call a function directly. (eg:) def test(): print 'main function test' I can call this function the following way eg) test() So why we need the below way of calling a function? if __name__ == '__main__': test() What is the advantage of this way calling a function. Kindly mail me as early as possible regards, Prabahar ________________________________________________________________________ Yahoo! India Matrimony: Find your life partner online Go to: http://yahoo.shaadi.com/india-matrimony From jeremit0 at gmail.com Fri Apr 8 14:17:32 2005 From: jeremit0 at gmail.com (jeremit0) Date: Fri, 08 Apr 2005 14:17:32 -0400 Subject: Equivalent string.find method for a list of strings Message-ID: I have read a text file using the command lines = myfile.readlines() and now I want to seach those lines for a particular string. I was hoping there was a way to "find" that string in a similar way as searching simply a simple string. I want to do something like lines.find.('my particular string') Is there a module that already exists that allows me to do this or will I have to created my own method? Thanks, Jeremy From t.bettio at transnorm.ch Thu Apr 14 14:43:22 2005 From: t.bettio at transnorm.ch (Tiziano Bettio) Date: Thu, 14 Apr 2005 20:43:22 +0200 Subject: Supercomputer and encryption and compression @ rate of 96% In-Reply-To: <1113490437.037734.158740@g14g2000cwa.googlegroups.com> References: <1113470846.970773.4780@g14g2000cwa.googlegroups.com> <1113490437.037734.158740@g14g2000cwa.googlegroups.com> Message-ID: <425EB9CA.1010708@transnorm.ch> martijn at gamecreators.nl wrote: >And how do you get the data back ? > >1+0=0 == 0+0=0 >0+1=1 == 1+1=1 > >let's say you have the end key : 0 >then you want to decompress it , but in what ? 0 0 or 1 0 > >;) > > > hi there could someone please tell me that this thread wasn't a aprilsfoll day joke and it is for real... i'm pretty much able to go down to a single bit but what would be the reverse algorithm as stated by martin... :0 From eppstein at ics.uci.edu Tue Apr 5 22:18:10 2005 From: eppstein at ics.uci.edu (David Eppstein) Date: Tue, 05 Apr 2005 18:18:10 -0800 Subject: math - need divisors algorithm References: Message-ID: > > Does anyone have suggested code for a compact, efficient, elegant, most of > > all pythonic routine to produce a list of all the proper divisors of an > > integer (given a list of prime factors/powers) I have code for this in (look for the function called, surprisingly, "divisors"). It's not very compact -- 155 lines from the start of the Pollard Rho factorization (thanks to Kirby Urner) to the end of the divisors function, but it's reasonably efficient even for largish numbers. -- David Eppstein Computer Science Dept., Univ. of California, Irvine http://www.ics.uci.edu/~eppstein/ From rkern at ucsd.edu Mon Apr 11 16:21:30 2005 From: rkern at ucsd.edu (Robert Kern) Date: Mon, 11 Apr 2005 13:21:30 -0700 Subject: Thoughts on some stdlib modules In-Reply-To: <16986.43349.305695.807402@montanaro.dyndns.org> References: <425999BD.7050308@v.loewis.de> <200504102212.19392.hancock@anansispaceworks.com> <16986.43349.305695.807402@montanaro.dyndns.org> Message-ID: Skip Montanaro wrote: > >> I guess the other thing to compare to is something like SciPy, which > >> is a kind of specialized distribution of Python for scientific > >> applications. > > Robert> No, Scipy is just a (large) package. Enthon, on the other hand, > Robert> is just such a distribution. > > I'm sorry, you lost me there. What's the difference between a large package > and a distribution? Scipy is not a "distribution of Python." It's just a single package, a single library; you still need the interpreter. Enthon for Windows is a distribution of the Python interpreter and a number of packages. Currently, MacEnthon is just a collection of packages because I can rely on the presence of Python 2.3.0 on all OSX 10.3 machines. In the future, I will be releasing a version for 2.4.x and that will include the interpreter. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From ladasky at my-deja.com Fri Apr 22 21:35:57 2005 From: ladasky at my-deja.com (ladasky at my-deja.com) Date: 22 Apr 2005 18:35:57 -0700 Subject: Semi-newbie, rolling my own __deepcopy__ In-Reply-To: References: <1112629066.785241.275670@z14g2000cwz.googlegroups.com> <1114122554.228545.105700@g14g2000cwa.googlegroups.com> Message-ID: <1114220157.718697.133960@z14g2000cwz.googlegroups.com> Michael Spencer wrote: > ladasky at my-deja.com wrote: > > I'm back... > [wondering why copy.deepcopy barfs on array instances] > > > > http://www.python.org/doc/2.3.3/lib/module-copy.html > deepcopy: > ... > This version does not copy types like module, class, function, method, stack > trace, stack frame, file, socket, window, *array*, or any similar types. > ... *smacks forehead* Duh. Right in the docs. Too many late nights in front of the screeen. Thanks, Michael... -- Rainforest laid low. "Wake up and smell the ozone," Says man with chainsaw. John J. Ladasky Jr., Ph.D. From xah at xahlee.org Tue Apr 19 06:54:29 2005 From: xah at xahlee.org (Xah Lee) Date: 19 Apr 2005 03:54:29 -0700 Subject: New Python regex Doc (was: Python documentation moronicities) In-Reply-To: <1113856843.023012.165500@l41g2000cwc.googlegroups.com> References: <1113301533.054410.203710@z14g2000cwz.googlegroups.com> <1113856843.023012.165500@l41g2000cwc.googlegroups.com> Message-ID: <1113908069.264676.207090@g14g2000cwa.googlegroups.com> send your feedbacks to Steve Holden. (http://www.holdenweb.com/) If he deem it proper, he will paypal me $100 bucks, and you can thank him for the instigation and betterment of the Python doc. Meanwhile, feel free to incorporate my edits into python doc. Xah xah at xahlee.org ? http://xahlee.org/ Xah Lee wrote: > i have rewrote the Python's re module documentation. > See it here for table of content page: > http://xahlee.org/perl-python/python_re-write/lib/module-re.html > > The doc is broken into 4 sections: > * regex functions (node111.html) > * regex OOP (re-objects.html) > * matched objects (match-objects.html) > * regex syntax (re-syntax.html) > > the regex syntax page i haven't edited, except the introductory first > paragraph. The other pages are completely rewritten for about 80%. > > There are a couple fine points or 3 places in the original doc i can't > understand. They are noted as NOTE DOC WRITERS or NEED EXAMPLE HERE. > > Xah > xah at xahlee.org > ? http://xahlee.org/ From fred.dixon at gmail.com Thu Apr 14 08:26:47 2005 From: fred.dixon at gmail.com (fred.dixon) Date: 14 Apr 2005 05:26:47 -0700 Subject: sort of a beginner question about globals In-Reply-To: References: <1113354531.380490.81190@z14g2000cwz.googlegroups.com> <3aOdnX8D67t5PcHfRVn-qQ@comcast.com> <1113403451.556360.116630@f14g2000cwb.googlegroups.com> <1113405724.301516.232000@f14g2000cwb.googlegroups.com> <6v-dnV7CJ7WZocDfRVn-oA@comcast.com> <1113422470.180010.172970@z14g2000cwz.googlegroups.com> <1113434483.437663.206030@f14g2000cwb.googlegroups.com> Message-ID: <1113481607.615479.72920@g14g2000cwa.googlegroups.com> when i am roughing out my functions and classes i out a pass statement as my first line just as a place holder and a convenient place to put a break when i am testing. no other good reason. From discard at dawes.za.net Fri Apr 15 03:57:54 2005 From: discard at dawes.za.net (Rogan Dawes) Date: Fri, 15 Apr 2005 09:57:54 +0200 Subject: Web Application Client Module In-Reply-To: <1113340287.265724.137300@f14g2000cwb.googlegroups.com> References: <1113340287.265724.137300@f14g2000cwb.googlegroups.com> Message-ID: Raffi wrote: > Hi All, > > I hope I'm posting this question to the correct newsgroups. We have a > web based database application that's accessed using IE. The > application opens a popup window to run in. With all the popup blockers > and compromised browsers out there, I'm looking into developing a web > based custom client side application to access the application with. > The application will be developed to only reach the web application > site using the https protocol. It also needs to javascript enabled. It > will be downloaded from the main web site and used to access the > database application. > > Any suggestions/ideas on how to go about developing the client > application? What tools tools are out there for such a project. > > Thanks, > Raffi > Wouldn't it be easier simply to make it NOT open a pop-up window? Besides, most browsers usually allow you to whitelist a site, or allow a single pop-up per click . . . Rogan -- Rogan Dawes *ALL* messages to discard at dawes.za.net will be dropped, and added to my blacklist. Please respond to "nntp AT dawes DOT za DOT net" From gsakkis at rutgers.edu Mon Apr 25 22:45:30 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 25 Apr 2005 19:45:30 -0700 Subject: Quote-aware string splitting References: <9Kgbe.24031$h6.523@tornado.texas.rr.com> <87oec2e1qa.fsf@mrbun.watterson> <1114483065.551933.68460@f14g2000cwb.googlegroups.com> Message-ID: <1114483530.128707.297530@z14g2000cwz.googlegroups.com> > import re > regex = re.compile(r''' > '.*?' | # single quoted substring > ".*?" | # double quoted substring > \S+ # all the rest > ''', re.VERBOSE) Oh, and if your strings may span more than one line, replace re.VERBOSE with re.VERBOSE | re.DOTALL. George From mahs at telcopartners.com Mon Apr 18 16:28:21 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Mon, 18 Apr 2005 13:28:21 -0700 Subject: def a((b,c,d),e): In-Reply-To: <1113854757.229118.137260@g14g2000cwa.googlegroups.com> References: <1113854757.229118.137260@g14g2000cwa.googlegroups.com> Message-ID: AdSR wrote: > Fellow Pythonistas, > > Please check out > > http://spyced.blogspot.com/2005/04/how-well-do-you-know-python-part-3.html > > if you haven't done so yet. It appears that you can specify a function > explicitly to take n-tuples as arguments. It actually works, checked > this myself. If you read the reference manual at > http://docs.python.org/ref/function.html > really carefully, you will find that it is indeed part of the language > spec, but it's a likely candidate for the least advertised Python > feature. > See also the source of inspect.getargs for just how much this complicates the argument-passing logic! > Small wonder since it looks like one of those language > features that make committing atrocities an order of magnitude easier. > > Has anyone actually used it in real code? It appears in a handful of places in the stdlib, mostly tests: #Search C:\Python23\Lib # Files *.py # For def [\w]+\(\( c:\python23\lib\test\test_compile.py(49) def comp_args((a, b)): c:\python23\lib\test\test_compile.py(53) def comp_args((a, b)=(3, 4)): c:\python23\lib\test\test_grammar.py(159) def f5((compound, first), two): pass c:\python23\lib\test\test_scope.py(318) def makeAddPair((a, b)): c:\python23\lib\test\test_scope.py(319) def addPair((c, d)): c:\python23\lib\site-packages\wx-2.5.3-msw-ansi\wx\lib\imageutils.py(36) def makeGray((r,g,b), factor, maskColor): c:\python23\lib\cgitb.py(82) def html((etype, evalue, etb), context=5): c:\python23\lib\cgitb.py(168) def text((etype, evalue, etb), context=5): c:\python23\lib\urlparse.py(118) def urlunparse((scheme, netloc, url, params, query, fragment)): c:\python23\lib\urlparse.py(127) def urlunsplit((scheme, netloc, url, query, fragment)): > > Cheers, > > AdSR From reinhold-birkenfeld-nospam at wolke7.net Sun Apr 17 10:28:13 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Sun, 17 Apr 2005 16:28:13 +0200 Subject: unicode "em space" in regex In-Reply-To: <1113744266.026254.183300@o13g2000cwo.googlegroups.com> References: <1113652436.971442.311570@z14g2000cwz.googlegroups.com> <4261442D.1010800@v.loewis.de> <1113744266.026254.183300@o13g2000cwo.googlegroups.com> Message-ID: <3cf6gsF6lp5ilU1@individual.net> Xah Lee wrote: > "Regular expression pattern strings may not contain null bytes, but can > specify the null byte using the \number notation." > > What is meant by null bytes here? Unprintable chars?? and the "\number" > is meant to be decimal? and in what encoding? The null byte is a byte with the integer value 0. Difficult, isn't it. The \number notation is, as you could read in http://docs.python.org/ref/strings.html, octal. Reinhold From aleksander.helgaker at gmail.com Fri Apr 22 11:04:06 2005 From: aleksander.helgaker at gmail.com (aleksander.helgaker at gmail.com) Date: 22 Apr 2005 08:04:06 -0700 Subject: Overiding error message when using a python program In-Reply-To: References: <1114181140.609745.192580@g14g2000cwa.googlegroups.com> Message-ID: <1114182246.383968.146810@l41g2000cwc.googlegroups.com> Thanks, this works great. I edited def prompt_user() so that it now reads def prompt_user(): try: userinput = input(">") except NameError: print "Command not recognised" From mirnazim at gmail.com Wed Apr 27 03:39:52 2005 From: mirnazim at gmail.com (Mir Nazim) Date: 27 Apr 2005 00:39:52 -0700 Subject: (PHP or Python) Developing something like www.tribe.net In-Reply-To: <1114503432.227799.52670@o13g2000cwo.googlegroups.com> References: <1113835147.364885.304290@l41g2000cwc.googlegroups.com> <1114503432.227799.52670@o13g2000cwo.googlegroups.com> Message-ID: <1114587592.260950.181990@l41g2000cwc.googlegroups.com> Thanks fro ur advice. I was also thinking to look into quixote. but wanted a second opinion. thanks again. From dbasch at yahoo.com Fri Apr 8 18:21:01 2005 From: dbasch at yahoo.com (Derek Basch) Date: 8 Apr 2005 15:21:01 -0700 Subject: Counting iterations References: <1112994185.983954.234650@l41g2000cwc.googlegroups.com> <4256f4c0$0$2603$da0feed9@news.zen.co.uk> Message-ID: <1112998861.316958.152060@g14g2000cwa.googlegroups.com> ooops you are right. Should have been: pets = ["cat", "dog", "bird"] num_pets = 0 for i in pets: num_pets += 1 print "pet" + "#" + num_pets That's the problem with one offs. I don't read them :). From pdemb at gazeta.pl Tue Apr 19 13:01:37 2005 From: pdemb at gazeta.pl (Peter Dembinski) Date: Tue, 19 Apr 2005 19:01:37 +0200 Subject: Refactoring in Python. Message-ID: <8764yiog3y.fsf@hector.domek> I am trying to write Master Thesis on refactoring Python code. Where should I look for information? -- http://www.dembi?ski.prv.pl From codecraig at gmail.com Fri Apr 15 11:30:12 2005 From: codecraig at gmail.com (codecraig) Date: 15 Apr 2005 08:30:12 -0700 Subject: py2exe - create one EXE Message-ID: <1113579012.150708.118990@o13g2000cwo.googlegroups.com> Hi, Is there a way to create one .exe using py2exe (or some other extension/utility that can do it)? Basically i want to generate one .exe that contains everything my python app needs to run instead of having a .exe, some .zips, etc. thanks From leszczynscy at nospamyahoo.com Tue Apr 26 22:50:00 2005 From: leszczynscy at nospamyahoo.com (Andy Leszczynski) Date: Tue, 26 Apr 2005 21:50:00 -0500 Subject: How remove directories with the content in the platform independent way? In-Reply-To: <7_adnZPgfvQeYfPfRVn-rg@comcast.com> References: <7_adnZPgfvQeYfPfRVn-rg@comcast.com> Message-ID: <7_adnZLgfvS1YPPfRVn-rg@comcast.com> Andy Leszczynski wrote: > James Stroud wrote: > >> Look at the os and os.path modules. >> >> http://docs.python.org/lib/module-os.html >> http://docs.python.org/lib/module-os.path.html >> >> >> >> On Tuesday 26 April 2005 07:27 pm, so sayeth Andy Leszczynski: >> >>> How remove directories with the content in the platform independent way? >>> Is the API for that? >>> >>> Thx, A. >> >> >> > It is not clear if rmdir would remove the non-empty dir ... > never min, I found this in that doc :-) # Delete everything reachable from the directory named in 'top', # assuming there are no symbolic links. # CAUTION: This is dangerous! For example, if top == '/', it # could delete all your disk files. import os for root, dirs, files in os.walk(top, topdown=False): for name in files: os.remove(os.path.join(root, name)) for name in dirs: os.rmdir(os.path.join(root, name)) From skip at pobox.com Wed Apr 27 22:39:45 2005 From: skip at pobox.com (Skip Montanaro) Date: Wed, 27 Apr 2005 21:39:45 -0500 Subject: regex over files In-Reply-To: <426F5B62.3010801@chamonix.reportlab.co.uk> References: <426D0659.7080307@chamonix.reportlab.co.uk> <426D08BC.1040703@klix.ch> <426E021E.8000809@jessikat.fsnet.co.uk> <17006.31984.182979.430076@montanaro.dyndns.org> <426E893D.2070905@chamonix.reportlab.co.uk> <426EAA9D.2050904@jessikat.fsnet.co.uk> <426F5B62.3010801@chamonix.reportlab.co.uk> Message-ID: <17008.19697.939514.53469@montanaro.dyndns.org> Robin> I implemented a simple scanning algorithm in two ways. First buffered scan Robin> tscan0.py; second mmapped scan tscan1.py. ... Robin> C:\code\reportlab\demos\gadflypaper>\tmp\tscan0.py dingo.dat Robin> len=139583265 w=103 time=110.91 Robin> C:\code\reportlab\demos\gadflypaper>\tmp\tscan1.py dingo.dat Robin> len=139583265 w=103 time=140.53 I'm not sure why the mmap() solution is so much slower for you. Perhaps on some systems files opened for reading are mmap'd under the covers. I'm sure it's highly platform-dependent. (My results on MacOSX - see below - are somewhat better.) Let me return to your original problem though, doing regex operations on files. I modified your two scripts slightly: tscan0.py: import sys, time, re fn = sys.argv[1] f=open(fn,'rb') n=0 t0 = time.time() while 1: buf = f.read(4096) if not buf: break for i in re.split("XXXXX", buf): n += 1 t1 = time.time() print "n=%d time=%.2f" % (n, (t1-t0)) tscan1.py: import sys, time, mmap, os, re fn = sys.argv[1] fh=os.open(fn,os.O_RDONLY) s=mmap.mmap(fh,0,access=mmap.ACCESS_READ) t0 = time.time() n = 0 for mat in re.split("XXXXX", s): n += 1 t1 = time.time() print "n=%d time=%.2f" % (n, (t1-t0)) The mmap version is almost obviously correct, assuming what we want to do is split the file on "XXXXX". The buffered read version is almost certainly incorrect, given our understanding that corner cases lurk at buffer boundaries. I took the file from Bengt Richter's example and replicated it a bunch of times to get a 122MB file. I then ran the above two programs against it: % python tscan1.py splitX n=2112001 time=8.88 % python tscan0.py splitX n=2139845 time=10.26 So the mmap'd version is within 15% of the performance of the buffered read version and we don't have to solve the problem of any corner cases (note the different values of n). I'm happy to take the extra runtime in exchange for simpler code. Skip From raoul.daruwala at gmail.com Tue Apr 26 14:51:36 2005 From: raoul.daruwala at gmail.com (raoul) Date: 26 Apr 2005 11:51:36 -0700 Subject: Fast plotting? In-Reply-To: References: Message-ID: <1114541496.010129.280700@z14g2000cwz.googlegroups.com> I like Ploticus. It's a bit kludgy for integration, you need to send the data to a file and have ploticus read it, but this can be easily done using memory mapped files. It's a very fast package and it produces very nice plots. SVG plots too. We use an svg viewer and then reload the svg tree to rerender the plot. From Scott.Daniels at Acm.Org Wed Apr 20 11:26:13 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 20 Apr 2005 08:26:13 -0700 Subject: Array of Chars to String In-Reply-To: <4265a3c8.14451179@news.oz.net> References: <42658990.7739398@news.oz.net> <4265a3c8.14451179@news.oz.net> Message-ID: <42666ee2$1@nntp0.pdx.net> Bengt Richter wrote: > ... BTW, since str has .translate, why not .maketrans? Probably because, while I can imagine u'whatever'.translate using a 256-wide table (and raising exceptions for other the rest), I have more problems imagining the size of the table for a UCS-4 unicode setup (32 bits per character). I suppose it could be done, but a na?ve program might be in for a big shock about memory consumption. --Scott David Daniels Scott.Daniels at Acm.Org From m at m.com Fri Apr 29 03:51:33 2005 From: m at m.com (monkey) Date: Fri, 29 Apr 2005 15:51:33 +0800 Subject: why "import wx" doesn't work? References: <427126ca$1_3@rain.i-cable.com> <42715a8b$1_1@rain.i-cable.com> Message-ID: <4271e783$1_2@rain.i-cable.com> Bright ( ; You show me a crystal clear explaination. As a newbie in python and even oop, I find the python documentation is not easy to figure out. That's great with you guys so nice here. > This is very good! wxApp is never defined if you use "import wx". You > must use "wx.wxApp" instead. > > If you import a module using "import anything", then all the names > imported from the module must begin with "anything.". If you import wx > using "import wx", then ALL the wx commands, classes and variables > (all the names) MUST begin with 'wx.". Change them, and your program > will work. > > "from wx import *" is a special shortcut, allowing you to use all the > names without "wx.". If you change "from something import *" to > "import something", your code will always break, this is normal. > > regards, > Filip Dreger > > From simon.brunning at gmail.com Fri Apr 22 10:56:33 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Fri, 22 Apr 2005 15:56:33 +0100 Subject: Overiding error message when using a python program In-Reply-To: <1114181140.609745.192580@g14g2000cwa.googlegroups.com> References: <1114181140.609745.192580@g14g2000cwa.googlegroups.com> Message-ID: <8c7f10c6050422075620c5e59b@mail.gmail.com> On 22 Apr 2005 07:45:40 -0700, aleksander.helgaker at gmail.com > I'm creating this program for my own use but naturally sometimes I > would make spelling mistakes (being a dyslexic and all) and so having a > long error message and having the program quit is more then a bit > irritating. It would be much more preferable if the program simply > wrote "Command not recognised" and then kept going. Is this possible? It certainly is. "NameError" is what's called an exception, and you can catch those. Try something like (untested): try: print 10 / pi except NameError: print "Command not recognised" I can't see where you'd want that in your code, 'cos I can't see where you are actually processing the user's input. For more on exceptions, see . -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From tim.golden at viacom-outdoor.co.uk Fri Apr 15 10:06:57 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Fri, 15 Apr 2005 15:06:57 +0100 Subject: Get OS name Message-ID: <9A28C052FF32734DACB0A288A3533991EBB777@vogbs009.gb.vo.local> [rbt] | | codecraig wrote: | > How can I get the OS Name, such as "Windows XP Pro". I | know I can do | > | > sys.getwindowsversion but that doesnt return a nice Windows XP Pro | > string. | > | > and os.name gives "nt" | > | > thanks. | > | | Read the docs... sys.getwindowsversion() should do the trick. AFAIK, | there is no way to differentiate between XP Home and Pro... I'm no expert on this (I don't even use XP) but the WMI Win32_OperatingSystem class seems to give a useful string here: import wmi c = wmi.WMI () for os in c.Win32_OperatingSystem (): print os.Caption gives "Microsoft Windows XP Professional" and "Microsoft Windows 2000 Professional" on a couple of machines I tried. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From jstroud at mbi.ucla.edu Fri Apr 15 01:03:17 2005 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 14 Apr 2005 22:03:17 -0700 Subject: question about functions In-Reply-To: <1113540288.415656.325750@l41g2000cwc.googlegroups.com> References: <1113540288.415656.325750@l41g2000cwc.googlegroups.com> Message-ID: <200504142203.17408.jstroud@mbi.ucla.edu> Oops, I messed up the indices on the previous post. Also, maybe you are thinking a bit more perlish: # start of ascript def my_funk(*alist): print "the first argument: %s" % alist[0] print "the second argument: %s" % alist[1] my_funk('wuzzup,','g?') # end of ascript On Thursday 14 April 2005 09:44 pm, chris patton wrote: > Hi everyone. > > I have a question about passing arguments to python functions. Is there > any way to make this job act like Perl? > > sub my_funk { > > print "the first argument: $_[0]\n"; > print "the second argument: $_[1]\n"; } > > In other words, can I call the arguments from a list? -- James Stroud, Ph.D. UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From simon.brunning at gmail.com Wed Apr 20 08:39:51 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Wed, 20 Apr 2005 13:39:51 +0100 Subject: building a small calculator In-Reply-To: <1114000275.227950.50870@f14g2000cwb.googlegroups.com> References: <1113999497.480245.47240@g14g2000cwa.googlegroups.com> <1114000275.227950.50870@f14g2000cwb.googlegroups.com> Message-ID: <8c7f10c605042005393c9d0219@mail.gmail.com> On 20 Apr 2005 05:31:15 -0700, aleksander.helgaker at gmail.com wrote: > I get the following error message when using the command sys.exit(). > > name 'sys' is not defined. You really are new at this, aren't you? ;-) You need to import the sys module before you use it. Put this at the top of your script: import sys I'd also suggest that you have a run through the tutorial - . It's time well spent. If you don't get on with that, there's another couple of tutorials available aimed directly at those new to programming - and . Lastly, although neophytes are more than welcome here, you might find the tutor mailing list a good place to ask questions in the early days of your Python experience. You'll find it here - . -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From Scott.Daniels at Acm.Org Tue Apr 12 14:12:03 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 12 Apr 2005 11:12:03 -0700 Subject: problem with the logic of read files In-Reply-To: <68da8$425bf954$43461874$29054@nf1.news-service.com> References: <68da8$425bf954$43461874$29054@nf1.news-service.com> Message-ID: <425c09f8$1@nntp0.pdx.net> m_tach at yahoo.com wrote: > #!/cbi/prg/python/current/bin/python > # -*- coding: iso-8859-1 -*- > import sys > import os > from progadn import * > ... > for x in extseq: > f = open(x, "r") > seq=f.read() > f.close() > s=seq > > def checkDNA(seq): > ... > > seq=checkDNA(seq) > print seq You terminated the loop to define checkDNA. What you want is: ... from progadn import * def checkDNA(seq): ... ... for x in extseq: f = open(x, "r") seq=f.read() f.close() s=seq seq = checkDNA(seq) print seq Even better might be: ... from progadn import * def checkDNA(seq): ... def main(): ... for x in extseq: f = open(x, "r") try: print checkDNA(f.read()) finally: f.close() if __name__ = '__main__': main() --Scott David Daniels Scott.Daniels at Acm.Org From lbates at syscononline.com Wed Apr 27 17:09:47 2005 From: lbates at syscononline.com (Larry Bates) Date: Wed, 27 Apr 2005 16:09:47 -0500 Subject: interactive web graphics In-Reply-To: References: Message-ID: Web application are different than local or client server applications. Web browser can connect to a server and make a request, but the program that satisfies the request runs to completion and disconnects from the client. You cannot easily do interactive-type applications. Things like progress bars can't really even be done. You can have your applications create graphs, charts, etc. and deliver them back to the user either as web pages or as PDF files. There is a python toolkit called ReportLab that provides a framework to do this from python programs that run on the server. The ReportLab graphics can do barcharts, line charts, scatter plots, etc. and you can either save as .JPG files that can be delivered on a web page or as a .PDF file that the user can download. Hard to say which would work best for you. Hope information helps a little. -Larry Bates Eckhoff, Michael A wrote: > Hello, > > I failed to locate a list for pygtk, so I thought I'd > ask my question here. Is it possible to write CGI > scripts that bring up a GUI (as in GTK+, QT, Tk, ...) > or an openGL display that is windowed inside a web > browser? > > The answer would seem to me to be no, since the > client could be Windows or Linux. I'd like to > display some pretty graphics (scientific visualisation), > but web applications are not my background. > > I would like a form with progress bars, but I guess > that would have to be implemented in some special way. > Sorry if these questions are ill-posed; I am just > getting my feet wet with python. > > Thanks, > Michael E > > PS Congratulations for having such wonderful documentation > on all things python. From reinhold-birkenfeld-nospam at wolke7.net Sun Apr 24 10:36:50 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Sun, 24 Apr 2005 16:36:50 +0200 Subject: postgresql modules and performance In-Reply-To: References: Message-ID: <3d1pbpF6rmccaU1@individual.net> Mage wrote: > Hello, > > I started to write my PostgreSQL layer. I tried pyPgSQL and PyGreSQL. I > made a *very minimal* performance test and comparsion with the same > thing in php. Table "movie" has 129 record and many fields. > > I found PyGreSQL / DB-API / fetchall horrible slow (32 sec in my test). > PHP did 13 secs and it gave the result in associative array. Maybe I did > something bad. Have you tried psycopg? Reinhold From mahs at telcopartners.com Sun Apr 3 18:07:13 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Sun, 03 Apr 2005 15:07:13 -0700 Subject: Help me dig my way out of nested scoping In-Reply-To: <1112562768.181026.180140@l41g2000cwc.googlegroups.com> References: <1112562768.181026.180140@l41g2000cwc.googlegroups.com> Message-ID: Brendan wrote: > Hi everyone > > I'm new to Python, so forgive me if the solution to my question should > have been obvious. ... Good question. For a thorough explanation see: http://www.python.org/dev/doc/devel/ref/naming.html Simple version follows: > > OK, here's my problem: How do I best store and change lastX, A(lastX) > and B(lastX) in FW's scope? This seems like it should be easy, but I'm > stuck. Any help would be appreciated! Assignments (i.e., binding names to objects) are always made in the local scope (unless you've used the 'global' declaration, which I don't think can help you here). So, for an even simpler demonstration of the problem see: > >>> def outer(): ... b = 1 ... def inner(): ... b += 1 ... print b ... inner() ... >>> outer() Traceback (most recent call last): File "", line 1, in ? File "", line 6, in outer File "", line 4, in inner UnboundLocalError: local variable 'b' referenced before assignment The solution is not to re-bind the identifier from the enclosing scope, but rather to mutate the object that it references. This requires a mutable object, such as a list: >>> def outer(): ... b = [1] # bind b to a mutable object ... def inner(): ... b[0] += 1 ... print b[0] ... inner() ... >>> outer() 2 >>> HTH Michael From roy at panix.com Sun Apr 3 08:37:01 2005 From: roy at panix.com (Roy Smith) Date: Sun, 03 Apr 2005 08:37:01 -0400 Subject: unittest vs py.test? References: <114pqf31isr8k4d@news.supernews.com> <1112372685.034751.99410@o13g2000cwo.googlegroups.com> <1I2dnUmAu5ZPSdDfRVn-rA@powergate.ca> <%Fl3e.1804$7b.990@trndny01> <_4-dnaRR8dv8dNDfRVn-tg@powergate.ca> <6I-dnbpiIZJNJNPfRVn-hA@powergate.ca> <6oQ3e.10378$db.6219@trndny07> <7x3bu8t7or.fsf@ruckus.brouhaha.com> Message-ID: In article <7x3bu8t7or.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > "Raymond Hettinger" writes: > > When writing a large suite, you quick come to appreciate being able > > to use assert statements with regular comparision operators, debugging > > with normal print statements, and not writing self.assertEqual over and > > over again. The generative tests are especially nice. > > But assert statements vanish when you turn on the optimizer. If > you're going to run your application with the optimizer turned on, I > certainly hope you run your regression tests with the optimizer on. That's an interesting thought. In something like C++, I would never think of shipping anything other than the exact binary I had tested ("test what you ship, ship what you test"). It's relatively common for turning on optimization to break something in mysterious ways in C or C++. This is both because many compilers have buggy optimizers, and because many programmers are sloppy about depending on uninitialized values. But, with something like Python (i.e. high-level interpreter), I've always assumed that turning optimization on or off would be a much safer operation. It never would have occurred to me that I would need to test with optimization turned on and off. Is my faith in optimization misguided? Of course, all of the Python I write is for internal use; I haven't yet been able to convince an employer that we should be shipping Python to customers. From klaus at seistrup.dk Mon Apr 18 13:24:05 2005 From: klaus at seistrup.dk (Klaus Alexander Seistrup) Date: Mon, 18 Apr 2005 17:24:05 +0000 (UTC) Subject: Removing dictionary-keys not in a set? References: <1113824946.525441.285760@l41g2000cwc.googlegroups.com> Message-ID: Tim N. van der Leeuw wrote: > I'd like to remove keys from a dictionary, which are not found > in a specific set. So it's kind of an intersection-operation. How about #v+ klaus at home:~ $ python Python 2.4.1 (#2, Mar 30 2005, 21:51:10) [GCC 3.3.5 (Debian 1:3.3.5-8ubuntu2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> d1 = {1:'a', 2:'b', 3:'c', 4:'d', 5:'e'} >>> s1 = set(d1) >>> s1 set([1, 2, 3, 4, 5]) >>> s2 = set([1, 3, 5]) >>> s1-s2 set([2, 4]) >>> for k in s1-s2: ... del d1[k] ... >>> d1 {1: 'a', 3: 'c', 5: 'e'} >>> ^D klaus at home:~ $ #v- -- Klaus Alexander Seistrup Magnetic Ink, Copenhagen, Denmark http://magnetic-ink.dk/ From walter at livinglogic.de Mon Apr 25 10:08:43 2005 From: walter at livinglogic.de (=?ISO-8859-1?Q?Walter_D=F6rwald?=) Date: Mon, 25 Apr 2005 16:08:43 +0200 Subject: HTML cleaner? In-Reply-To: References: Message-ID: <426CF9EB.5060008@livinglogic.de> Ivan Voras wrote: > M.-A. Lemburg wrote: > >> Not true: mxTidy integrates tidy as C lib. It's not an interface >> to the command line tool. > > Thanks, I'll look at it again! Another option might be the HTML parser (libxml2.htmlReadMemory()) from libxml2 (http://www.xmlsoft.org) Bye, Walter D?rwald From grante at visi.com Fri Apr 22 15:07:16 2005 From: grante at visi.com (Grant Edwards) Date: Fri, 22 Apr 2005 19:07:16 -0000 Subject: gui developing References: Message-ID: <116iir4hq8muc62@corp.supernews.com> On 2005-04-22, Mage wrote: > I am flirting with the idea of developing a gui app in python > as a newbie. Which module should I use? I have noticed that > wxpython is already installed on my gentoo and the examples on > their wiki looks easy. Is it okay or should I use wax or > something else? If you need portability, then wxPython is hard to beat. wxPython is a bit complex -- it took me a while to grasp the concept of separate trees/hierarchies for widget layout and for widget ownership. Though there are a few situations where it could be useful (I've never run across any of them in my apps), the whole ID scheme seems pretty clunky. Wax unifies the two trees so it's simpler to learn (it's more like Tk). Sizers in wxPython feel a log like hbox/vbox layout from TeX, so I like that. The Gtk port of Python is pretty decent as well, but portability to Windows and Mac isn't as good. I've never tried Qt. -- Grant Edwards grante Yow! Will the third world at war keep "Bosom Buddies" visi.com off the air? From max2 at fisso.casa Sat Apr 2 11:05:10 2005 From: max2 at fisso.casa (max(01)*) Date: Sat, 02 Apr 2005 16:05:10 GMT Subject: instance name In-Reply-To: <5jz3e.504252$w62.286883@bgtnsc05-news.ops.worldnet.att.net> References: <99z3e.1157607$35.42889387@news4.tin.it> <5jz3e.504252$w62.286883@bgtnsc05-news.ops.worldnet.att.net> Message-ID: Andrew Koenig wrote: > "max(01)*" wrote in message > news:99z3e.1157607$35.42889387 at news4.tin.it... > > >>is there a way to define a class method which prints the instance name? > > > The term "the instance name" is misleading, because it assumes, without > saying so explicitly, that every instance has a unique name. > > In fact, there is no reason that an instance needs to have a name at all, or > that it should have only one. > > You gave this example: > > instance_1 = class_1() > instance_1.myName() > > but what if I did this instead? > > class_1().myName() > > Or this? > > instance_1 = class_1() > instance_2 = instance_1 > instance_2.myName() > > excellent points. i'll get back with proper questions afterwards. thanks macs From michele.simionato at gmail.com Wed Apr 27 03:44:06 2005 From: michele.simionato at gmail.com (Michele Simionato) Date: 27 Apr 2005 00:44:06 -0700 Subject: (PHP or Python) Developing something like www.tribe.net In-Reply-To: <1114587592.260950.181990@l41g2000cwc.googlegroups.com> References: <1113835147.364885.304290@l41g2000cwc.googlegroups.com> <1114503432.227799.52670@o13g2000cwo.googlegroups.com> <1114587592.260950.181990@l41g2000cwc.googlegroups.com> Message-ID: <1114587846.011299.125420@g14g2000cwa.googlegroups.com> I would also look at CherryPy, the new 2.0 version seems pretty interesting (I have not tried it, but I have seen a short presentation at the ACCU conference, and it looks really trivial to use). From bill.mill at gmail.com Wed Apr 13 09:16:37 2005 From: bill.mill at gmail.com (Bill Mill) Date: Wed, 13 Apr 2005 09:16:37 -0400 Subject: preallocate list In-Reply-To: <797fe3d40504130611dbf2ffe@mail.gmail.com> References: <797fe3d40504130611dbf2ffe@mail.gmail.com> Message-ID: <797fe3d4050413061618086ba@mail.gmail.com> Just a correction: > I would profile your app to see that it's your append which is taking > ages, but to preallocate a list of strings would look like: > > ["This is an average length string" for i in range(approx_length)] > > My guess is that it won't help to preallocate, but time it and let us > know. A test to back my guess: > > import timeit, math > > def test1(): > lst = [0 for i in range(100000)] > for i in xrange(100000): > lst[i] = math.sin(i) * i > > def test2(): > lst = [] > for i in xrange(100000): > lst.append(math.sin(i) * i) > > t1 = timeit.Timer('test1()', 'from __main__ import test1') > t2 = timeit.Timer('test2()', 'from __main__ import test2') > print "time1: %f" % t1.timeit(100) > print "time2: %f" % t2.timeit(100) > The results change slightly when I actually insert an integer, instead of a float, with lst[i] = i and lst.append(i): 09:14 AM ~$ python test.py time1: 3.352000 time2: 3.672000 The preallocated list is slightly faster in most of my tests, but I still don't think it'll bring a large performance benefit with it unless you're making a truly huge list. I need to wake up before pressing "send". Peace Bill Mill From sm.synonymous at gmail.com Fri Apr 22 03:56:46 2005 From: sm.synonymous at gmail.com (Synonymous) Date: 22 Apr 2005 00:56:46 -0700 Subject: Pattern Matching Given # of Characters and no String Input; use RegularExpressions? References: Message-ID: Hello! I was trying to create a program to search for the largest common subsetstring among filenames in a directory, them move the filenames to the substring's name. I have succeeded, with help, in doing so and here is the code. Thanks for your help! --- Code --- #This program was created with feed back from: smeghead and sirup plus aum of I2P; and also tiissa and John Machin of comp.lang.python #Thank you very much. #I still get the odd error in this, but it was 1 out of 2500 files successfully sorted. Make sure you have a directory under c:/test/ called 'aa' and have your #I release this code into the public domain :o), send feed back to sm.synonymous at gmail.com files in c:/test/ import pickle import os import shutil os.chdir ( '/test') aaaa=2 aa='aa' x=0 y=20 while y <> 2: print y List = [] for fileName in os.listdir ( '/test/' ): Directory = fileName List.append(Directory) List.append("A111111111111") List.sort() List.append("Z111111111111") ListLength = len(List) - 1 x = 0 while x < ListLength: ListLength = len(List) - 1 b = List[x] c = List[x + 1] backward1 = List[x - 1] d = b[:y] e = c[:y] backward2 = backward1[:y] f = str(d) g = str(e) backward3 = str(backward2) if f==g: if os.path.isdir (aa+"/"+f) == True: shutil.move(b,aa+"/"+f) else: os.mkdir(aa+"/"+f) #os.mkdir(f) shutil.move(b,aa+"/"+f) else: if f==backward3: if os.path.isdir (aa+"/"+f) == True: shutil.move(b,aa+"/"+f) else: os.mkdir(aa+"/"+f) #os.mkdir(f) shutil.move(b,aa+"/"+f) else: aaaa=3 x = x + 1 y = y - 1 --- End Code --- sm.synonymous at gmail.com (Synonymous) wrote in message news:... > Hello, > > Can regular expressions compare file names to one another. It seems RE > can only compare with input i give it, while I want it to compare > amongst itself and give me matches if the first x characters are > similiar. > > For example: > > cccat > cccap > cccan > dddfa > dddfg > dddfz > > Would result in the 'ddd' and the 'ccc' being grouped together if I > specified it to look for a match of the first 3 characters. > > What I am trying to do is build a script that will automatically > create directories based on duplicates like this starting with say 10 > characters, and going down to 1. This way "Vacation1.jpg, > Vacation2.jpg" would be sent to its own directory (if i specifiy the > first 8 characters being similiar) and "Cat1.jpg, Cat2.jpg" would > (with 3) as well. > > Thanks for your help and interest! > > S M From bvande at po-box.mcgill.ca Fri Apr 22 03:25:32 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Fri, 22 Apr 2005 03:25:32 -0400 Subject: time.strftime in 2.4.1 claims data out of range when not In-Reply-To: <0001HW.BE8DEB89000A10E8F02845B0@news.verizon.net> References: <0001HW.BE8DEB89000A10E8F02845B0@news.verizon.net> Message-ID: <4268A6EC.2020108@po-box.mcgill.ca> Sheila King said unto the world upon 2005-04-22 02:45: > I have a web app that has been running just fine for several months under > Python 2.2.2. > > We are preparing to upgrade the server to run Python 2.4.1. > > However, part of my web app is throwing an error on this code (that has > previously worked without exception): > > >>>>time.strftime("%Y-%m-%d", (Y, M, D, 0,0,0,0,0,0)) > > Traceback (most recent call last): > File "", line 1, in ? > ValueError: day of year out of range > >>>>Y > > 2005 > >>>>M > > 5 > >>>>D > > 15L > > > I don't see what parts of the date that I have submitted to strftime are out > of range? > > Also, the phrasing of the error message is a bit odd? > "day of year out of range" > > I'm not sure what the > day of a year > > would be??? > > Sheila King > http://www.thinkspot.net/sheila/ > > The day of the year is the ordinal number of the day, counting from Jan. 1st. So, Feb. 1st is the 32nd day, Dec 31 the 365/6 (depending on leap year). The docs for the time module indicate that the 8th (counting from 1) position of a struct_time is the day of the year, and that it can range from 1-366. So, naturally, the 0 value in your 8th position is the problem. That does leave the mystery of why your code worked on 2.2.2; I've no idea. The docs do seem to indicate that there were a number of changes at 2.2, though. Best, Brian vdB From RonGrossi382685 at yahoo.com Tue Apr 19 11:41:23 2005 From: RonGrossi382685 at yahoo.com (RonGrossi382685 at yahoo.com) Date: 19 Apr 2005 08:41:23 -0700 Subject: Do You Want To Know For Sure That You Are Going To Heaven? The reason some people don't know for sure if they are going to Heaven when they die is because they just don't know. The good news is that you can know for sure that you are going to Heaven which is described in the Holy Bible as a beautiful place with no death, sorrow, sickness or pain. (newsgroup-post 142) Message-ID: <1113925283.115755.202120@f14g2000cwb.googlegroups.com> The reason some people don't know for sure if they are going to Heaven when they die is because they just don't know. The good news is that you can know for sure that you are going to Heaven which is described in the Holy Bible as a beautiful place with no death, sorrow, sickness or pain. God tells us in the Holy Bible how simple it is to be saved so that we can live forever with Him in Heaven. "For if you confess with your mouth Jesus is Lord and believe in your heart that God raised Him from the dead, you WILL BE SAVED." (Romans 10:9) Over 2000 years ago God came from Heaven to earth in the person of Jesus Christ to shed His blood and die on a cross to pay our sin debt in full. Jesus Christ was born in Israel supernaturally to a virgin Jewish woman named Mary and lived a sinless life for thirty-three years. At the age of thirty-three Jesus was scourged and had a crown of thorns pressed onto His head then Jesus was crucified. Three days after Jesus died on a cross and was placed in a grave Jesus rose from the dead as Jesus said would happen before Jesus died. If someone tells you that they are going to die and in three days come back to life again and it happens then this person must be the real deal. Jesus Christ is the only person that ever lived a perfect sinless life. This is why Jesus is able to cover our sins(misdeeds) with His own blood because Jesus is sinless. The Holy Bible says, "In Him(Jesus) we have redemption through His blood, the forgiveness of sins..." (Ephesians 1:7) If you would like God to forgive you of your past, present and future sins just ask Jesus Christ to be your Lord and Saviour. It doesn't matter how old you are or how many bad things that you have done in your life including lying and stealing all the way up to murder. Just pray the prayer below with your mouth and mean it from your heart and God will hear you and save you. Dear Jesus Christ, I want to be saved so that I can have a home in Heaven with You when I die. I agree with You that I am a sinner. I believe that You love me and want to save me. I believe that You bled and died on the cross to pay the penalty for my sins and that You rose from the dead. Please forgive my sins and come into my heart and be my Lord and Saviour. Thanks Lord Jesus Christ for forgiving me and saving me through Your merciful grace. Amen. Welcome to the family of God if you just allowed God to save you. Now you are a real Christian and you can know for sure that you will live in Heaven forever when this life comes to an end. As a child of God we are to avoid sin(wrongdoing), but if you do sin the Holy Bible says, "My dear children, I write this to you so that you will not sin. But if anybody does sin, we have one who speaks to the Father in our defense Jesus Christ, the Righteous One." Those of you that have not yet decided to place your trust in the Lord Jesus Christ may never get another chance to do so because you do not know when you will die. Jesus said "I am the way, the truth and the life: no one can come to the Father(God)(in Heaven), but by me." (John 14:6) This means that if you die without trusting in Jesus Christ as your Lord and Saviour you will be forever separated from the love of God in a place called Hell. The Holy Bible descibes Hell as a place of eternal torment, suffering, pain and agony for all those who have rejected Jesus Christ. The good news is that you can avoid Hell by allowing Jesus Christ to save you today. Only then will you have true peace in your life knowing that no matter what happens you are on your way to Heaven. Praise the Lord! Servant of the Lord Jesus Christ Ronald L. Grossi *Show this to your family and friends so they can know that they have a choice where they will spend eternity. Thanks! ____________________________________________________ Got Questions? http://www.gotquestions.org/archive.html Other Languages http://www.godssimpleplan.org/gsps.html Free Movie: To Hell and Back http://www.tbn.org/index.php/8/1.html Animation http://www.browser.to/jesus-animation The Passion Of The Christ http://www.thepassionofthechrist.com Beware Of Cults http://www.carm.org/cults/cultlist.htm About Hell http://www.equip.org/free/DH198.htm Is Jesus God? http://www.powertochange.com/questions/qna2.html Free Online Bible http://www.biblegateway.com ____________________________________________________ From fredrik at pythonware.com Tue Apr 12 02:28:21 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 12 Apr 2005 08:28:21 +0200 Subject: Module for handling Nested Tables in HTML References: Message-ID: Gurpreet Sachdeva wrote: > Can anyone suggest some good tool for handling nested > tables in a HTML page... BeautifulSoup is somehow not working with > Nested Tables. sounds strange. have you tested the latest release? (2.0) http://www.crummy.com/software/BeautifulSoup/ if you cannot get BS to work, and the author cannot help you, you might consider using an HTML->XML converter, and using your favourite XML tool to pull apart the result. some alternatives: http://utidylib.berlios.de/ http://effbot.org/zone/element-tidylib.htm From jeremy+plusnews at jeremysanders.net Mon Apr 18 06:10:58 2005 From: jeremy+plusnews at jeremysanders.net (Jeremy Sanders) Date: Mon, 18 Apr 2005 11:10:58 +0100 Subject: ANN: Veusz 0.5 - a scientific plotting package References: <1113810917.134164.113060@g14g2000cwa.googlegroups.com> Message-ID: On Mon, 18 Apr 2005 00:55:17 -0700, hemanth wrote: > Why not matplotlib? Of late, it has seemed to have picked up a lot of > attention. I would prefer that the different plotting packages developers > join hands and implement missing features into a single plotting package > and make this a part of Python standard library. In contrast to the > various web frameworks we now have in Python, it is preferable to have > atleast one plotting package as a standard Python package. I made a reply on this subject to the SciPy mailing list: http://www.scipy.org/mailinglists/mailman?fn=scipy-user/2005-April/004312.html Basically my main issue was the baroque object structure that matplotlib used (it may have got better then), and its speed (which has). The difficulty of writing a plotting package is the user interface, and so I don't think I'm wasting much effort by having my own plotting routines. I've done 90% of what's needed there. Basically, I'll be happy when contouring and images are added. The advantage of Veusz is the nice object-based system of building up a plot. I have a version of veusz which used matplotlib as a backend, but I abandoned that several months ago. Jeremy From enleverlesO.OmcO at OmclaveauO.com Thu Apr 14 15:34:56 2005 From: enleverlesO.OmcO at OmclaveauO.com (Do Re Mi chel La Si Do) Date: Thu, 14 Apr 2005 21:34:56 +0200 Subject: Using python from a browser References: Message-ID: <425eedec$0$3101$8fcfb975@news.wanadoo.fr> Hi ! I confirm for IE. Others, I don't know. @-salutations Michel Claveau From radam2 at tampabay.rr.com Sun Apr 3 09:23:28 2005 From: radam2 at tampabay.rr.com (Ron_Adam) Date: Sun, 03 Apr 2005 13:23:28 GMT Subject: Decorater inside a function? Is there a way? References: <1112466233.403989.125810@l41g2000cwc.googlegroups.com> <1112516432.638697.193840@o13g2000cwo.googlegroups.com> Message-ID: <2erv41d8ilujl0vmformr26vm0tvhf689o@4ax.com> On 3 Apr 2005 00:20:32 -0800, "George Sakkis" wrote: >Yes, it is possible to turn off type checking at runtime; just add this >in the beginning of your define: > >def define(func): > if not ENABLE_TYPECHECKING: > return lambda func: func > # else decorate func > >where ENABLE_TYPECHECKING is a module level variable that can be >exposed to the module's clients. In my module, the default is >ENABLE_TYPECHECKING = __debug__. > > >George Cool, I'll try that. Thanks, Ron From barbaros at ptmat.fc.ul.pt Mon Apr 4 14:31:11 2005 From: barbaros at ptmat.fc.ul.pt (barbaros) Date: 4 Apr 2005 11:31:11 -0700 Subject: dynamic partial mirror, apt-get fails Message-ID: <1112639471.508763.113780@f14g2000cwb.googlegroups.com> Hi everybody, I am trying to implement a cgi script for mirroring a small part of a large collection of files (the debian distribution). The idea is to mirror only those files which are requested, by downloading them "on the fly" when the clients request them. Requests in the form "wget http://local.mirror.pt/~debian/cgi-bin/get.cgi?pool/main/a/abcde/abcde.deb" work fine already. The script get.cgi verifies if the file exists. If it exists, the script simply sends a "Location: ..." directive to its standart output and exists. If the file does not exist, the script downloads it from one of several predefined locations, and after the downloading process has succeeded it sends a "Location: ..." directive to its standard output and exits. This is more or less what apt-proxy (and other proxies) do, except that my script is independent of the directory structure (it should work for any collection of files, not only for the debian distribution) and it can be run by an ordinary user (you don't have to be root in order to install it). Now, the problem is that the debian package manager (dselect or apt-get) does not work exactly like wget. Requests in the form "apt-get http://..." fail with the strange message "302 Found". I looked a little bit into the source of both wget and apt-get and it seems to me that wget has code which deals specifically with the "Location: ..." directive, while apt-get has not. The questions are: Is my conclusion above correct ? Are future versions of apt-get going to accept "Location: ..." directives ? Should I try and modify the source of apt-get in order to teach it to handle these directives ? You can find all the details about my problem at my web page: http://cmaf.ptmat.fc.ul.pt/~barbaros -> english -> computers and programming -> deb_part_mirr Thank you. Cristian Barbarosie -- PLEASE NOTE: comp.infosystems.www.authoring.cgi is a SELF-MODERATED newsgroup. aa.net and boutell.com are NOT the originators of the articles and are NOT responsible for their content. HOW TO POST to comp.infosystems.www.authoring.cgi: http://www.thinkspot.net/ciwac/howtopost.html From cpghost at cordula.ws Wed Apr 13 11:32:22 2005 From: cpghost at cordula.ws (Cordula's Web) Date: 13 Apr 2005 08:32:22 -0700 Subject: for line in file weirdness References: <1113388411.589754.82600@f14g2000cwb.googlegroups.com> Message-ID: <1113406342.700962.51800@l41g2000cwc.googlegroups.com> A read-ahead buffer? Yes, that would explain it. Sorry, I missed this piece of information in the documentation. Thanks to all who replied. From mefjr75 at hotmail.com Wed Apr 27 14:02:55 2005 From: mefjr75 at hotmail.com (M.E.Farmer) Date: 27 Apr 2005 11:02:55 -0700 Subject: names of methods, exported functions In-Reply-To: <1114619877.485916.232570@l41g2000cwc.googlegroups.com> References: <1114592521.726967.320810@o13g2000cwo.googlegroups.com> <426f9552.44993106@news.oz.net> <1114619877.485916.232570@l41g2000cwc.googlegroups.com> Message-ID: <1114622385.802866.265100@o13g2000cwo.googlegroups.com> Appears that most of the relevant code is in the Helper and TextDoc classes of pydoc also might need the doc() function. My head hurts every time I stare at the internals of pydoc ;) I guess it is time for a lunch break. M.E.Farmer From jerf at jerf.org Fri Apr 1 16:46:14 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Fri, 01 Apr 2005 16:46:14 -0500 Subject: Decorater inside a function? Is there a way? References: Message-ID: On Fri, 01 Apr 2005 19:56:55 +0000, Ron_Adam wrote: > On Fri, 01 Apr 2005 13:47:06 -0500, Jeremy Bowers > wrote: >>Is this an April Fools gag? If so, it's not a very good one as it's quite >>in line with the sort of question I've seen many times before. "I have >>a hammer, how do I use it to inflate my tire?" > > Not an April fools gag, I'm just new to decorators and google brings > up lots of discussions from the past on how they may be implemented in > the future, but not much in actually how they work or how to use them. OK, just checking :-) A decorator is completely equivalent in principle to def function(): pass function = decorator(function) That's a simplified form; decorators can themselves be an expression which returns a callable that can be applied to a function and the rule for applying several in sequence work as you'd expect (pipelining earlier results into later ones, making for a great Obfuscated Python entry or two based on the "function name misdirection" trick), but this simplified form captures the essense, which is what I think you're looking for. In particular, it's just "syntax sugar", not a "special feature". > I'm trying to understand the use's, limits, and possibilities of > decorators. > > It just occurred to me that wrapping the contents of a function vs > wrapping the function it's self, could be useful. Decorators, literally, can only wrap functions. You can write a wrapper then that does something to the arguments, which people sometimes do, but you can't directly "wrap" the arguments. Note, having shown you how decorators work, you can "manually" apply the decorator yourself: Python 2.3.5 (#1, Mar 3 2005, 17:32:12) [GCC 3.4.3 (Gentoo Linux 3.4.3, ssp-3.4.3-0, pie-8.7.6.6)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import string >>> string._join = string.join >>> def joinWrap(*args, **kwargs): ... print args, kwargs ... return "My Wrapper", string._join(*args, **kwargs) ... >>> string.join = joinWrap >>> string.join(["1","2","3"], "|") My Wrapper (['1', '2', '3'], '|') {} '1|2|3' >>> So, whatever it is you are trying can do can still be done without the decorator syntax, and *this* is not unheard of, though managing the references correctly can be tricky the first few times if you're not used to it. (Note the replaced function (join in this example) can go anywhere the wrapper can get at it, I just stick it back in the original module for simplicity.) It's not the first thing I reach for, in fact in all my testing code I don't think I ever do this, but it is in the toolbox. Do this instead of abusing the decorator syntax; you could write a decorator that tries to figure out if it's being run in a testing environment and conditionally affects the function, but that's probably a bad idea. Feeling-like-I-owed-you-an-answer-after-the-april-fool-accusation-ly yrs, Jeremy Bowers :-) From grante at visi.com Sun Apr 24 11:38:29 2005 From: grante at visi.com (Grant Edwards) Date: Sun, 24 Apr 2005 15:38:29 -0000 Subject: Is this a bug? References: <426bb3e9$0$83084$ed2619ec@ptn-nntp-reader01.plus.net> Message-ID: <116nfblc10i9340@corp.supernews.com> On 2005-04-24, Michael Sparks wrote: >>>> a=["hello"] >>>> a = a + "world" > Traceback (most recent call last): > File "", line 1, in ? > TypeError: can only concatenate list (not "str") to list > However if we do this just slightly differently: > >>>> a = ["hello"] >>>> a += "world" >>>> a > ['hello', 'w', 'o', 'r', 'l', 'd'] > > We get completely different behaviour. This strikes me as a bug - should I > log it as one, or is there a good reason for this behaviour? I think it's a bug regardless of the reason for the behavior: 1) It doesn't do what a reasonable user expects. 2) It doesn't do what the documentation says it will. According to the language reference, An augmented assignment expression like x += 1 can be rewritten as x = x + 1 to achieve a similar, but not exactly equal effect. In the augmented version, x is only evaluated once. I don't consider the two results you posted "similar". -- Grant Edwards grante Yow! TAILFINS!!...click... at visi.com From gmuller at worldonline.nl Thu Apr 21 14:44:25 2005 From: gmuller at worldonline.nl (Gerrit Muller) Date: Thu, 21 Apr 2005 20:44:25 +0200 Subject: python-dev Summary for 2005-04-01 through 2005-04-15 In-Reply-To: <1114042877.208529.146820@g14g2000cwa.googlegroups.com> References: <1114042877.208529.146820@g14g2000cwa.googlegroups.com> Message-ID: <4267f48d$0$44097$5fc3050@dreader2.news.tiscali.nl> Tim Lesher wrote: > --------------------------- > New python-dev summary team > --------------------------- > > This summary marks the first by the team of Steve Bethard, Tim Lesher, > and Tony Meyer. We're trying a collaborative approach to the > summaries: each fortnight, we'll be getting together in a virtual > smoke-filled back room to divide up the interesting threads. Then > we'll stitch together the summaries in roughly the same form as you've > seen in the past. We'll mark each editor's entries with his initials. > +1 This first summary is a good start! Thanks. > Thanks to Brett Cannon for sixty-one excellent python-dev summaries. > Also, thanks for providing scripts to help get the new summaries off > the ground! We're looking forward to the contributions you'll make to > the Python core, now that the summaries aren't taking up all your > time. +1 Brett, thanks a lot! regards, Gerrit -- Praktijk voor Psychosociale therapie Lia Charit? http://www.liacharite.nl/ From sabbey at u.washington.edu Sun Apr 17 18:02:12 2005 From: sabbey at u.washington.edu (Brian Sabbey) Date: Sun, 17 Apr 2005 15:02:12 -0700 Subject: pre-PEP: Simple Thunks In-Reply-To: <7og3615g159tgksejbo15oo8jcit3ugec2@4ax.com> References: <3jl2615c5pckknicc32ccv2cktue3nh603@4ax.com> <7og3615g159tgksejbo15oo8jcit3ugec2@4ax.com> Message-ID: Ron_Adam wrote: > On Sat, 16 Apr 2005 17:25:00 -0700, Brian Sabbey >> Yes, much of what thunks do can also be done by passing a function >> argument. But thunks are different because they share the surrounding >> function's namespace (which inner functions do not), and because they can >> be defined in a more readable way. > > Generally my reason for using a function is to group and separate code > from the current name space. I don't see that as a drawback. I agree that one almost always wants separate namespaces when defining a function, but the same is not true when considering only callback functions. Thunks are a type of anonymous callback functions, and so a separate namespace usually isn't required or desired. > Are thunks a way to group and reuse expressions in the current scope? > If so, why even use arguments? Wouldn't it be easier to just declare > what I need right before calling the group? Maybe just informally > declare the calling procedure in a comment. > > def thunkit: # no argument list defines a local group. > # set thunk,x and y before calling. > before() > result = thunk(x,y) > after() > > def foo(x,y): > x, y = y, x > return x,y > > thunk = foo > x,y = 1,2 > do thunkit > print result > > -> (2,1) > > Since everything is in local name space, you really don't need to > pass arguments or return values. I'm kicking myself for the first example I gave in my original post in this thread because, looking at it again, I see now that it really gives the wrong impression about what I want thunks to be in python. The 'thunkit' function above shouldn't be in the same namespace as the thunk. It is supposed to be a re-usable function, for example, to acquire and release a resource. On the other hand, the 'foo' function is supposed to be in the namespace of the surrounding code; it's not re-usable. So your example above is pretty much the opposite of what I was trying to get across. > > The 'do' keyword says to evaluate the group. Sort of like eval() or > exec would, but in a much more controlled way. And the group as a > whole can be passed around by not using the 'do'. But then it starts > to look and act like a class with limits on it. But maybe a good > replacement for lambas? > > I sort of wonder if this is one of those things that looks like it > could be useful at first, but it turns out that using functions and > class's in the proper way, is also the best way. (?) I don't think so. My pickled_file example below can't be done as cleanly with a class. If I were to want to ensure the closing of the pickled file, the required try/finally could not be encapsulated in a class or function. > >> You're right that, in this case, it would be better to just write >> "f(stuff, 27, 28)". That example was just an attempt at describing the >> syntax and semantics rather than to provide any sort of motivation. If >> the thunk contained anything more than a call to 'stuff', though, it would >> not be as easy as passing 'stuff' to 'f'. For example, >> >> do f(27, 28): >> print stuff() >> >> would require one to define and pass a callback function to 'f'. To me, >> 'do' should be used in any situation in which a callback *could* be used, >> but rarely is because doing so would be awkward. Probably the simplest >> real-world example is opening and closing a file. Rarely will you see >> code like this: >> >> def with_file(callback, filename): >> f = open(filename) >> callback(f) >> f.close() >> >> def print_file(file): >> print file.read() >> >> with_file(print_file, 'file.txt') >> >> For obvious reasons, it usually appears like this: >> >> f = open('file.txt') >> print f.read() >> f.close() >> >> Normally, though, one wants to do a lot more than just print the file. >> There may be many lines between 'open' and 'close'. In this case, it is >> easy to introduce a bug, such as returning before calling 'close', or >> re-binding 'f' to a different file (the former bug is avoidable by using >> 'try'/'finally', but the latter is not). It would be nice to be able to >> avoid these types of bugs by abstracting open/close. Thunks allow you to >> make this abstraction in a way that is more concise and more readable than >> the callback example given above: > > How would abstracting open/close help reduce bugs? I gave two examples of bugs that one can encounter when using open/close. Personally, I have run into the first one at least once. > I'm really used to using function calls, so anything that does things > differently tend to be less readable to me. But this is my own > preference. What is most readable to people tends to be what they use > most. IMHO > >> do f in with_file('file.txt'): >> print f.read() >> >> Thunks are also more useful than callbacks in many cases since they allow >> variables to be rebound: >> >> t = "no file read yet" >> do f in with_file('file.txt'): >> t = f.read() >> >> Using a callback to do the above example is, in my opinion, more >> difficult: >> >> def with_file(callback, filename): >> f = open(filename) >> t = callback(f) >> f.close() >> return t >> >> def my_read(f): >> return f.read() >> >> t = with_file(my_read, 'file.txt') > > Wouldn't your with_file thunk def look pretty much the same as the > callback? It would look exactly the same. You would be able to use the same 'with_file' function in both situations. > I wouldn't use either of these examples. To me the open/read/close > example you gave as the normal case would work fine, with some basic > error checking of course. But worrying about the error checking is what one wants to avoid. Even if it is trivial to remember to close a file, it's annoying to have to think about this every time one wants to use a file. It would be nice to be able to worry about closing the file exactly once. It's also annoying to have to use try/finally over and over again as one would in many real-life situations. It would be nice to be able to think about the try/finally code once and put it in a re-usable function. The open/close file is just the simplest example. Instead of a file, it maybe be a database or something more complex. > Since Python's return statement can handle > multiple values, it's no problem to put everything in a single > function and return both the status with an error code if any, and the > result. I would keep the open, read/write, and close statements in > the same function and not split them up. What about try/finally? What if it is more complex than just opening and closing a file? The example that got me annoyed enough to write this pre-PEP is pickling and unpickling. I want to unpickle a file, modify it, and immediately pickle it again. This is a pretty easy thing to do, but if you're doing it over and over again, there gets to be a lot of boilerplate. One can of course create a class to handle the boilerplate, but instantiating a class is still more complicated than it has to be. Here is an example of using thunks to do this: def pickled_file(thunk, name): f = open(name, 'r') l = pickle.load(f) f.close() thunk(l) f = open(name, 'w') pickle.dump(l, f) f.close() Now I can re-use pickled_file whenever I have to modify a pickled file: do data in pickled_file('pickled.txt'): data.append('more data') data.append('even more data') In my opinion, that is easier and faster to write, more readable, and less bug-prone than any non-thunk alternative. >>> When I see 'do', it reminds me of 'do loops'. That is 'Do' involves >>> some sort of flow control. I gather you mean it as do items in a >>> list, but with the capability to substitute the named function. Is >>> this correct? >> >> I used 'do' because that's what ruby uses for something similar. >> > > I could see using do as an inverse 'for' operator. Where 'do' would > give values to items in a list, verses taking them from a list. I'm > not exactly sure how that would work. Maybe... > > def fa(a,b): > return a+b > def fb(c,d): > return c*b > def fc(e,f): > return e**f > > fgroup: > fa(a,b) > fb(c,d) > fc(e,f) > > results = do 2,3 in flist > > print results > -> (5, 6, 8) > > But this is something else, and not what your thunk is trying to do. > > > > So it looks to me you have two basic concepts here. > > (1.) Grouping code in local name space. > > I can see where this could be useful. It would be cool if the group > inherited the name space it was called with. > > (2.) A way to pass values to items in the group. > > Since you are using local space, that would be assignment statements > in place of arguments. > > Would this work ok for what you want to do? > > def with_file: # no argument list, local group. > f = open(filename) > t = callback(f) > f.close > > def my_read(f): > return f.read() > > callback = my_read > filename = 'filename' > do with_file This wouldn't work since with_file wouldn't be re-usable. It also doesn't get rid of the awkwardness of defining a callback. -Brian From antonyliu2002 at yahoo.com Wed Apr 20 00:11:46 2005 From: antonyliu2002 at yahoo.com (Anthony Liu) Date: Tue, 19 Apr 2005 21:11:46 -0700 (PDT) Subject: Importing some functions from a py file In-Reply-To: 6667 Message-ID: <20050420041147.94358.qmail@web54502.mail.yahoo.com> O, sorry, I did have main() at the very end of code1.py. Sorry for this confusion. --- John Machin wrote: > On Tue, 19 Apr 2005 20:17:06 -0700 (PDT), Anthony > Liu > wrote: > > >The choice is (b): > > > >(b) you do have "def main()" as per my example, but > >you have an unguarded "main()" at the top level > > > >Below is exactly what I have: > > > >def func1(): > > do_sth_1() > > > >def func2(): > > do_sth_2() > > > >def main(): > > do sth_m() > >#end of code1.py > > > If that's what you have, then main() won't be > executed *EVER*, neither > when code1 is imported, nor when it is run as a > script. > > > > >So, you suggest that if I add to the end of > code1.py > >module the following, > > > >if __name__ == "__main__": > > main() > > > >I should be OK, right? > > > > > > Maybe, nobody can tell WTF is going on from your > descriptions :-( > -- > http://mail.python.org/mailman/listinfo/python-list > __________________________________ Do you Yahoo!? Yahoo! Mail - You care about security. So do we. http://promotions.yahoo.com/new_mail From michele.simionato at gmail.com Tue Apr 12 12:51:19 2005 From: michele.simionato at gmail.com (Michele Simionato) Date: 12 Apr 2005 09:51:19 -0700 Subject: singleton objects with decorators In-Reply-To: References: <1113300588.335527.26290@o13g2000cwo.googlegroups.com> <1113310269.596284.136100@f14g2000cwb.googlegroups.com> <1113318042.836605.132820@o13g2000cwo.googlegroups.com> Message-ID: <1113324679.749845.300040@l41g2000cwc.googlegroups.com> Uhm? If I pass different parameters I want to have different instances. The Singleton behaviour is recovered only when I pass always the same arguments, in particular when I pass 0-arguments: >>> class Foobar: ... __metaclass__ = Memoize ... >>> Foobar() <__main__.Foobar object at 0xb7defbcc> >>> Foobar() <__main__.Foobar object at 0xb7defbcc> >>> Foobar() <__main__.Foobar object at 0xb7defbcc> Of course if for Singleton you mean "whatever I pass to the constructor it must always return the same instance" then this pattern is not a Singleton. This is why I call it memoize ;) From max2 at fisso.casa Tue Apr 5 13:30:46 2005 From: max2 at fisso.casa (max(01)*) Date: Tue, 05 Apr 2005 17:30:46 GMT Subject: redundant importr In-Reply-To: References: <3avnh3F6cekgkU1@individual.net> <1MudnZ0j7M-bIdDfRVn-sA@powergate.ca> Message-ID: Peter Hansen wrote: > max(01)* wrote: > >> Peter Hansen wrote: >> >>> No it doesn't. I thought I was clear, but I can reword >>> it for you: the files are compiled *in-memory* and the >>> results are never written to disk. >>> >>> > *if* they are compiled, where are they put, if the >>> >>>> corresponding *.py files are on a non-writeable directory? >>> >>> >>> They are not put anywhere. >> >> >> ok, maybe it is an implementation-dependent issue after all. > > > Not really. > >> consider this: > > [snip] > >> -rw-r--r-- 1 max2 max2 307 2005-04-02 17:45 imported.pyc >> >> see? > > > Yes, but you don't, yet. :-) > > Obviously the .pyc file is being written, so my comments > above, out of context, is wrong. > oops! > Now please go put them back in context. You asked what > would happen if the directory was not writable. That's > the context in which to interpret my claims that the > bytecode (the *result* of the compilation) is not > written to disk. > > I'll try one last time, before giving up in abject > failure and letting someone else take a stab at this: > the compilation will occur every time if a .pyc file > does not exist. The interpreter will attempt to write > the results of the compilation process to disk in a > ..pyc file to cache it for the next time, to avoid > having to recompile. *If* this is not possible, then > no caching takes place, no .pyc file is written, and > the next time you run the code, the compilation step > will occur all over again (note: with the results being > held in memory only while the program runs, then > discarded). > > Please tell me it's clear now. :-) it's not clear. it's crystalline. :-) thanks for your patience and help. best regards macs From seberino at spawar.navy.mil Wed Apr 20 01:58:49 2005 From: seberino at spawar.navy.mil (seberino at spawar.navy.mil) Date: 19 Apr 2005 22:58:49 -0700 Subject: Why Python does *SLICING* the way it does?? Message-ID: <1113976729.450677.261130@o13g2000cwo.googlegroups.com> Many people I know ask why Python does slicing the way it does..... Can anyone /please/ give me a good defense/justification??? I'm referring to why mystring[:4] gives me elements 0, 1, 2 and 3 but *NOT* mystring[4] (5th element). Many people don't like idea that 5th element is not invited. (BTW, yes I'm aware of the explanation where slicing is shown to involve slices _between_ elements. This doesn't explain why this is *best* way to do it.) Chris From grante at visi.com Thu Apr 21 09:47:47 2005 From: grante at visi.com (Grant Edwards) Date: Thu, 21 Apr 2005 13:47:47 -0000 Subject: goto statement References: <20050420092359.81900.qmail@web8409.mail.in.yahoo.com> <3cmtgvF6q13cvU1@individual.net> Message-ID: <116fbo3pma1lsdb@corp.supernews.com> On 2005-04-21, Sergei Organov wrote: > Well, I'm writing for embedded realtime systems in C/C++ and > have never encountered a single need to use goto. I have encountered situations in C programs where the best thing to use was a goto. Those situations have always been handled beutifully by a "raise" in Python. > Comparing interrupts to goto doesn't make any sense for me > either. For example, most architectures have 'branch' > *hardware* instructions that are much more close equivalents > to goto than interrupts are, but that doesn't justify use of > goto in high-level languages in any way. I agree. The "jump" or "branch" instruction corresponds exactly to a goto. An interrupt is more like a "signal" and a "signal handler" in C. Sort of like an asynchronous function call or thread context switch. -- Grant Edwards grante Yow! Now that we're at in LOVE, you can BUY visi.com this GOLDFISH for a 48% DISCOUNT. From peter at engcorp.com Fri Apr 1 12:41:26 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 01 Apr 2005 12:41:26 -0500 Subject: Showing errors explicitly in try... except In-Reply-To: <1112354356.092391.238710@f14g2000cwb.googlegroups.com> References: <1112354356.092391.238710@f14g2000cwb.googlegroups.com> Message-ID: Harlin Seritt wrote: > When using try... except... errors don't show up. Is there a way to > force stderr despite using try...except? "force", no. The "stderr" stuff is done by an "unhandled exception" handler that is at the very top level, so if you catch the exception, it will never see it to print it. Doing this will probably suffice, however: import traceback try: 1/0 # one should avoid non-specific exception catching # in most cases, but this is an example: except: traceback.print_exc() -Peter From tjreedy at udel.edu Sun Apr 24 00:20:40 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 24 Apr 2005 00:20:40 -0400 Subject: Variables References: <426B0283.40602@cloudthunder.com> <426B083A.70104@cloudthunder.com> Message-ID: "Richard Blackwood" wrote in message news:426B083A.70104 at cloudthunder.com... > Indeed, this language is math. In mathematics, the word 'variable' is generally an undefined meta-term that is *notorious* for having multiple possible meanings and shades of meaning. One mathematician/linguist once claimed to have discerned somewhere around 15 different meanings and shades thereof. The context usually makes the particular meaning clear enough, at least to other mathematicians. But the ambiguity sometimes disconcerting to students. > My friend says that foo is a constant and necessarily not a variable. 'constant' is one of the possible meanings of 'variable'. As is "Given that (3*x -2)/5 = 1, what is the value of the variable x". Sometimes, whether a 'variable' actually 'varies' or not, is a matter of viewpoint. We may think of 'varying' as something that happens in time, whereas most math is timeless. In any case, 'foo=5' can be followed, in Python, by 'foo="hopscotch" '. So names (as opposed to objects) do not even have a type. Also, in Python, 'variable' is not a part of the official language description in the way it is for some other programming languages. Terry J. Reedy From rpmuller at gmail.com Wed Apr 6 18:30:41 2005 From: rpmuller at gmail.com (RickMuller) Date: 6 Apr 2005 15:30:41 -0700 Subject: sorting a list and counting interchanges Message-ID: <1112826641.728979.278530@f14g2000cwb.googlegroups.com> I have to sort a list, but in addition to the sorting, I need to compute a phase factor that is +1 if there is an even number of interchanges in the sort, and -1 if there is an odd number of interchanges. I could write a bubble sort, count the number of interchanges, and compute the factor, but I have a feeling that there some decorate-sort-undecorate solution buried in this problem somewhere. However, I can't see it. Can anyone else help me with this? I was thinking of something along the lines of zipping the list with a range() of the same length, sorting that, and then counting the number of times the second list has an item smaller than its previous item. In other words a = [1,10,2,7] b = zip(a,range(len(a))) b.sort() a_sorted = [i for i,j in b] order = [j for i,j in b] phase = 0 for i in range(len(order)-1): if order[i] > order[i+1]: phase += 1 phase = 2*(phase%2)-1 However, I can't prove that this works, and there's *got* to be a more elegant way. Thanks in advance, Rick From fredrik at pythonware.com Fri Apr 8 17:03:02 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 8 Apr 2005 23:03:02 +0200 Subject: Declaring variables from a list References: <1163d88e.0504081255.438fbb96@posting.google.com> Message-ID: "Cactus" wrote: > If I got a list is it possible to declare a variable from the items in that list? > > Code Sample: > Blob = ['Var1', 'Var2', 'vAR3'] > i = 5 > for listitems in Blob: > i += 1 > listitems = i > > print Var1 > 6 > print Var2 > 7 > print vAR3 > 8 > > Something like that? This doesn't work (obviously) but is there a way to do this? why? if you want a dictionary, use a dictionary (see the tutorial for details). From mediocre_person at hotmail.com Thu Apr 21 11:46:48 2005 From: mediocre_person at hotmail.com (mediocre_person at hotmail.com) Date: 21 Apr 2005 08:46:48 -0700 Subject: A smallish Tkinter question In-Reply-To: <4267c284$1_3@newspeer2.tds.net> References: <1114096464.111138.262750@o13g2000cwo.googlegroups.com> <4267c284$1_3@newspeer2.tds.net> Message-ID: <1114098408.274110.136660@z14g2000cwz.googlegroups.com> ***Many*** thanks. I was getting right confused, but this is pretty clear. I had also tried, in run(...): while True: sleep(1.0) ... But it's clear from your response why this also didn't work! Nick. From gandalf at geochemsource.com Thu Apr 7 11:37:46 2005 From: gandalf at geochemsource.com (Laszlo Zsolt Nagy) Date: Thu, 07 Apr 2005 17:37:46 +0200 Subject: import statement - package visibility problem In-Reply-To: <425550AC.2020006@geochemsource.com> References: <42550CB9.8060309@geochemsource.com> <425539D2.2020001@rubin.hu> <425550AC.2020006@geochemsource.com> Message-ID: <425553CA.9090403@geochemsource.com> >> >> 2. Maybe the layering of your application is wrong. If >> DatabaseConnection provides common functionality to the different >> Adapters, it should be on the same layer or one beneath the Adapters. > Another notice. If I put 'DatabaseConnection' under 'Adapters' then it means that 'DatabaseConnection' is an adapter. But it is not. :-) In the other direction, Adapters are deeper, so adapters should can DatabaseConnection-s (and in fact they are). -- _________________________________________________________________ Laszlo Nagy web: http://designasign.biz IT Consultant mail: gandalf at geochemsource.com Python forever! From ivanlan at pauahtun.org Mon Apr 18 11:02:44 2005 From: ivanlan at pauahtun.org (Ivan Van Laningham) Date: Mon, 18 Apr 2005 09:02:44 -0600 Subject: Slight discrepancy with filecmp.cmp References: Message-ID: <4263CC14.8E920226@pauahtun.org> Hi All-- John Machin wrote: > > On Sun, 17 Apr 2005 22:06:04 -0600, Ivan Van Laningham > wrote: > [snip] > > So I wrote a set of > >programs to both index the disk versions with the cd versions, and to > >compare, using filecmp.cmp(), the cd and disk version. Works fine. > >Turned up several dozen files that had been inadvertantly rotated or > >saved with the wrong quality, various fat-fingered mistakes like that. > > > >However, it didn't flag the files that I know have bitrot. I seem to > >remember that diff uses a checksum algorithm on binary files, not a > >byte-by-byte comparison. Am I wrong? > > According to the docs: > > """ > cmp( f1, f2[, shallow[, use_statcache]]) > > Compare the files named f1 and f2, returning True if they seem equal, > False otherwise. > Unless shallow is given and is false, files with identical os.stat() > signatures are taken to be equal > """ > > and what is an os.stat() signature, you ask? So did I. > > According to the code itself: > > def _sig(st): > return (stat.S_IFMT(st.st_mode), > st.st_size, > st.st_mtime) > > Looks like it assumes two files are the same if they are of the same > type, same size, and same time-last-modified. Normally I guess that's > good enough, but maybe the phantom bit-toggler is bypassing the file > system somehow. What OS are you running? > WinXP, SP2 > You might like to do two things: (1) run your comparison again with > shallow=False (2) submit a patch to the docs. > You know, I read that doc, tried it, and it made absolutely no difference. Then I read your message, read the docs again, and finally realized I had flipped the sense of shallow in my head. Sheesh. So then I tried it with shallow=False, not True, and it runs about ten times slower, but it works. Beautifully. Now I have to go back and redo the first five thousand, but it's worth it. Thanks. Shows how much you need another set of eyeballs to debug your brain;-) > (-: > You have of course attempted to eliminate other variables by checking > that the bit-rot effect is apparent using different display software, > a different computer, an observer who's not on the same medication as > you, ... haven't you? > :-) > ;-) Absolutely. Several different viewers and several different OSs. And my wife never sees anything the way I do;-) Metta, Ivan ---------------------------------------------- Ivan Van Laningham God N Locomotive Works http://www.andi-holmes.com/ http://www.foretec.com/python/workshops/1998-11/proceedings.html Army Signal Corps: Cu Chi, Class of '70 Author: Teach Yourself Python in 24 Hours From cfriedl at bigpond.net.au Wed Apr 27 19:57:30 2005 From: cfriedl at bigpond.net.au (cfriedl at bigpond.net.au) Date: 27 Apr 2005 16:57:30 -0700 Subject: suggestions on how to do this In-Reply-To: References: Message-ID: <1114646250.393470.152270@l41g2000cwc.googlegroups.com> Hi Terry I apprecaite the advice. Briefly I'm familiar with the math (its an eigenvalue problem in fluid flow) but not so much with python (3 months on and off), hence my post here. I'm looking for python advice on how to implement this effectively. I love python and would like to use it well. As for vague subject, I've not found a strong correlation between subject line and number or depth of responses. Perhaps today the curious looked at it. But at other times, even with a quite specific subject, no replies come. Such is life. From deetsNOSPAM at web.de Thu Apr 7 09:14:37 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Thu, 07 Apr 2005 15:14:37 +0200 Subject: Python backend binding to PAM, NSS or pppd References: Message-ID: Heiko Wundram wrote: > Hey all! > > Before I start hacking away, I'm looking for a Python backend binding for > libpam or libnss, or a python binding for the pppd plugin mechanism. > > I'm trying to set up an SQL authentication scheme for virtual user > accounts used for mail and PPTP-VPN-access, and I'd love to do the > authentication bit in Python. And, yes, I know about pam-mysql and > nss-mysql, but both projects are old and unmaintained, and I use Oracle as > backend DB anyway. > > If anybody knows of any project which has implemented a part of this, I'd > love to hear about the effort... I've been using pyton-pam before. Works as expected - but pam frustrated me a bit, and you gotta run as root for it to work - a thing I didn't want to do. No idea for pppd. -- Regards, Diez B. Roggisch From abhishek216 at yahoo.com Wed Apr 20 03:46:36 2005 From: abhishek216 at yahoo.com (Abhishek S) Date: Wed, 20 Apr 2005 00:46:36 -0700 (PDT) Subject: Fwd: Memory leak in python Message-ID: <20050420074636.57522.qmail@web31714.mail.mud.yahoo.com> Hi Nick, Thanks for reply... Please include me in reply. Currently i am not in the list (i will subscribe soon) I upgarded to 2.4.1 - still the same issue. Nick> Thats not a lot of leak - have you done that over a longer time period? Abhi> I have tried for 4 days. It has reached 150MB. Nick> Are there any objects in gc.garbage? >>> gc.set_debug(gc.DEBUG_LEAK) >>> gc.get_debug( ) 62 >>> gc.collect() 0 >>> gc.garbage [] >>> Abhi> There is none. Nick> Are you writing objects with __del__ methods? If so then that is your problem probably. Abhi> I have not written any __del__ methods. Nick> Have you written any C extension modules in C? Yes. Many - All of them are called only when the app starts. And never called again. Till then it is stable only - 16MB used. I have tried following - let me know if you need any more details.. and want me to try something. 1) I found a "sizer" python program. Which gives me the module which is growing. It indicates that __main__ is growing. __main__': 4000774 2) I tried following.. (not smart but..) def f(): c = gc.get_objects() j = 0 for i in c: j = j + 1 try: tmp = len(i) if tmp > 1000: print "(c[%d]) (%d)," % (j-1, tmp) except: pass it prints me as folows: l(c[175]) (7336), l(c[12475]) (1260), l(c[12477]) (1260), l(c[12479]) (1381), l(c[12481]) (1381), l(c[34159]) (1200), l(c[37144]) (28234), l(c[37191]) (28286), >>> type(c[37191]) >>> for k,v in c[37164].items(): ... print k, v ... b = b + 1 ... if b > 30: ... break ... 1085115764 620 1080048556 2 1085045932 4 1085146316 1 1085246700 2 1090615060 9 1089571940 2 1090519084 2 1090876932 234 1093456364 48 1085168140 2 1089964748 6 1089994828 0 1090095684 69 1076932268 2 1085014108 6 1080092204 10 1084888812 1 1118543628 48 1089994860 6 1076731524 6 1079640188 3 1084883076 15 1079712492 1 1118459244 64 1080295564 1 1076522028 4 1085211788 2 1076887700 20 1076729756 70 1091012236 2 This two dict in the last is growing slowly.. I am not maintaing any dict with such indices and value. Any clue? Please let me know what else to check and how! At the time i am ending this.. module size.. '__main__': 7926830, Thanks, Abhishek Note: forwarded message attached. __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -------------- next part -------------- An embedded message was scrubbed... From: Abhishek S Subject: Memory leak in python Date: Tue, 19 Apr 2005 04:58:18 -0700 (PDT) Size: 2678 URL: From uche.ogbuji at gmail.com Sat Apr 16 10:12:30 2005 From: uche.ogbuji at gmail.com (Uche Ogbuji) Date: Sat, 16 Apr 2005 08:12:30 -0600 Subject: python modules in home dir In-Reply-To: <8416c258.0504091309.7ba2047d@posting.google.com> References: <8416c258.0504091309.7ba2047d@posting.google.com> Message-ID: <1113660751.14099.19.camel@borgia> On Sat, 2005-04-09 at 14:09 -0700, dzieciou wrote: > I'm new-comer in Python. > I want to install few Python modules (4Suite, RDFLib, Twisted and Racoon) > in my home directory, since Python installation is already installed in the > system > and I'm NOT its admin. > I cannot install pyvm (portable binary python machine) - have no such big > quota. > Any idea how can I solve it? To install 4Suite in the home dir, use an incantation such as: ./setup.py config --prefix=$HOME/lib ./setup.py install Note: I expect you also installed Python in your home dir? -- Uche Ogbuji Fourthought, Inc. http://uche.ogbuji.net http://fourthought.com http://copia.ogbuji.net http://4Suite.org Use CSS to display XML, part 2 - http://www-128.ibm.com/developerworks/edu/x-dw-x-xmlcss2-i.html Writing and Reading XML with XIST - http://www.xml.com/pub/a/2005/03/16/py-xml.html Use XSLT to prepare XML for import into OpenOffice Calc - http://www.ibm.com/developerworks/xml/library/x-oocalc/ Schema standardization for top-down semantic transparency - http://www-128.ibm.com/developerworks/xml/library/x-think31.html From tlesher at gmail.com Wed Apr 20 20:21:17 2005 From: tlesher at gmail.com (Tim Lesher) Date: 20 Apr 2005 17:21:17 -0700 Subject: python-dev Summary for 2005-04-01 through 2005-04-15 Message-ID: <1114042877.208529.146820@g14g2000cwa.googlegroups.com> [The HTML version of this Summary is available at http://www.python.org/dev/summary/2005-04-01_2005-04-15.html] ====================== Summary Announcements ====================== --------------------------- New python-dev summary team --------------------------- This summary marks the first by the team of Steve Bethard, Tim Lesher, and Tony Meyer. We're trying a collaborative approach to the summaries: each fortnight, we'll be getting together in a virtual smoke-filled back room to divide up the interesting threads. Then we'll stitch together the summaries in roughly the same form as you've seen in the past. We'll mark each editor's entries with his initials. Thanks to Brett Cannon for sixty-one excellent python-dev summaries. Also, thanks for providing scripts to help get the new summaries off the ground! We're looking forward to the contributions you'll make to the Python core, now that the summaries aren't taking up all your time. [TDL] ========= Summaries ========= ----------------------- Acceptable diff formats ----------------------- Nick Coghlan asked if context diffs are still favoured for patches. Historically, context diffs were preferred, but it appears that unified diffs are the today's choice. Raymond Hettinger made the sensible suggestion that whichever is most informative for the particular patch should be used, and Bob Ippolito pointed out that if CVS is replaced with subversion, unified diffs will have better support. The `patch submission guidelines`_ will be updated at some point to reflect the preference for unified diffs, although if your diff program doesn't support '-u', then context diffs are ok - plain patches are, of course, not. Contributing threads: - `Unified or context diffs? `__ .. _patch submission guidelines: http://www.python.org/patches/ [TAM] --------------- Developers List --------------- Raymond Hettinger has started a `project to track developers`_ and the (tracker and commit) privileges they have, and who gave them the privileges, and why (for example, was it for a one-shot project). Removing inactive developers should improve clarity, institutional memory, security, and makes everything tidier. Raymond has begun contacting recently inactive developers to check whether they still require the privileges they have. Contributing threads: - `Developer list update `__ .. _project to track developers: http://cvs.sourceforge.net/viewcvs.py/*checkout*/python/python/dist/src/Misc/developers.txt [TAM] ---------------------- Right Operator Methods ---------------------- Greg Ewing explored an issue with new-style classes that define only right operator methods (__radd__, __rmul__, etc.) Instances of such a class cannot be added/multiplied/etc. together as Python raises a TypeError. Armin Rigo explained the rule: if the instances on both sides of an operator are of the same class, only the non-reversed method is ever called. Armin also explained that an __add__ or __mul__ method that returns NotImplemented may be called twice when Python attempts to differentiate between numeric and sequence operations. Contributing threads: - `New style classes and operator methods `__ [SJB] ------------------------------------------ Hierarchical groups in regular expressions ------------------------------------------ Chris Ottrey demoed his `pyre2 project`_ that can extract a hierarchy of strings when nested groups match in a regular expression. The current re module (in the stdlib) only matches the last occurrence of a group in the string, throwing away any preceding matches. People discussed some of pyre2's proposed API, with the main suggestion being to extend the API to support unnamed (positional) groups in addition to named groups. Though a number of people expressed interest in the idea, it was not clear whether the functionality should be included in the standard library. However, most agreed that if it was included, it should be integrated with the existing re module. Gustavo Niemeyer offered to perform this integration if an API could be agreed upon. Further discussion was moved to the pyre2 `development wiki`_ and `mailing list`_. Contributing threads: - `hierarchicial named groups extension to the re library `__ .. _pyre2 project: http://pyre2.sourceforge.net/ .. _development wiki: http://py.redsoft.be/pyre2/wiki/ .. _mailing list: http://lists.sourceforge.net/lists/listinfo/pyre2-devel [SJB] ------------------------------- Security capabilities in Python ------------------------------- The issue of security came up again, and Ka-Ping Yee suggested that in Python's restricted execution mode secure proxies can be created by using lexical scoping. He posted `some code`_ for revealing only certain "facets" of an object by using a function to declare a proxy class that used a function's local variables to build the proxy. Thus to access the attributes used in the proxy class, you need to access things like im_func or func_closure, which are not accessible in restricted execution mode. James Y Knight illustrated how strategic overriding of __eq__ in a subclass of str could allow access to the hidden "facets". Eyal Lotem suggested that such an attack could be countered by implementing "facets" in C, but having to turn to C every time you needed a particular security construct seemed unappealing. Contributing threads: - `Security capabilities in Python `__ .. _some code: http://zesty.ca/python/facet.py [SJB] --------------------------------- Improving GilState API Robustness --------------------------------- Michael Hudson noted that his changes to thread handling in the readline module appeared to trigger `bug 1176893`_ ("Readline segfault"). However, he believed the problem lay in the GilState API, rather than in his changes: PyGilState_Release crashes if PyEval_InitThreads wasn't called, even if the code you're writing doesn't use multiple threads. He proposed several solutions, but no clear favorite emerged from respondents, and Tim Peters noted that `PEP 311`_, Simplified Global Interpreter Lock Acquisition for Extensions, "specifically disowns responsibility for worrying about whether Py_Initialize and PyEval_InitThreads have been called." After further discussion, Michael checked in a change to PyGilState_Release that calls PyEval_SaveThread instead of PyEval_ReleaseThread, fixing the problem. Bob Ippolito wondered whether just calling PyEval_InitThreads directly in Py_Initialize might be a better idea. No objections were raised, so long as the underlying OS locking mechanisms weren't overly expensive; some initial benchmarks indicated that this approach was viable, at least on Linux and OS X. Contributing threads: - `threading (GilState) question `__ .. _bug 1176893: http://www.python.org/sf/1176893 .. _PEP 311: http://www.python.org/peps/pep-0311.html [TDL] ---------------------------------------- Unicode byte order mark decoding ---------------------------------------- Evan Jones saw that the UTF-16 decoder discards the byte-order mark (BOM) from Unicode files, while the UTF-8 decoder doesn't. Although the BOM isn't really required in UTF-8 files, many Unicode-generating applications, especially on Microsoft platforms, add it. Walter D?rwald created a patch_ to add a UTF-8-Sig codec that generates a BOM on writing and skips it on reading. A long discussion ensued on the history of the Unicode standard and Microsoft's influence over its evolution. Stephen Turnbull suggested (and Marc-Andre Lemburg agreed) that BOM and signature handling be moved to a higher-level API, but no overall consensus was achieved. Contributing threads: - `Unicode byte order mark decoding `__ .. _patch: http://www.python.org/sf/1177307 [TDL] -------------------- Marshalling Infinity -------------------- Scott David Daniels kicked off a very long thread by asking what (un)marshal should do with floating point NaNs. The current behaviour (as with any NaN, infinity, or signed zero) is undefined: a platform-dependant accident, because Python is written to C89, which has no such concepts. Tim Peters pointed out all code for (de)serialing C doubles should go through _PyFloat_Pack8()/_PyFloat_Unpack8(), and that the current implementation suggests that the routines could simply copy bytes on platforms that use the standard IEEE-754 single and double formats natively. Michael Hudson obliged by creating a `patch to implement this`_. The consensus was that the correct behaviour is that packing a NaN or infinity shouldn't cause an exception. When unpacking, an IEEE-754 platform shouldn't cause an exception, but a non-754 platform should, since there's no sensible value that it can be unpacked to, and errors should never pass silently. Contributing threads: - `marshal / unmarshal `__ .. _patch to implement this: http://python.org/sf/1181301 [TAM] --------------------------------- Location of the sign bit in longs --------------------------------- Michael Hudson asked about the possibility of longs storing the sign bit somewhere other than the current location, suggesting the top bit of ob_digit[0]. Tim Peters suggested that it would be better to give struct _longobject a distinct sign member. This simplifies code, costs no extra bytes for some longs, and 8 extra bytes for others, and shouldn't hurt binary compatibility. Michael coughed up a `longobject patch`_, which seems likely to be checked in. Contributing threads: - `marshal / unmarshal `__ .. _longobject patch: http://python.org/sf/1177779 [TAM] =============== Skipped Threads =============== - python-dev Summary for 2005-03-16 through 2005-03-31 [draft] - [Python-checkins] python/dist/src/Lib/logging handlers.py, 1.19, 1.19.2.1 - [Python-checkins] python/dist/src/Modules mathmodule.c, 2.74, 2.75 - Weekly Python Patch/Bug Summary - Mail.python.org - New bug, directly assigned, okay? - inconsistency when swapping obj.__dict__ with a dict-like object... - Pickling instances of nested classes - args attribute of Exception objects ======== Epilogue ======== ------------ Introduction ------------ This is a summary of traffic on the `python-dev mailing list`_ from April 01, 2005 through April 15, 2005. It is intended to inform the wider Python community of on-going developments on the list on a semi-monthly basis. An archive_ of previous summaries is available online. An `RSS feed`_ of the titles of the summaries is available. You can also watch comp.lang.python or comp.lang.python.announce for new summaries (or through their email gateways of python-list or python-announce, respectively, as found at http://mail.python.org). This is the first summary written by the python-dev summary cabal of Steve Bethard, Tim Lesher, and Tony Meyer (So long, Brett, and thanks for all the fish!). To contact us, please send email: - Steve Bethard (steven.bethard at gmail.com) - Tim Lesher (tlesher at gmail.com) - Tony Meyer (tony.meyer at gmail.com) Do *not* post to comp.lang.python if you wish to reach us. The `Python Software Foundation`_ is the non-profit organization that holds the intellectual property for Python. It also tries to advance the development and use of Python. If you find the python-dev Summary helpful please consider making a donation. You can make a donation at http://python.org/psf/donations.html . Every penny helps so even a small donation with a credit card, check, or by PayPal helps. -------------------- Commenting on Topics -------------------- To comment on anything mentioned here, just post to `comp.lang.python`_ (or email python-list at python.org which is a gateway to the newsgroup) with a subject line mentioning what you are discussing. All python-dev members are interested in seeing ideas discussed by the community, so don't hesitate to take a stance on something. And if all of this really interests you then get involved and join `python-dev`_! ------------------------- How to Read the Summaries ------------------------- The in-development version of the documentation for Python can be found at http://www.python.org/dev/doc/devel/ and should be used when looking up any documentation for new code; otherwise use the current documentation as found at http://docs.python.org/ . PEPs (Python Enhancement Proposals) are located at http://www.python.org/peps/ . To view files in the Python CVS online, go to http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/ . Reported bugs and suggested patches can be found at the SourceForge_ project page. Please note that this summary is written using reStructuredText_. Any unfamiliar punctuation is probably markup for reST_ (otherwise it is probably regular expression syntax or a typo =); you can safely ignore it. I do suggest learning reST, though; it's simple and is accepted for `PEP markup`_ and can be turned into many different formats like HTML and LaTeX. Unfortunately, even though reST is standardized, the wonders of programs that like to reformat text do not allow me to guarantee you will be able to run the text version of this summary through Docutils_ as-is unless it is from the `original text file`_. .. _python-dev: http://www.python.org/dev/ .. _SourceForge: http://sourceforge.net/tracker/?group_id=5470 .. _python-dev mailing list: http://mail.python.org/mailman/listinfo/python-dev .. _c.l.py: .. _comp.lang.python: http://groups.google.com/groups?q=comp.lang.python .. _PEP Markup: http://www.python.org/peps/pep-0012.html .. _Docutils: http://docutils.sf.net/ .. _reST: .. _reStructuredText: http://docutils.sf.net/rst.html .. _PSF: .. _Python Software Foundation: http://python.org/psf/ .. _last summary: http://www.python.org/dev/summary/ .. _original text file: http://www.python.org/dev/summary/2005-04-01_2005-04-15.ht .. _archive: http://www.python.org/dev/summary/ .. _RSS feed: http://www.python.org/dev/summary/channews.rdf From steve at holdenweb.com Mon Apr 4 16:51:49 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 04 Apr 2005 16:51:49 -0400 Subject: text analysis in python In-Reply-To: <42507E00.1090806@acm.org> References: <1325i2-sd2.ln1@lairds.us> <424FF1CD.2040102@acm.org> <42507E00.1090806@acm.org> Message-ID: Maurice LING wrote: > Terry Reedy wrote: > >> "Maurice LING" wrote in message >> news:424FF1CD.2040102 at acm.org... >> >>> Say I code my stuffs in Jython (importing java libraries) in a file >>> "text.py" >> >> >> >> Just to be clear, Jython is not a separate langague that you code >> *in*, but a separate implementation that you may slightly differently >> code *for*. >> > Yes, I do get this point rightly. Jython is just an implementation of > Python virtual machine using Java. I do note that there are some > differences, such as, Jython can only handle pure python modules. > However, I'm not a language expert to differentiate language differences > between these 2 implementations of Python, as in Jython and CPython. If > someone care to enlighten, it will be my pleasure to consult. TIA. > That's not strictly correct. The Python virtual machine isn;t implemented at all in Jython, instead the JVM is used as the compilation target. >> >>> ... Will there be any issues when I try to import text.py into CPython? >> >> >> >> If text.py is written in an appropriate version of Python, it itself >> will cause no problem. Hoqwever, when it imports javacode files, as >> opposed to CPython bytecode files, CPython will choke. >> > In my example, the file "text.py" is coded in Jython, importing Java > libraries. I do get that I cannot import Java jar files directly into > CPython. What I do not get is that what is so special about Jython that > it can "fool" CPython into using Java libraries... or is that there will > always be a need for Java virtual machine and Python virtual machine > when I use Java libraries in Jython... and importing Jython coded files > into CPython.... > Jython is pretty much a Python interpreter that compiles Python into JVM bytecodes. Consequently the amount of "trickery" involved is rather less, though clearly there is some (automated conversion b etween Java and Pythin data types where appropriate, and automated signature-based selection of the appropriate Java method being the two most obvious). regards Steve -- Steve Holden +1 703 861 4237 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ From jepler at unpythonic.net Tue Apr 12 17:09:01 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 12 Apr 2005 16:09:01 -0500 Subject: Why won't someone step up and make use of the Free tools (was Re: Python 2.4 killing commercial Windows Python development ?) In-Reply-To: <425c29b6.217598109@news.oz.net> References: <425a9869$0$38039$bed64819@news.gradwell.net> <425c29b6.217598109@news.oz.net> Message-ID: <20050412210900.GC6421@unpythonic.net> On Tue, Apr 12, 2005 at 08:25:58PM +0000, Bengt Richter wrote: > But credit where due. Someone has stepped up to a large chunk of the problem: > > http://jove.prohosting.com/iwave/ipython/pyMinGW.html Yay. I'm glad somebody *is* doing this. Maybe all that is needed is to "get the word out". Some prepackaged binaries would be nice, however. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From james at wrong.nu Thu Apr 14 09:47:05 2005 From: james at wrong.nu (R. C. James Harlow) Date: Thu, 14 Apr 2005 13:47:05 +0000 Subject: Supercomputer and encryption and compression @ rate of 96% In-Reply-To: <1113470846.970773.4780@g14g2000cwa.googlegroups.com> References: <1113470846.970773.4780@g14g2000cwa.googlegroups.com> Message-ID: <200504141447.05710.james@wrong.nu> On Thursday 14 April 2005 10:27, c3poptuse at yahoo.com wrote: > Supercomputer and encryption and compression @ rate of 96% Dear Sir or Madam, I have received notification that you posted a compression algorithm on the newsgroup comp.lang.python on or about 10:27:26 on the 04/14/2005. I am writing to you to inform you that the algorithm published infringes my "zero-bit compression" algorithm, US Pat No. 13375P33K, which details the transmission of information using no bandwidth to achieve a 100% compression. Please immediately follow up with a retraction of rights to this algorithm or you will hear from my solicitor, Mr J. Peasbody. Yours in law, James Harlow. From justaskme at if.you.want.to.contact.me Sat Apr 9 08:12:11 2005 From: justaskme at if.you.want.to.contact.me (Joe) Date: Sat, 09 Apr 2005 14:12:11 +0200 Subject: Python/wxPython Reducing memory usage. References: <1113028557.757987.146950@g14g2000cwa.googlegroups.com> Message-ID: On 8 Apr 2005 23:35:57 -0700, "lotmr" wrote: >Is there any way that I could compile or optimize the my program and/or its memory usage? ... and ideally, if we could also reduce the size of the DLL, so that it would only include the widgets actually used, it'd be even nicer. >(Note: I don't have a problem with making this program win32 specific, >as it already is only win32) I don't have much experience with it, but is the PythonWin wrapper to MFC horrible to use as compared to wxWidgets? If it's good enough and you don't care about non-Windows platforms, you'll probably save a lot of RAM and file footprint. Joe. From matt.fryer at gmail.com Fri Apr 22 12:31:59 2005 From: matt.fryer at gmail.com (Matt) Date: 22 Apr 2005 09:31:59 -0700 Subject: Python Debugger with source code tracking ability In-Reply-To: References: Message-ID: <1114187519.431002.184420@z14g2000cwz.googlegroups.com> wxPython is including the ActiveGrid ide as a sample in its latest point release. The ide includes a debugger that allows you to set breakpoints in source code, inspect values, etc. From irmen.NOSPAM at xs4all.nl Sat Apr 16 09:43:32 2005 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Sat, 16 Apr 2005 15:43:32 +0200 Subject: XML parsing per record In-Reply-To: References: Message-ID: <42611686$0$148$e4fe514c@news.xs4all.nl> Willem Ligtenberg wrote: > I want to parse a very large (2.4 gig) XML file (bioinformatics ofcourse :)) > But I have no clue how to do that. Most things I see read the entire xml > file at once. That isn't going to work here ofcourse. > > So I would like to parse a XML file one record at a time and then be able > to store the information in another object. > How should I do that? > > Thanks in advance, > > Willem Ligtenberg > A total newbie to python by the way. Read about SAX parsers. This may be of help: http://www.devarticles.com/c/a/XML/Parsing-XML-with-SAX-and-Python/ Out of curiousity, why is the data stored in a XML file? XML is not known for its efficiency.... --Irmen From Scott.Daniels at Acm.Org Fri Apr 8 16:18:33 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 08 Apr 2005 13:18:33 -0700 Subject: Can dictionary values access their keys? In-Reply-To: References: <4256b3d3$1@nntp0.pdx.net> Message-ID: <4256e1ba$1@nntp0.pdx.net> Matthew Thorley wrote: > Scott David Daniels wrote: ...(explaining Python has no "the" parent) > I see what your saying, but I my situation the values of the dictionary > are unique objects created by a parent object. But that is your convention, not Python's. Some good general rules: 1) For frequent (or fast) access you should know where something is, rather than search for it. 2) You (your app) should be willing to "pay" for your own needs for navigation rather than expect a built-in cost for everyone that provides convenience for a few. 3) A very "Pythonic" storage system makes it clear how you navigate, so relying on magic is usually a bad idea. > When the 'root object' is 'global' I see what your saying, but when > > class A: > def __init__(self, container): > self.container=container > > class B(dict): > def magice_get_parent(self): > ... > > class special_value(): > def __init__(self, val): > self.val = val > > def magic_get_key(self): > ... > > parent = A(B) > parent.container[x] = special_value(1) > parent.container[y] = special_value(2) > parent.container[z] = special_value(1) OK, if you want help, try doing code, not sketching what it might be. > class special_value(): Cannot be. Perhaps: class special_value(object): > class A: > def __init__(self, container): > self.container=container ... > class B(dict): ... > parent = A(B) > parent.container[x] = ... Either you must use: parent = A(B()) or class A: def __init__(self, containerClass): self.container = containerClass() By the way, if you are subclassing dict, you might as well use new-style throughout (so: class A(object): ...). Now, how about rather than all of this magic, trying: class A: def __init__(self, container): self.container = container self.container.parent = self and instead of > parent.container[x] = special_value(1) parent.container.set(x, special_value(1)) using: class B(dict): ... def set(self, key, contents): self[key] = contents contents.origin = self, key ... Then after: parent = A(B()) parent.container.set(x, special_value(1)) parent.container.set(y, special_value(2)) parent.container.set(z, special_value(1)) You can do: child = parent.container print child.parent value1 = parent.container[x] box, key = value1.origin assert box[key] is value1 and box.parent is parent And you didn't have to use magic at all. --Scott David Daniels Scott.Daniels at Acm.Org From bokr at oz.net Sat Apr 30 03:28:05 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 30 Apr 2005 07:28:05 GMT Subject: Micro-PEP: str.translate(None) to mean identity translation References: <4272e00c.260731842@news.oz.net> <1114835238.762478.236940@o13g2000cwo.googlegroups.com> Message-ID: <42732ed7.280902606@news.oz.net> On 29 Apr 2005 21:27:18 -0700, "M.E.Farmer" wrote: >Bengt Richter wrote: >> Just thought None as the first argument would be both handy and >mnemonic, >> signifying no translation, but allowing easy expression of deleting >characters, >> e.g., >> >> s = s.translate(None, 'badcharshere') >> >> Regards, >> Bengt Richter > >What's wrong with : > >s = s.replace('badchars', "") That's not what translate does with the badchars, which is a set of characters, each and all of whose instances in the source string will be deleted from the source string. Something like for c in badchars: s = s.replace(c,'') > >It seems obvious to replace a char ( to me anyway ) with a blank >string, rather than to 'translate' it to None. >I am sure you have a reason what am I missing ? >M.E.Farmer The first argument is normally a 256-character string that serves as a table for converting source characters to destination, so s.translate(table, bad) does something like s = ''.join([table[ord(c)] for c in s if c not in bad] >>> help(str.translate) Help on method_descriptor: translate(...) S.translate(table [,deletechars]) -> string Return a copy of the string S, where all characters occurring in the optional argument deletechars are removed, and the remaining characters have been mapped through the given translation table, which must be a string of length 256. So just to delete, you wind up constructinf a table argument that is just 1:1 as in >>> 'abcde'.translate(''.join([chr(i) for i in xrange(256)]), 'tbd') 'ace' and the answer to the question, "What translation does such a table do?" is "None" ;-) Regards, Bengt Richter From hmrosser at bellsouth.net Wed Apr 27 22:38:04 2005 From: hmrosser at bellsouth.net (Hal Rosser) Date: Wed, 27 Apr 2005 22:38:04 -0400 Subject: Problem with sending a variable(python) while using html References: <426fe1f8$0$636$ba624c82@nntp02.dk.telia.net> <426ff886$0$13746$ba624c82@nntp03.dk.telia.net> Message-ID: <3_Xbe.8981$lf2.6507@bignews6.bellsouth.net> append "&eventid=str(variable_name)" to the url in the link The hidden field is not sent unless the form is submitted. If you use the link - you send the data appended to the url "Hansan" wrote in message news:426ff886$0$13746$ba624c82 at nntp03.dk.telia.net... > Hi. > > Sorry forgot to post a "non-working" example > > That could be > print "", "some text" type=hidden name="eventid" value='''+str(variable_name)+'''>'''" > > I know that it isnt very creative, but I am having a hard time getting html > to work together with python. > > When the link "some text" is clicked I want to send both the first variable > called variable and the second one(variable_name) to the script (script.py) From max at alcyone.com Tue Apr 12 23:03:15 2005 From: max at alcyone.com (Erik Max Francis) Date: Tue, 12 Apr 2005 20:03:15 -0700 Subject: templating system In-Reply-To: References: Message-ID: <196dnbltDvtpFsHfRVn-uA@speakeasy.net> Ksenia Marasanova wrote: > Thanks! > > I've read "Known issues and caveats" on the website: > > """ > EmPy was primarily intended for static processing of documents, > rather than dynamic use, and hence speed of processing was not the > primary consideration in its design. > """ > > Have you noticed any speed problems with EmPy? In the interests of full disclosure, I'm the author of EmPy. All I meant by that note was that EmPy was not primarily designed for blazing speed; that is, it could easily be made much more efficient in a lot of ways. I've never had a need to do so, so it's always been low priority. I've certainly never heard of any complaints of EmPy's speed (or lack therefore) as being a problem in the field. Unless you huge realtime demands, I doubt EmPy's speed would be a major impediment. (Of course, if you find that it is, please tell me!) -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis A wise man never loses anything if he have himself. -- Montaigne From fred.dixon at gmail.com Wed Apr 13 10:44:11 2005 From: fred.dixon at gmail.com (fred.dixon) Date: 13 Apr 2005 07:44:11 -0700 Subject: sort of a beginner question about globals In-Reply-To: <3aOdnX8D67t5PcHfRVn-qQ@comcast.com> References: <1113354531.380490.81190@z14g2000cwz.googlegroups.com> <3aOdnX8D67t5PcHfRVn-qQ@comcast.com> Message-ID: <1113403451.556360.116630@f14g2000cwb.googlegroups.com> I want to use OPTIONS as a global var. In this particular case I am trying to set a global debug constant so I can have some debug logging happen when my program is run with a -debug option. what will actuall end up in OPTIONS is OPTIONS.debug = True as i am using optparse module. From fuzzyman at gmail.com Fri Apr 29 09:30:30 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 29 Apr 2005 06:30:30 -0700 Subject: [ANN] Voidspace Python Guestbook 1.4.1 (etc) Message-ID: My Honoured Guests ===================== Yup... the time has come, **The Voidspace Python Guestbook 1.4.1** has been released into the wild. * `The Guestbook Homepage`__ * `Quick Download Link (120k)`__ * `Plain Guestbook Example`__ * `Voidspace Guestbook`__ [#]_ __ http://www.voidsapce.org.uk/python/guestbook.html __ http://www.voidsapce.org.uk/cgi-bin/voidspace/downman.py?file=guestbook.zip __ http://www.voidsapce.org.uk/cgi-bin/voidspace/guestbook.py __ http://www.voidsapce.org.uk/cgi-bin/voidspace/guestbook2.py What is the Voidspace Python Guestbook ======================================== Guestbook is a Python script that allows you to add a 'guestbook' facility to your website. It is fully customisable using HTML templates - so the guestbook will appear to be fully integrated with your website. The entries are saved in a plain text file, for easy editing, and there is a naughty word filter as well. Almost every aspect of the appearance is editable using the templates. A few other user settings can be configured as well. All the instructions are contained in the template file. It can email you when an entry is made by someone, and also features smilies, spam protection, javascript form validation, and allows a limited set of html in comments. It is regularly improved and updated. What's New ? =============== This is a major update since the last release [#]_. The new features are : * Javascript form validation (client side) * More advanced anti-spam features (we do a basic check that the entry was made by a human rather than a bot) * A limited set of html is now allowed in entries * Smilies !!!! * Better use of CSS in the standard template * Counter tells you how many times the guestbook has been viewed * A few other bugfixes and improvements Because of the changes there are a few external files (python modules and javascript files) that will need to be installed, as well as the smiley images. Full instructions come with the docs. .. [#] Using the HTML templates .. [#] Version 1.3.0 was the last released version. 1.4.0 did exist for a few days before it was superceded..... *Also*... FireMail the firedrop plugin has been updated. It now resolves the macros before emailing. The plugin.zip also now contains rest.py (reST support for firedrop) which has also been updated, and the update isn't yet included in the official distribution. See http://www.voidspace.org.uk/python/programs.shtml#firedrop *Also*.... A couple of new 'recipes' that *may* be of interest. googlerank How Well Ranked is Your Website ? Version 0.1.0 18th April 2005 googlerank is a small recipe that uses the google api. You give it a domain (by setting a variable), and then a set of search terms via stdin. It then does google searches until a result from your domain is found (so long as it is within the first 200 results - 20 searches). This tells you how far down the list your site appears for given search terms. This is a useful tool for working with website design - it's also very interesting. It produces results that look like : For the search term "python cookies" : Out of an estimated 176000 results. Your website came at position "7". With URL - "http://www.voidspace.org.uk/python/recipebook.shtml" see : http://www.voidspace.org.uk/python/recipebook.shtml#google CGIHTTPServerWithSSI A Simple Server with SSI Processing Version 0.1.0 15th April 2005 This is a simple server implementation, this one based on CGIHTTPServer. It does everything that CGIHTTPServer does, with some SSI processing as well. So far it handles include and flastmod, but adding additional instructions would be easy. Simply drop it in a directory and it will serve webpages, with that directory as the root directory. Any pages that end in .shtml or .shtm, it does SSI processing on. see : http://www.voidspace.org.uk/python/recipebook.shtml#ssi Best Regards, Fuzzy http://www.voidspace.org.uk/py?thon From bokr at oz.net Sat Apr 2 21:58:58 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 03 Apr 2005 02:58:58 GMT Subject: redundant imports References: <86zmwgx0he.fsf@guru.mired.org> Message-ID: <424f52e2.157933225@news.oz.net> On Sat, 02 Apr 2005 16:44:29 -0600, Mike Meyer wrote: >"max(01)*" writes: > >> Peter Hansen wrote: >>> max(01)* wrote: >>> >>>> hi everybody. >>>> >>>> suppose that code-1.py imports code-2.py and code-3.py (because it >>>> uses names from both), and that code-2.py imports code-3.py. >>>> >>>> if python were c, code-1.c should only *include* code-2.c, because >>>> the latter in turns includes code-3.c. >>>> >>>> inclusion of modules in c is a purely preprocessing textual matter >>>> (compilation is deferred to after the fact), i guess, so that such >>>> things are possible. import of modules in python is a different >>>> beast, so the "redundancy" is (i think) necessary. >>>> >>>> any comment/suggestion/idea? >>> You're mixed up about this whole idea. >>> >> >> that's why i am asking for advice here. >> my concern was motivated by a (clumsy) attempt to understand the >> difference of mechanism between the approach to modular programming in >> a more "traditional" language (c) and python. > >[Names changed to be valid python module names.] > >I feel I ought to point out that you don't really *have* to import the >code_3.py in code_1.py. You can get to things code_3.py in code_1.py >as code_2.code_3.. > >The semantic behavior of "include" in C is the same as "from module Bzzt ;-) It's not the same semantics! >import *" in python. Both cases add all the names in the included >namespace directly to the including namespace. This usage is But a C #include results in processing as if the _source_ were substituted into the including source in place of the #include line. That's not what from module import * does, because when import executes the module's source (happening only the first time BTW, unlike in-place #include) it creates a module global that is distinct from the includer's global. The import * creates local bindings to the objects visible as bindings in the global space of the module, but the objects retain their module global references (if any, since there doesn't have to be any). IMO execfile('module.py') is closer to C's #include effect. Note: >>> print '----\n%s----'%open('impex.py').read() ---- g = 'g in global space of impex.py' def showg(): print g ---- >>> from impex import * >>> g 'g in global space of impex.py' >>> showg() g in global space of impex.py >>> g = 'g in global space of importer' >>> g 'g in global space of importer' >>> showg() g in global space of impex.py Note that showg insisted on looking for g in it's idea of global. Now we'll bring in g and showg via execfile: >>> >>> execfile('impex.py') >>> g 'g in global space of impex.py' >>> showg() g in global space of impex.py >>> g = 'g in global space of importer' >>> showg() g in global space of importer Note that because execfile executed the definition of showg in the interactive global space, it sees the interactive change of g's binding (in what it now also showg's global space). (Execfile inside a function or class definition needs careful control, but can be done). >depreciated in Python, because it leads to problems figuring out where >a specific variable came from. In C, it creates a problem called "name >space pollution". This is the case when a file1.c gets all the symbols >for some_header.h, even though it doesn't include/need those symbols, >because some header file1.c included needed a symbol from >some_header.h. This is especially galling if the pollution collides >with some_header2.h that file1.c actually needs. > Of course in C you could write some #ifxxx kludges to control inclusion of named things from a given header file somewhat. But name space pollution is a pox, to be sure ;-) Regards, Bengt Richter From j.p.t.j.berends at [N0SP4M].nl Fri Apr 8 05:38:53 2005 From: j.p.t.j.berends at [N0SP4M].nl (J Berends) Date: Fri, 08 Apr 2005 11:38:53 +0200 Subject: 'Address already in use' when using socket In-Reply-To: References: <87wtretghg.fsf@gto.net> Message-ID: <9e7e6$4256511a$82a1a4df$15818@news1.tudelft.nl> Peter Hansen wrote: > Bearish wrote: > >> I get 'Address already in use' errors when using sockets. > > > Generally one can fix this using: > > sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) > > where "sock" is the server socket in question. Do > this prior to attempting to bind to the port. > > -Peter I agree on this, wanted to write the same thing when I saw this. From pinard at iro.umontreal.ca Thu Apr 14 10:07:25 2005 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Thu, 14 Apr 2005 10:07:25 -0400 Subject: Compute pi to base 12 using Python? In-Reply-To: References: <425cefae.268278123@news.oz.net> Message-ID: <20050414140725.GA17342@phenix.progiciels-bpi.ca> [Doug Schwarz] > The chromatic scale is based on one twelfth powers of two, i.e., if > the frequency of a note in the scale is f(n), then the frequency of > the next note is given by f(n+1) = f(n) * 2^(1/12) This easy view of things has been known for a long time, but has only been popular (relatively) recently. Traditionally, scale designers were definitely running after rational proportions between scale notes, not fearing some problems they necessarily create, because such scales are often nicer and interesting to the musical ear. I should relate this discussion to Python somehow! :-) Easy, as I have a few Python programs doing various scale computations -- I should try to bundle these together somewhere in my personal Web site, some day... -- Fran?ois Pinard http://pinard.progiciels-bpi.ca From u.hobelmann at web.de Fri Apr 1 16:59:38 2005 From: u.hobelmann at web.de (Ulrich Hobelmann) Date: Fri, 01 Apr 2005 15:59:38 -0600 Subject: Lambda: the Ultimate Design Flaw In-Reply-To: <1498066.d23UzBfE8y@yahoo.com> References: <1498066.d23UzBfE8y@yahoo.com> Message-ID: <3b5ui7F6h0vgtU1@individual.net> alex goldman wrote: > Daniel Silva wrote: > > >>At any rate, FOLD must fold. > > > I personally think GOTO was unduly criticized by Dijkstra. With the benefit > of hindsight, we can see that giving up GOTO in favor of other primitives > failed to solve the decades-old software crisis. The fault of goto in imperative languages is that it has no arguments, thus creating spaghetti of gotos and assignments. Continuations rule! From peter at engcorp.com Thu Apr 28 11:21:36 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 28 Apr 2005 11:21:36 -0400 Subject: anonymous functions/expressions without lambda? In-Reply-To: References: Message-ID: Paul Miller wrote: > For example, let's say I have a function which binds a key to a function > call. I want to do something "simple" in this function call, and I have > a lot of bindings, so I don't want to have a ton of tiny little > functions scattered around: > > def setVarTo1(): > foo.var = 1 > def setVarTo2(): > foo.var = 2 > > bind('a', setVarTo1) > bind('b', setVarTo2) > > Instead, I'd like to do something like this: > > bind('a', foo.var = 1) > bind('b', foo.var = 2) > > What's the recommended way to do something like this? This meets your requirements as stated: def temp(): foo.var = 1 bind('a', temp) def temp(): foo.var = 2 bind('b', temp) del temp -Peter From joal at bigpond.net.au Fri Apr 1 02:45:00 2005 From: joal at bigpond.net.au (Joal Heagney) Date: Fri, 01 Apr 2005 07:45:00 GMT Subject: New to programming question In-Reply-To: <1112325275.120122.100800@o13g2000cwo.googlegroups.com> References: <1112325275.120122.100800@o13g2000cwo.googlegroups.com> Message-ID: <0_63e.19914$C7.11056@news-server.bigpond.net.au> Ben wrote: > This is an exercise from the Non-programmers tutorial for Python > by Josh Cogliati. > > The exercise is: > > Write a program that has a user guess your name, but they only get 3 > chances to do so until the program quits. > > Here is my script: > > -------------------------- > > count = 0 > name = raw_input("Guess my name. ") > > while name != 'Ben' and count < 3: Everything inside this loop will only occur if the name doesn't equal 'Ben' and the count is less than 3. > count = count + 1 You increase the count by one, which allows your code to catch the case where count = 2 and now equals 3. > if name != 'Ben' and count < 3: > name = raw_input('Guess again. ') > elif name == 'Ben' and count < 3: > print "You're right!" > else: > print 'No more tries.' Which is why you get this print message, because count is now equal to 3. > > ---------------------------------- > > Everything works except the line: print "You're right!" But at no point does the program get an opportunity to print "No more tries.' because there is no point inside this loop where name == 'Ben'. > Could someone tell me what is wrong and give me a better alternative to > what I came up with. > > Thank you > > Ben Also, you're duplicating a lot of your case testing. You check to see if the name is 'Ben' at the start, and then inside the loop, and the same for the counts. I tried to write out a logical method of approaching this problem, but in truth this particular use-case isn't that simple is it? Here's my contribution anycase: count = 0 # Get first input name = raw_input("Guess my name: ") # Give the sucker two extra goes while count < 2: # Check the value of name if name == 'Ben': print "You're right!" break else: name = raw_input("Try again: ") # Of course, we haven't checked the sucker's last guess # so we have to do that now. if count == 2: if name == 'Ben': print "You're right!" else: print "No more tries for you!!!" Hope this helps. Joal From mal at egenix.com Thu Apr 7 15:17:51 2005 From: mal at egenix.com (M.-A. Lemburg) Date: Thu, 07 Apr 2005 21:17:51 +0200 Subject: oracle interface In-Reply-To: References: Message-ID: <4255875F.8030600@egenix.com> Andrew Dalke wrote: > In searching I find there several different ways to > connect to an Oracle server on MS Windows: > > mxODBC - http://www.egenix.com/files/python/mxODBC.html > built on top of the ODBC drivers for a given database mxODBC works nicely with Oracl on Windows. There are two options: 1. MS Oracle ODBC driver: This is the MS version of an ODBC driver for Oracle. It is well integrated into MS transaction managers, authentication and other MS techniques, but doesn't support all the the 8i and 9i features. 2. Oracle ODBC driver: This driver is supported by Oracle itself and does have support for 8i and 9i. If these don't work for you, there are also a number of commercial ODBC driver kits which support Oracle from the usual suspects (OpenLink, EasySoft, DataDirect, etc.). Usage is pretty straightforward: a) install the ODBC driver b) create an ODBC data source (this connects the ODBC driver with the database you want to talk to) c) install egenix-mx-base and egenix-mx-commercial d) fire up Python... from mx.ODBC.Windows import DriverConnect dbc = DriverConnect("DSN=;UID=;PWD=") c = dbc.cursor() c.execute('select * from mytable') print c.fetchall() If you like it, contact sales at egenix.com and we'll let you know what else is needed :-) -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Apr 07 2005) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ ::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,FreeBSD for free ! :::: From bgs248 at hotmail.com Sat Apr 30 15:32:31 2005 From: bgs248 at hotmail.com (bgs) Date: 30 Apr 2005 12:32:31 -0700 Subject: array type casting problem in scipy.interpolate References: <42732655@news.ColoState.EDU> Message-ID: <1114889551.101190.312080@l41g2000cwc.googlegroups.com> The routine requires real arrays, and you are giving it one complex one. It does not know what to do with the complex array. What are you expecting it to do? If you need the real and imaginary parts to be separately interpolated, then split the complex array into two real arrays and use the routine twice. From mauriceling at acm.org Tue Apr 26 17:33:28 2005 From: mauriceling at acm.org (Maurice LING) Date: Wed, 27 Apr 2005 07:33:28 +1000 Subject: bytecode non-backcompatibility References: <1114418065.581779.52480@l41g2000cwc.googlegroups.com> Message-ID: Terry Reedy wrote: > "Maurice LING" wrote in message > news:d4kh4q$tqf$1 at domitilla.aioe.org... > > >>Now I understand that Python bytecodes are only dealing with pure python >>source codes. > > > Then stop blaming (machine-independent) CPython 'bytecodes' for any > problems you have with compiled-to-machine-language C extensions, which > have nothing to do with bytecodes. Bytecodes also have nothing directly to > do with source-code compatibility. > > > technicalities are wrong but situation remains unchanged. maurice From bokr at oz.net Thu Apr 21 13:26:40 2005 From: bokr at oz.net (Bengt Richter) Date: Thu, 21 Apr 2005 17:26:40 GMT Subject: Enumerating formatting strings References: <3cm9r2F6nif67U1@individual.net> <42660fc2.42093557@news.oz.net> <42662dc9.49780670@news.oz.net> Message-ID: <4267dc41.159980529@news.oz.net> On Wed, 20 Apr 2005 17:09:16 -0700, Michael Spencer wrote: >Andrew Dalke wrote: > >> I see you assume that only \w+ can fit inside of a %() >> in a format string. The actual Python code allows anything >> up to the balanced closed parens. >> >Gah! I guess that torpedoes the regexp approach, then. > >Thanks for looking at this > I brute-forced a str subclass that will call a mapping object's __getitem__ for both kinds of format spec and '*' specs. Just to see what it would take. I didn't go the whole way loking for a __format__ method on the mapping object, along the lines I suggested in a previous post. Someone else's turn again ;-) This has not been tested thoroughly... The approach is to scan the original format string and put pieces into an out list and then ''.join that for final ouput. The pieces are the non-format parts and string from doing the formatting as formats are found. %(name) format args are retrieved from the mapping object by name as usual, and saved as the arg for rewritten plain format made from the tail after %(name), which is the same tail as %tail, except that the value is already retrieved. Next '*' or decimal strings are packed into the rewritten format, etc. The '*' values are retrieved by integer values passed to mapobj[i] and incremented each time. If the arg value was not retrieved by name, that's another mapobj[i]. Then the conversion is done with the plain format. The tests have MixFmt(fmt, verbose=True) % MapObj(position_params, namedict) and the verbose prints each rewritten format and arg and result as it appends them to out. ----< mixfmt.py >------------------------------------------------------------------------ # mixfmt.py -- a string subclass with __mod__ permitting mixed '%(name)s %s' formatting import re class MixFmtError(Exception): pass class MixFmt(str): def __new__(cls, s, **kw): return str.__new__(cls, s) def __init__(self, *a, **kw): self._verbose = kw.get('verbose') # Michael Spencer's regex, slightly modded, but only for reference, since XXX note parse_format = re.compile(r''' ( \% # placeholder (?:\(\w*\))? # 0 or 1 "named" groups XXX "%( (any)(balanced) parens )s" is legal! [\#0\-\+]? # 0 or 1 conversion flags (?:\* | \d+)? # optional minimum conversion width (?:\.\* | \.\d+)? # optional precision [hlL]? # optional length modifier [diouxXeEfFgGcrs] # conversion type - note %% omitted ) ''', re.VERBOSE) def __mod__(self, mapobj): """ The '%' MixFmt string operation allowing both %(whatever)fmt and %fmt by calling mapobj[whatever] for named args, and mapobj[i] sequentially counting i for each '*' width or precision spec, and unnamed args. It is up to the mapobj to handle this. See MapObj example used in tests. """ out = [] iarg = 0 pos, end = 0, len(self) sentinel = object() while pos=0 and self[pos:pos+2] == '%%': pos+=2 pos = self.find('%', pos) if pos<0: out.append(self[last:].replace('%%','%')); break # here we have start of fmt with % at pos out.append(self[last:pos].replace('%%','%')) last = pos plain_arg = sentinel pos = pos+1 if self[pos]=='(': # scan for balanced matching ')' brk = 1; pos+=1 while brk>0: nextrp = self.find(')',pos) if nextrp<0: raise MixFmtError, 'no match for "(" at %s'%(pos+1) nextlp = self.find('(', pos) if nextlp>=0: if nextlp %r %% %r => %r' % (plain_fmt, (plain_arg,), result) out.append(result) return ''.join(out) class MapObj(object): """ Example for test. Handles both named and positional (integer) keys for MixFmt(fmtstring) % MapObj(posargs, namedict) """ def __init__(self, *args, **kw): self.args = args self.kw = kw def __getitem__(self, i): if isinstance(i, int): return self.args[i] else: try: return self.kw[i] except KeyError: return ''%i def test(fmt, *args, **namedict): print '\n==== test with:\n %r\n %s\n %s' %(fmt, args, namedict) print MixFmt(fmt, verbose=True) % MapObj(*args, **namedict) def testseq(): test('(no %%)') test('%s', *['first']) test('%(sym)s',**dict(sym='second')) test('%s %*.*d %*s', *['third -- expect " 012 ab" after colon:', 5, 3, 12, 4, 'ab']) test('%(arg1)s %% %(arg2).*f %()s %s', *[3, 'last'], **{ 'arg1':'fourth -- expect " % 2.220 NULL? last" after colon:', 'arg2':2.22, '':'NULL?'}) #'%s %*.*d %*s', *['expect " 345 ab"??:', 2, 1, 12345, 4, 'ab']) test('fifth -- non-key name: %(this(is)a.--test!)s') if __name__ == '__main__': import sys if not sys.argv[1:]: raise SystemExit,'Usage: python24 mixfmt.py -test | fmt ([key =] (s | (-i|-f) num)+ )*' fmt, rawargs = sys.argv[1], iter(sys.argv[2:]) if fmt == '-test': testseq(); raise SystemExit args = [] namedict = {}; to_name_dict=False for arg in rawargs: if arg == '-i': arg = int(rawargs.next()) if arg == '-f': arg = float(rawargs.next()) if arg == '=': to_name_dict = True elif to_name_dict: namedict[args.pop()] = arg; to_name_dict=False else: args.append(arg) test(fmt, *args, **namedict) ----------------------------------------------------------------------------------------- Result of py24 mixfmt.py -test: [10:06] C:\pywk\pymods>py24 mixfmt.py -test ==== test with: '(no %%)' () {} (no %) ==== test with: '%s' ('first',) {} -> '%s' % ('first',) => 'first' first ==== test with: '%(sym)s' () {'sym': 'second'} -> '%s' % ('second',) => 'second' second ==== test with: '%s %*.*d %*s' ('third -- expect " 012 ab" after colon:', 5, 3, 12, 4, 'ab') {} -> '%s' % ('third -- expect " 012 ab" after colon:',) => 'third -- expect " 012 ab" after colon:' -> '%5.3d' % (12,) => ' 012' -> '%4s' % ('ab',) => ' ab' third -- expect " 012 ab" after colon: 012 ab ==== test with: '%(arg1)s %% %(arg2).*f %()s %s' (3, 'last') {'': 'NULL?', 'arg1': 'fourth -- expect " % 2.220 NULL? last" after colon:', 'arg2': 2.2200000 000000002} -> '%s' % ('fourth -- expect " % 2.220 NULL? last" after colon:',) => 'fourth -- expect " % 2.220 NULL? last" after colon:' -> '%.3f' % (2.2200000000000002,) => '2.220' -> '%s' % ('NULL?',) => 'NULL?' -> '%s' % ('last',) => 'last' fourth -- expect " % 2.220 NULL? last" after colon: % 2.220 NULL? last ==== test with: 'fifth -- non-key name: %(this(is)a.--test!)s' () {} -> '%s' % ("",) => "" fifth -- non-key name: You can also run it interactively with one format and some args, e.g., [10:25] C:\pywk\pymods>py24 mixfmt.py Usage: python24 mixfmt.py -test | fmt ([key =] (s | (-i|-f) num)+ )* [10:25] C:\pywk\pymods>py24 mixfmt.py "%*.*f %(hi)s" -i 6 -i 3 -f 3.5 hi = hello ==== test with: '%*.*f %(hi)s' (6, 3, 3.5) {'hi': 'hello'} -> '%6.3f' % (3.5,) => ' 3.500' -> '%s' % ('hello',) => 'hello' 3.500 hello Regards, Bengt Richter From codecraig at gmail.com Thu Apr 21 12:54:41 2005 From: codecraig at gmail.com (codecraig) Date: 21 Apr 2005 09:54:41 -0700 Subject: Regular Expressions - Python vs Perl In-Reply-To: References: <1114092105.964664.211430@l41g2000cwc.googlegroups.com> <1114098472.768814.281750@g14g2000cwa.googlegroups.com> Message-ID: <1114102481.963973.252500@g14g2000cwa.googlegroups.com> I found some benchmarking (perhaps simple) but search for "The Great Computer language shootout" ....look at the original shootout and the win32 one. Thomas: "I doubt the total execution time for all the RegEx queries you ever ran took as much time as you just wasted on your little experiment. " .....no need to be angry. I don't have some "little experiment", but thanks for being concerned about me wasting my time. I do understand that python is certainly easier to read, no doubt. I was just doing some research to find out about speed/performance between the two. But thanks for pointing out, again, that Pyton is easier to read. (let's just not forget that python is great for other things other than just readability.) From claudio.grondi at freenet.de Tue Apr 26 08:28:56 2005 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Tue, 26 Apr 2005 12:28:56 -0000 Subject: from comp.ai.vision - beside C also Python code included Message-ID: <3d6jgjF6i2pvtU1@individual.net> From: Thomas Deselaers Subject: Q&A : FIRE (Flexible Image Retrieval Engine) sources available FIRE is an extensible image retrieval engine that was developed to investigate the impact of different features for content-based image retrieval. The system was used in the 2004 ImageCLEF evaluation and obtained the best results for the medical task using only visual information. The system also gives very good results for general color photographs using invariant color features and Tamura texture histograms. FIRE contains lots of different feature extraction tools, distance measures, and tools for performance evaluation. The source code, a demo, and further information about FIRE is available online at http://www-i6.informatik.rwth-aachen.de/~deselaers/fire.html From greg at cosc.canterbury.ac.nz Wed Apr 20 01:53:00 2005 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Wed, 20 Apr 2005 17:53:00 +1200 Subject: def a((b,c,d),e): In-Reply-To: <1113854757.229118.137260@g14g2000cwa.googlegroups.com> References: <1113854757.229118.137260@g14g2000cwa.googlegroups.com> Message-ID: <3cm929F64ls55U1@individual.net> AdSR wrote: > if you haven't done so yet. It appears that you can specify a function > explicitly to take n-tuples as arguments. > > Has anyone actually used it in real code? Yes. In PyGUI I have some point and rectangle manipulation utilities that do things like def add_pt((x1, y1), (x2, y2)): return (x1 + y1, x2 + y2) In cases like this, it can help to make things more concise and probably also slightly more efficient. > it looks like one of those language features that make > committing atrocities an order of magnitude easier. I don't remember ever being seriously burned by using it. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From bokr at oz.net Thu Apr 7 20:55:41 2005 From: bokr at oz.net (Bengt Richter) Date: Fri, 08 Apr 2005 00:55:41 GMT Subject: How to name Exceptions that aren't Errors References: <3blfl8F6gt80jU1@individual.net> Message-ID: <4255d539.584516580@news.oz.net> On Thu, 07 Apr 2005 15:40:24 -0400, Steve Holden wrote: >Leo Breebaart wrote: >> I've recently become rather fond of using Exceptions in Python to >> signal special conditions that aren't errors, but which I feel >> are better communicated up the call stack via the exception >> mechanism than via e.g. return values. >> >Absolutely. > >> For instance, I'm thinking of methods such as: >> >> >> def run(self): >> """ Feed the input file to the simulator. """ >> >> for linenr, line in enumerate(self.infile): >> try: >> current_values = self.parse_line(linenr, line) >> ==> except CommentLineException: >> continue >> results = self.do_one_simulation_step(current_values) >> self.process_simulation_results(results) >> >> >> which I use in order to discard comments from a file I'm parsing >> line-by-line. It also possible for exception arguments to deliver a result, rather than indicate something rejected. E.g., you can terminate a recursive search via an exception. If no exception occurs, you have gone through the entire search space and not met the solution criterion. Regards, Bengt Richter From jepler at unpythonic.net Thu Apr 7 12:11:04 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 7 Apr 2005 11:11:04 -0500 Subject: Read 16 bit integer complex data In-Reply-To: <1112887876.272539.277420@z14g2000cwz.googlegroups.com> References: <1112887876.272539.277420@z14g2000cwz.googlegroups.com> Message-ID: <20050407161103.GG12835@unpythonic.net> You may want to use the 'numeric' or 'numarray' extensions for this. The page on numarray is here: http://www.stsci.edu/resources/software_hardware/numarray numarray doesn't support "complex 16-bit integer" as a type, but you can get a complex, floating-point valued array from your integer values. Here's how, with a bit of explanation along the way: I created a small example: a vector of 2 "complex 16-bit integers" in the native byte-order. >>> s = struct.pack("hhhh", 1, 2, 3, 4) >>> s '\x01\x00\x02\x00\x03\x00\x04\x00' I think this stands for the vector <1+2j, 3+4j> according to what you wrote. I can turn this into a 4-element numarray like so: >>> numarray.fromstring(s, "s") array([1, 2, 3, 4], type=Int16) and extract the real and complex parts with extended slices: >>> t[1::2] # take the items 1, 3, ..., 2*n+1 i.e., the complex parts array([2, 4], type=Int16) This expression forms the complex 64-bit floating point 2-element array from 't': >>> u = t[0::2] + t[1::2] * 1j >>> u array([ 1.+2.j, 3.+4.j]) If the byte-order of the file is different from the native byte order, you can byte-swap it before forming the complex FP array: >>> t.byteswap() >>> t array([ 256, 512, 768, 1024], type=Int16) Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From mauriceling at acm.org Thu Apr 28 22:47:12 2005 From: mauriceling at acm.org (Maurice LING) Date: Fri, 29 Apr 2005 12:47:12 +1000 Subject: New Python website References: <1114735502.510591.6360@f14g2000cwb.googlegroups.com> Message-ID: Michael Soulier wrote: > On 28 Apr 2005 17:45:02 -0700, lpe wrote: > >>http://www.pycode.com >> >>I was kinda suprised when I could not find any good sites with 3rd >>party modules (other than the Vaults of Parnassus, where you must host >>files elsewhere), so I decided to write one myself :) >>It is brand new and might still be buggy, but hopefully it will be >>usefull to some people. Feel free to join and upload any of your code. >>thanks > > > Something wrong with PyPi? > > Mike > I think it is quite clear when he says "I could not find any good sites with 3rd party modules (other than the Vaults of Parnassus, where you must host files elsewhere)", suggesting that he is looking for a site whereby 3rd party modules can be hosted, rather than a site telling you where 3rd party modules are hosted. maurice From mwm at mired.org Mon Apr 25 10:15:36 2005 From: mwm at mired.org (Mike Meyer) Date: Mon, 25 Apr 2005 09:15:36 -0500 Subject: what is the best way to determine system OS? References: <1114436211.942212.203790@f14g2000cwb.googlegroups.com> Message-ID: <868y37osc7.fsf@guru.mired.org> "googleboy" writes: > Hi there. > > I am writing a little app tha tI would like to make cross-platform > (debian, RH, Fedora, Solaris, AIX, etc) > > Originally I decided to check what uname returned, as I didn't think it > mattered beyond the detail of Linux or SunOS etc. > > Recently I have learned that FC3 breaks my script, so I need to be > able to determine not simply "Linux" but to know exactly what unix the > script is being run on. Anyway, checking the system name is the wrong way to build portable programs. For one thing, as you've discovered, new systems won't work properly. For another, upgrades to existing systems may break things as well. What you should do instead is check on how to use the features you want. If you watch a typical autoconf script, you'll see it groveling through libraries, include files, and various directories looking for subroutines, defines and commands. That's the idea, but without knowing which features you're looking for, I can't say how you would check for them. This takes more time to write, but results in more robust code. For instance, if some distribution changes one of the features to mimic a "better" distribution that you already support, instead of your script breaking, it'll just work. This is much better than having to teach your script how to distinguish between versions of distributions. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From martin at v.loewis.de Sun Apr 24 12:18:34 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 24 Apr 2005 18:18:34 +0200 Subject: Unicode problems, yet again In-Reply-To: References: <171m61pido84fckea94h8231j8n077qt8k@4ax.com> Message-ID: <426bc6db$0$10299$9b622d9e@news.freenet.de> Ivan Voras wrote: > Sorry, that was just steam venting from my ears - I often get bitten by > the "ordinal not in range(128)" error. :) I think I'm glad to hear that. Errors should never pass silently, unless explicitly silenced. When you get that error, it means there is a bug in your code (just like a ValueError, a TypeError, or an IndexError). The best way to deal with them is to fix them. Now, the troubling part is clearly that you are getting *bitten* by this specific error, and often so. I presume you get other kinds of errors also often, but they don't bite :-) This suggests that you should really try to understand what the error message is trying to tell so, and what precisely the underlying error is. For other errors, you have already come to an understanding what they mean: NameError, ah, there must be a typo. AttributeError on None, ah, forgot to check for a None result somewhere. ordinal not in range(128), hmm, let's try different variations of the code and see which ones work. This is going to continue biting you until you really understand what it means. The most "sane" mental model (and architecture) is one where you always have Unicode strings in your code, and decode/encode only at system interfaces (sockets, databases, ...). It turns out that the database you use already follows this strategy (i.e. it decodes for you), so you now only need to design the other interfaces so it is clear when you have Unicode characters and when you have bytes. Regards, Martin From anthra.norell at tiscalinet.ch Sat Apr 30 17:19:00 2005 From: anthra.norell at tiscalinet.ch (Anthra Norell) Date: Sat, 30 Apr 2005 23:19:00 +0200 Subject: Data smoothing algorithms? - Thank you all References: <000c01c54c38$313eb580$0201a8c0@mcuf7> Message-ID: <00a201c54dca$3a936d40$0201a8c0@mcuf7> Thank you all for your solutions! The moving average filter will surely do. I will take a closer look at SciPy, though. The doc is impressive. I believe it's curve fitting I am looking for rather than interpolation. There's a chapter on that too. Frederic ----- Original Message ----- From: "Larry Bates" Newsgroups: comp.lang.python To: Sent: Friday, April 29, 2005 9:02 PM Subject: Re: Data smoothing algorithms? > Sounds like what you are looking for is spline interpolation. > Given a set of datapoints is passes spline curves through > each point giving you smooth transitions. Did a lot of this > in Fortran MANY years ago. > > Google turned up: > > http://www.scipy.org/documentation/apidocs/scipy/scipy.interpolate.html > > http://cmp.felk.cvut.cz/~kybic/thesis/pydoc/bigsplines.html > > http://www.mirror5.com/software/plotutils/plotutils.html > > Good Luck > Larry Bates > > John J. Lee wrote: > > "Anthra Norell" writes: > > > > > >>Hi, > >> > >>The following are differences of solar declinations from one day to > >>the next, (never mind the unit). Considering the inertia of a > >>planet, any progress of (apparent) celestial motion over regular > >>time intervals has to be highly regular too, meaning that a plot > >>cannot be jagged. The data I googled out of Her Majesty's Nautical > >>Almanac are merely nautical precision and that, I suppose, is where > >>the jitter comes in. There's got to be algorithms out there to iron > >>it out. If it were a straight line, I could do it. But this, over > >>the whole year, is a wavy curve, somthing with a dominant sine > >>component. Suggestions welcome. > > > > > > The important thing is to have a (mathematical, hopefully) model of > > how you expect the data to vary with time. Start from there, and > > then, for example, use regression to fit a curve to the data. > > > > The "Numerical Recipes" (Press et al.) book is popular and IMHO is a > > good place to learn about these things (comes in several language > > flavours, including Fortran and C -- sadly no Python AFAIK), though > > the implementations aren't a great choice for serious "production" > > use, according to those in the know. > > > > OTOH, there are quick and dirty methods that don't involve any model > > worth speaking of -- and Press et al. covers those too :-) > > > > > > John > > > -- > http://mail.python.org/mailman/listinfo/python-list From bokr at oz.net Tue Apr 19 01:02:10 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 19 Apr 2005 05:02:10 GMT Subject: pre-PEP: Suite-Based Keywords References: Message-ID: <42648ee7.317700188@news.oz.net> On Mon, 18 Apr 2005 14:06:08 -0700, "Robert Brewer" wrote: >Reinhold Birkenfeld wrote: >> >y =3D (f(11, 22, x=3D1, y=3D'y for f') * >> > g(*args_from_somewhere, >> > x=3D'x for g', y=3D'y for g', >> > foo=3Dlambda: return 'foo for g')) >> > >> >would be my current way to express this. But still, the less lines, >> >the less confusing it is. > >And Ron Adam replied: >> I would probably do it this way. >>=20 >> y =3D f(11, 22, x=3D1, y=3D'y for f') \ >> * g( *args_from_somewhere, >> x=3D'x for g',=20 >> y=3D'y for g', >> foo=3Dlambda: return 'foo for g' ) > >Which are both prettier, until you actually try to use them: > >>>> g( *args_from_somewhere, x=3D'x for g', y=3D'y for g', foo=3Dlambda: >return 'foo for g' ) >Traceback ( File "", line 1 > g( *args_from_somewhere, x=3D'x for g', y=3D'y for g', foo=3Dlambda: >return 'foo for g' ) > ^ >SyntaxError: invalid syntax > > I had a bug too ;-/ No returns in lambda ;-) Other than that, it compiles, so I suspect the visual structure helped, even if not so pretty. Regards, Bengt Richter From greg at cosc.canterbury.ac.nz Tue Apr 19 22:24:56 2005 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Wed, 20 Apr 2005 14:24:56 +1200 Subject: eval function not working how i want it dag namn In-Reply-To: <1113608512.081043.168400@g14g2000cwa.googlegroups.com> References: <1113567261.483667.198430@z14g2000cwz.googlegroups.com> <1113608512.081043.168400@g14g2000cwa.googlegroups.com> Message-ID: <3clssbF6p180fU1@individual.net> robcarlton wrote: > thanks. I'll use the getattr function now, and I think I understand > where I went wrong with eval. I was thinking in Lisp where the lexical > scope would mean that obj is defined The full story is actually more subtle. The name 'obj' *is* accessible from a nested scope if you do something like def f(obj): def g(): print obj g() But the bytecode compiler has to do extra work to make a name in an intermediate scope accessible to an inner scope, and it only does this if it sees a reference to the name in the inner scope. In your code, the reference is invisible at compile time, so the compiler misses it, and the run-time evaluation fails. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From jhargraveiii at msn.com Fri Apr 1 23:12:15 2005 From: jhargraveiii at msn.com (Jim Hargrave) Date: Fri, 01 Apr 2005 23:12:15 -0500 Subject: Python plug-in Frameworks like Eclipse RCP... In-Reply-To: References: Message-ID: Hum, maybe my question was too specific. What I would really like to know is what is the best way to implement a Python application with a pluggable architecture. In particular, I would like to use wxPython and have plug ins automatically register themselves with the GUI by adding themselves to the mean or adding a tab. Again this is much like Eclipse RCP - but forget that part :-) J Jim Hargrave wrote: > Eclipse provides a very nice application framework which supports > plug-ins. It's easy to dynamically add new functionality, menu items, > property editors, options etc.. using a combination of XML and Java code. > > Is there a similar framework for Python? If not any hints on how such a > framework would be implemented? > > I'm building a client side tool using Python/wxPython for our > translators and would like to have a pluggable architecture similar to > Eclipse RCP > > > thanks! From kkrueger at example.edu Thu Apr 21 20:33:00 2005 From: kkrueger at example.edu (Karl A. Krueger) Date: Fri, 22 Apr 2005 00:33:00 +0000 (UTC) Subject: Regular Expressions - Python vs Perl References: <1114092105.964664.211430@l41g2000cwc.googlegroups.com> Message-ID: Terry Reedy wrote: > Depending upon you particular application, 'completeness' may be a > more relevant concern than 'performance'. I believe the original > Python regex engine did not have all the Perl extensions, some of them > decidedly 'non regular'. It was replace by the 'perl-compatible regex > engine' (pcre or pre), written in C by a non-pythonista so that other > languages/applications, like Python, could drop it in and have what > the title claimed -- perl-like re capability. By way of comparison, there do exist at least some Perl-compatible regex libraries in other non-Perl languages, which don't use libpcre. An example is CL-PPCRE (http://www.weitz.de/cl-ppcre/), which claims to be "more compatible with the regex semantics of Perl 5.8.0 than, say, Perl 5.6.1 is." -- Karl A. Krueger { s/example/whoi/ } From harold.fellermann at upf.edu Wed Apr 6 14:11:08 2005 From: harold.fellermann at upf.edu (harold fellermann) Date: Wed, 6 Apr 2005 20:11:08 +0200 Subject: richcmpfunc semantics Message-ID: <52cccc58d7ef2924d653acaf1f8690f1@upf.edu> Hi all, I want to implement rich comparision in an extension class. Problem is I cannot find good documentation of the richcmpfunc semantics. Given the signature richcmpfunc compare(PyObject *,PyObject, int); I supposed the two objects passed are the ones to be compared. What is the meaning of the integer argument? Does it specify the kind of comparision operator (e.g. __eq__ or __le__), and if so, how? What is my richcmpfunc supposed to return? 0 or 1 indicating False or True? What has to be done, if the function is invoked for an operator I don't want to define? Maybe there is some good documentation available, but I cannot find it. So, any references or help is appreciated. Cheers, - harold - -- "Scientist are very good in answering the questions they choose to answer." -- Richard Alley From fuzzyman at gmail.com Tue Apr 5 11:14:43 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 5 Apr 2005 08:14:43 -0700 Subject: Python Google Server In-Reply-To: References: <1112696434.623557.97000@g14g2000cwa.googlegroups.com> <1112706994.922193.5610@z14g2000cwz.googlegroups.com> Message-ID: <1112714083.674249.44370@g14g2000cwa.googlegroups.com> Of course - sorry. Thanks for the fix. Out of interest - why are you using this... just for curiosity, or is it helpful ? Regards, Fuzzy http://www.voidspace.org.uk/python From gsakkis at rutgers.edu Sat Apr 2 13:23:53 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 2 Apr 2005 10:23:53 -0800 Subject: Decorater inside a function? Is there a way? References: Message-ID: <1112466233.403989.125810@l41g2000cwc.googlegroups.com> It turns out it's not a "how to inflate tires with a hammer" request; I've actually written an optional type checking module using decorators. The implementation details are not easy to grok, but the usage is straightforward: from typecheck import * @returns(listOf(int, size=3)) @expects(x=str, y=containerOf(int)) def foo(x,y): return [len(x)] + list(y) >>> foo('1',[2,3]) [1, 2, 3] >>> foo('1',(2,3)) [1, 2, 3] >>> foo(1,[2,3]) Traceback (most recent call last): ... TypeError: str expected (int given) >>> foo('1',[2,'3']) Traceback (most recent call last): ... TypeError: container expected ([2, '3'] given) >>> foo('1',[2,3,4]) Traceback (most recent call last): ... TypeError: container of size 3 expected ([1, 2, 3, 4] given) George From mehmetmutigozel at gmail.com Fri Apr 22 18:18:53 2005 From: mehmetmutigozel at gmail.com (mehmetmutigozel at gmail.com) Date: 22 Apr 2005 15:18:53 -0700 Subject: a=[ lambda t: t**n for n in range(4) ] In-Reply-To: <1114206105.666055.33720@g14g2000cwa.googlegroups.com> References: <1114206105.666055.33720@g14g2000cwa.googlegroups.com> Message-ID: <1114208333.622909.179640@l41g2000cwc.googlegroups.com> Thanx for your replies. I'm looking for array of functions. Something like a=[ sin(x) , cos(x) ] >>> x=0.0 >>> a [0, 1] >>> x=1.0 >>> a ... of course it can be made by >>> def cratearray(x): ... ~~~~ ... return a a=createarray(1.0) but this isn't what i am asking for. something automized. From cjbottaro at alumni.cs.utexas.edu Fri Apr 8 14:44:45 2005 From: cjbottaro at alumni.cs.utexas.edu (Christopher J. Bottaro) Date: Fri, 08 Apr 2005 13:44:45 -0500 Subject: base64 interoperability Message-ID: Python's base64 module encodes and decodes differently than PHP's. Python's docs says that it ahere's to RFC1521 (sept 1993), while PHP's adheres to RFC2045 (nov 1996). Is there any Python module that uses the new standard? Why is Python using the old standard anyways? Thanks. From tjreedy at udel.edu Fri Apr 1 11:28:44 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 1 Apr 2005 11:28:44 -0500 Subject: property and virtuality References: Message-ID: "harold fellermann" wrote in message news:d3322b8e9c17c6f6827db716cfbaac12 at upf.edu... > I asked this question some time ago, but as I got no answer, so I just > try it a second time. This did get out, but I can't answer except to suggest looking at code for other C extension modules. Nested (inner) classes are fairly rare, but I presume that once you know how to add attributes in general, you add class as an attribute in the same way you would add an int, etc, as an attribute. (And if I am wrong, you should certainly get another response '-). Terry J. Reedy From sabbey at u.washington.edu Sat Apr 16 17:01:56 2005 From: sabbey at u.washington.edu (Brian Sabbey) Date: Sat, 16 Apr 2005 14:01:56 -0700 Subject: pre-PEP: Suite-Based Keywords In-Reply-To: <3cc186F6lodv5U1@individual.net> References: <3cc186F6lodv5U1@individual.net> Message-ID: Reinhold Birkenfeld wrote: > Brian Sabbey wrote: >> Here is a pre-PEP for what I call "suite-based keyword arguments". The >> mechanism described here is intended to act as a complement to thunks. >> Please let me know what you think. >> >> Suite-Based Keyword Arguments >> ----------------------------- >> >> Passing complicated arguments to functions is currently awkward in Python. >> For example, the typical way to define a class property winds up polluting >> the class's namespace with the property's get/set methods. By allowing >> keyword arguments to be defined in a suite following a function call, >> complicated arguments can be passed in a cleaner, easier way. >> >> Examples >> ======== >> >> Using suite-based keyword arguments, the code >> >> f(x = 1) >> >> is equivalent to >> >> f(): >> x = 1 > > Pretty cool, but it interferes with current suites. > > How would you write > > if f(x=1): > print "yes" > > using suite-based keyword args? > > Reinhold > You wouldn't be able to use suite keywords in that situation. Also, one would not be able to use suite keywords when there is more than one function call on the same line: y = f()*g(): x = 1 # ?? not allowed There is only so much suites can do. Cases in which you want to do both are probably far enough between that it seems acceptable to me to require two suites: t = f(): x = 1 if t: y = 1 In general, I think that anything more than just a function call with an optional assignment should be disallowed: y = [f()]: # ? probably shouldn't be allowed x = 1 -Brian From ojokimu at yahoo.co.uk Thu Apr 28 16:44:13 2005 From: ojokimu at yahoo.co.uk (John Ridley) Date: Thu, 28 Apr 2005 21:44:13 +0100 (BST) Subject: kdialog and unicode Message-ID: <20050428204413.91626.qmail@web26810.mail.ukl.yahoo.com> Matt wrote: > Interesting - this displays correctly when I run the above code from a > python shell. However, when I run it as a superkaramba theme (which is > a wrapper interface to some kde functions, but allegedly passes > straight python functions direct to the python interpreter), it shows > up as letters, with &nnn (where nnn is a number) instead of the \xc4 > etc. I need to do some more investigating of this with the > superkaramba developers, and my own machine to see where the problem > lies - clearly it's not in the code I'm using - there's either > something wrong on my machine, or wrong with the way superkaramba > passes this code to the python interpreter. If xml character escapes are showing up in the output, it suggests the input is being treated as plain-text, rather than as rich-text (i.e. markup). In order for kdialog to guess that the input is markup, it needs to find some sort of tag before the first line-break. That is why I used P tags to enclose the polish text in my example - you didn't leave these off when you tried it out with superkaramba, did you? What exactly *is* the code you are running? BTW, if you want more details on kdialog's markup handling, try this reference from the qt docs: http://doc.trolltech.com/qstylesheet.html HTH John Ridley Send instant messages to your online friends http://uk.messenger.yahoo.com From fdreger at amiga.pl Sat Apr 23 12:28:13 2005 From: fdreger at amiga.pl (Filip Dreger) Date: Sat, 23 Apr 2005 18:28:13 +0200 Subject: func_code vs. string problem Message-ID: Each function has a func_code property that is suposed to contain the pure bytecode of the function. All the context (including reference to relevant namespaces) is stored in different fields of the function object. Since 'exec' is able to execute any string or bytecode in the current scope, it would seem possible to execute code of any function in any namespace. But no matter how I tried, I could not do it. There must be something I am missing. Here's what I do: (if anyone wants to help, I placed the source under http://www.bajobongo.net/foo.py - tested on Python 2.4.1) 1. I declare a function. In the next steps I will try to run its code from inside a class: def myfunction(): print abc self.test() 2. I declare a class foo, with two methods. The first one tries to reach some local variables from a string passed to exec. The other one tries to do the same from inside a bytecode (from myfunction). IMHE this should make no difference to 'exec' - [spoiler: it does]. class foo: def test(self): print "ABC" def checkfunction(self): abc=10 exec myfunction.func_code def checkstring(self): abc=10 exec "print abc;self.test()" 3. I test the both methods. Sadly, the 'checkfunction' fails to find the correct namespace (id does not see 'abc' nor 'self'). Adding things like: "exec myfunction.func_code in globals(),locals()" does not help. i=foo() i.checkstring() i.checkfunction() # this throws exception; why??? 4. I try to find some help here, and hope to also gain better undesrtanding of how Python works :-) Thanks for any suggestions, regards, Filip Dreger From steve at holdenweb.com Wed Apr 13 07:22:27 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 13 Apr 2005 07:22:27 -0400 Subject: Python documentation moronicities (continued) In-Reply-To: <1113388891.512839.111250@f14g2000cwb.googlegroups.com> References: <1113301533.054410.203710@z14g2000cwz.googlegroups.com> <1113346139.139720.17510@o13g2000cwo.googlegroups.com> <1113388891.512839.111250@f14g2000cwb.googlegroups.com> Message-ID: runes wrote: > Seems like criticising the manual is som kind of heresy. So be it. > Don't think so, but this being open source I suspect that Fredrik was trying to get them improved. > You know, the Re documentation contains many pages. Ufortunately I > didn't dwell with the first introductory paragraph, I was trying to > solve a particular problem. I'm not that used to looking for links to > external sources in the manual either. Unable? I wasn't looking for a > Howto in the manual. And frankly, 'python regex howto" in Google is > quicker way. > Right, so you found what you needed, you just think it should be referenced from the main docs. I think this is a good idea. > Of course I cannot suggest a better place for the link. > Come on, of course you can. All you need to say is whereabouts in the re documentation it should mention the How-To. > Writing technical documents always trigger the question: Who is the > audience. I accept that I may not be the primary audience. If I should > suggest anything, it would be that the examples section is expanded. > Again, you would be a good candidate to suggest changes, since you've just been learning that part of Python. > Generally: I have got my experiences with the Python Manual over the > the last 30 months Python beeing my preferred language. One of them is > that I have to look elsewhere. > But anyone is allowed to suggest improvements. Please don't be deterred because you think people were trying to put you off. The documentation contains links for suggesting improvements. That is a working channel for criticism and suggestion (and it's how many others first got their names in the python documentation, including myself). See http://docs.python.org/doc/doc.html http://docs.python.org/doc/about.html regards Steve -- Steve Holden +1 703 861 4237 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ From littlejohn.75 at news.free.fr Mon Apr 18 15:02:31 2005 From: littlejohn.75 at news.free.fr (F. Petitjean) Date: 18 Apr 2005 19:02:31 GMT Subject: packages References: Message-ID: <42640447$0$24669$626a14ce@news.free.fr> Le Mon, 18 Apr 2005 20:29:39 +0200, Mage a ?crit : > Hello, > > I read about modules and packages in the tutorial. I think I understand > how to use packages and modules, even I know how to create a module (as > far I understand it's a simple .py) file , but I don't know how can I > create a package and when should I do it. The standard library contains some packages : email, xml, distutils ... Read the __init__.py in the directory "package-name". > > Where should I look for more information? > > Mage > example of use : import distutils help(distutils) help(distutils.sysconfig) Traceback (most recent call last): File "", line 1, in ? AttributeError: 'module' object has no attribute 'sysconfig' import distutils.sysconfig help(distutils.sysconfig) distutils.sysconfig.get_python_lib(standard_lib=True) '/home/fp2x/local/lib/python2.4' distutils.sysconfig.get_python_lib(standard_lib=False) '/home/fp2x/local/lib/python2.4/site-packages' From simon.brunning at gmail.com Mon Apr 4 08:49:43 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Mon, 4 Apr 2005 13:49:43 +0100 Subject: (win32) speedfan api control In-Reply-To: <3b8m2tF6enbpaU1@individual.net> References: <3b8m2tF6enbpaU1@individual.net> Message-ID: <8c7f10c60504040549121c7d97@mail.gmail.com> On Apr 3, 2005 1:52 AM, Claudio Grondi wrote: > May I ask how did you get the > "TJvXPCheckbox" and the other > values necessary to access the program > GUI ? (as I can see, there is no source > code of SpeedFan available) ? Winspector is good for this kind of thing. http://www.brunningonline.net/simon/blog/archives/001320.html -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From serpent17 at gmail.com Mon Apr 18 13:45:34 2005 From: serpent17 at gmail.com (serpent17 at gmail.com) Date: 18 Apr 2005 10:45:34 -0700 Subject: Problem with unpack hex to decimal In-Reply-To: <3cgmfsF6hud65U1@individual.net> References: <1113763068.002612.240940@l41g2000cwc.googlegroups.com> <3cgmfsF6hud65U1@individual.net> Message-ID: <1113846334.680404.284180@z14g2000cwz.googlegroups.com> Thank you all very much. It looked like I was not the only one confused. Jake. From lbates at syscononline.com Tue Apr 5 08:43:01 2005 From: lbates at syscononline.com (Larry Bates) Date: Tue, 05 Apr 2005 07:43:01 -0500 Subject: copying a file in the python script In-Reply-To: <1112678460.464474.82610@z14g2000cwz.googlegroups.com> References: <1112678460.464474.82610@z14g2000cwz.googlegroups.com> Message-ID: <2ZadndRAcawiGs_fRVn-ig@comcast.com> If you are moving the file to another directory on the same hard drive (e.g. same filesystem) you can use os.rename(old, new) and the file doesn't have to be copied at all. This is more efficient. If you are copying to another filesystem, you must use shutil.copy and os.remove (or os.unlink). Larry Bates Raghul wrote: > hi > I am having a problem. I want to copy a file from the folder and > paste it or move it to another folder. Is it possible in python? > Actually I need to implement this in the zope for my site. When I click > any file it should move or copied to another folder in the same machine > using zope. > > Thanks in advance. > From polykrombelcentercom Fri Apr 29 14:11:28 2005 From: polykrombelcentercom (Exeem (at dot)) Date: Fri, 29 Apr 2005 20:11:28 +0200 Subject: [newbie] Embedding Flash OCX object Message-ID: Hi All, I'm trying to find a way to embbed the flash.ocx object in a Windows Python application, I've successfully integrated a flash object with the ocx already installed on the system using the Activex Wrapper, but i would like to embbed it inside my application in order to distribute my application without the need for the user to install the flash player. It would like also to embbed the flash animation inside my application without loading it .. i mean directly from the memory. I've seen that it was possible in C++ or in Delphi, using the http://www.flashplayercontrol.com/ .. but don't know how to make it in Python. Any ideas are welcome Dan. From tjreedy at udel.edu Fri Apr 1 21:03:59 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 1 Apr 2005 21:03:59 -0500 Subject: Case-insensitive dict, non-destructive, fast, anyone? References: <424dc33c.55623752@news.oz.net> <424dda51.61532058@news.oz.net> Message-ID: "Raymond Hettinger" wrote in message news:rul3e.4647$db.487 at trndny07... > More important than the percentage is the clarity of the resulting code > and the > avoidance of continous reinvention of workarounds. > > Separating tool features into a basic and an advanced version is common > solution > to managing option/customization complexity. A super bells & whistles dict would certainly pre-answer a lot of queries and save much newsgroup/list response time. tjr From mahs at telcopartners.com Tue Apr 26 13:26:51 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Tue, 26 Apr 2005 10:26:51 -0700 Subject: Pythonic way to do static local variables? In-Reply-To: References: <_xgbe.128633$cg1.54987@bgtnsc04-news.ops.worldnet.att.net> <7Ujbe.647694$w62.444038@bgtnsc05-news.ops.worldnet.att.net> Message-ID: Terry Reedy wrote: > "Charles Krug" wrote in message > news:7Ujbe.647694$w62.444038 at bgtnsc05-news.ops.worldnet.att.net... > >>Both of these techniques look promising here. > > > Here a third, the closure approach (obviously not directly tested): > > > Just for grins, here's a fourth approach, using the descriptor protocol >>> def func_with_state(state,a): ... state.append(a) ... return state ... >>> f = func_with_state.__get__([]) >>> f(1) [1] >>> f(2) [1, 2] >>> f(3) [1, 2, 3] >>> Michael From tuure at laurinolli.net Thu Apr 14 12:55:01 2005 From: tuure at laurinolli.net (Tuure Laurinolli) Date: Thu, 14 Apr 2005 19:55:01 +0300 Subject: New-style classes, iter and PySequence_Check Message-ID: Someone pasted the original version of the following code snippet on #python today. I started investigating why the new-style class didn't work as expected, and found that at least some instances of new-style classes apparently don't return true for PyInstance_Check, which causes a problem in PySequence_Check, since it will only do an attribute lookup for instances. Things probably shouldn't be this way. Should I go to python-dev with this? Demonstration snippet: args={'a':0} class Args(object): def __getattr__(self,attr): print "__getattr__:", attr return getattr(args,attr) class ClassicArgs: def __getattr__(self, attr): print "__getattr__:", attr return getattr(args, attr) if __name__ == '__main__': c = ClassicArgs() i = c.__iter__() print i i = iter(c) print i a = Args() i = a.__iter__() print i i = iter(a) print i From james at wrong.nu Sun Apr 24 10:51:08 2005 From: james at wrong.nu (R. C. James Harlow) Date: Sun, 24 Apr 2005 15:51:08 +0100 Subject: Variables In-Reply-To: <426B0283.40602@cloudthunder.com> References: <426B0283.40602@cloudthunder.com> Message-ID: <200504241551.21884.james@wrong.nu> On Sunday 24 April 2005 03:20, Richard Blackwood wrote: > To All: > > Folks, I need your help. I have a friend who claims that if I write: > > foo = 5 > > then foo is NOT a variable, necessarily. This is a really amusingly recursive discussion. Your friend has a piece of knowledge, "what a variable is and is not". He uses the word "variable" to refer to this piece of knowledge. Now, if in some parallel universe people used the word "hairbrush" to refer to this bit of knowledge, that wouldn't stop his argument having validity if he travelled to that universe - if it would then it's already invalidated, as there are more people in *this* universe who use the word variable to refer to foo than there are who insist that it's not correct, by a significant proportion. So by corollary your friend has already argued that one can use many different words to correctly refer to the same concept. I think your friend would also find it hard to disagree that a single word can have multiple meanings, like the example given of "Domain" in maths. I think he would have a similarly tough time saying that these words with multiple meanings were only allowable in maths, not in english or the offshoots of maths like programming. So there's no reason why the concept of what you call a variable and what he calls a variable shouldn't be different. In summary, the words he uses to describe variables are constants, but point at variables, which are different than the constants you use to describe variables, which point at variables, and vary from the variables that his variables point at. And if that last sentence doesn't convince him of the futility of trying to use natual language to communicate precise concepts, nothing will. -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From monografia at xfdgr.com Mon Apr 25 23:02:30 2005 From: monografia at xfdgr.com (monografia ) Date: Tue, 26 Apr 2005 04:02:30 +0100 Subject: 7474 monografia =?iso-8859-1?q?administra=E7=E3o?= - monografia direito 7474 Message-ID: Monografias completas a partir de 250,00 ! monografia administra??o direito turismo economia letras pedagogia monografias teses tese. Sua monografia a partir de 250,00 http://monografiadireta.rg3.net From fdreger at amiga.pl Sat Apr 23 17:47:22 2005 From: fdreger at amiga.pl (Filip Dreger) Date: Sat, 23 Apr 2005 23:47:22 +0200 Subject: func_code vs. string problem References: <04mdnXLeedaPLvffRVn-vQ@comcast.com> Message-ID: Uzytkownik "Steven Bethard" napisal w wiadomosci news:04mdnXLeedaPLvffRVn-vQ at comcast.com... > See the documentation: > > http://docs.python.org/ref/dynamic-features.html > > """The eval(), execfile(), and input() functions and the exec > statement do not have access to the full environment for resolving > names. Names may be resolved in the local and global namespaces of > the caller. Free variables are not resolved in the nearest enclosing > namespace, but in the global namespace.""" Thank you! I feel silly I have not found the piece of instruction myself. And even worse, as I still do not understand: if exec() resolves free bariable names in the global namespace, how come it works well with code in a string? Or with a code in a compiled string? > Note the last sentence, which tells you that your free variable, > 'abc', will be resolved in the *global* namespace. In your > particular problem, you can solve this by substituting your local > namespace for the global namespace. This particular problem - sadly - is a simplified version of the real one. I need access to both: global and local namespaces, so this solution is not for me. The manual says I can pass two dictionaries to exec, one for global namespace and one for local. But, strange as it seems, I could not get it to work. In the example I gave, changing exec f.func_code to exec f.func_code in globals(),locals() does not help a bit. > One possible workaround might be: > > py> class foo: > ... def test(self): > ... print "ABC" > ... def checkfunction(self): > ... abc=10 > ... l = locals() > ... l.update(globals()) > ... exec myfunction.func_code in l > ... def checkstring(self): > ... abc=10 > ... exec "print abc;self.test()" > ... > py> foo().checkfunction() > __main__.foo > 10 > ABC I thought about that... I don't know why, but it seems wrong. Maybe the updating dictionaries is not very expensive, but there must be some better way. This code has a 'workaround - fixme' written all over it. Up to now, each time I encountered such a workaroundish solution, it turned out Python has a cleaner way to do it. I sure hope this is also the case here :-). > But I'd have to know what your real use case is to tell you whether > or not this is worth the trouble. Why do you want to exec the > func_code anyway? Why can't you just call the function? I put the description in the other post. Perhaps it's jkust my design that's broken. Thanks again. regards, Filip Dreger From gandalf at geochemsource.com Wed Apr 20 11:47:49 2005 From: gandalf at geochemsource.com (Laszlo Zsolt Nagy) Date: Wed, 20 Apr 2005 17:47:49 +0200 Subject: Faster os.walk() In-Reply-To: <1114011606.600970.43300@l41g2000cwc.googlegroups.com> References: <1114011606.600970.43300@l41g2000cwc.googlegroups.com> Message-ID: <426679A5.8090504@geochemsource.com> fuzzylollipop wrote: >I am trying to get the number of bytes used by files in a directory. >I am using a large directory ( lots of stuff checked out of multiple >large cvs repositories ) and there is lots of wasted time doing >multiple os.stat() on dirs and files from different methods. > > Do you need a precise value, or are you satisfied with approximations too? Under which operating system? The 'du' command can be your firend. man du Best, Laci 2.0 -- _________________________________________________________________ Laszlo Nagy web: http://designasign.biz IT Consultant mail: gandalf at geochemsource.com Python forever! From a.schmolck at gmx.net Tue Apr 19 16:42:18 2005 From: a.schmolck at gmx.net (Alexander Schmolck) Date: Tue, 19 Apr 2005 21:42:18 +0100 Subject: Array of Chars to String References: Message-ID: James Stroud writes: > But this seems ugly. I especially don't like "newstr += lttr" because it makes > a new string every time. I am thinking that something like this has to be a > function somewhere already or that I can make it more efficient using a > built-in tool. "".join 'as From max2 at fisso.casa Wed Apr 13 13:37:48 2005 From: max2 at fisso.casa (max(01)*) Date: Wed, 13 Apr 2005 17:37:48 GMT Subject: domain specific UI languages Message-ID: hi. in a previous thread, mr lundh talks about the possibility to create "domain specific UI languages" using tkinter. can he (or anyone else who pleases) explain what they are? give some examples (simple is better)? bye macs From dave at pythonapocrypha.com Tue Apr 12 12:39:06 2005 From: dave at pythonapocrypha.com (Dave Brueck) Date: Tue, 12 Apr 2005 10:39:06 -0600 Subject: Python 2.4 killing commercial Windows Python development ? In-Reply-To: References: <425a9869$0$38039$bed64819@news.gradwell.net><425aa0fb$0$38041$bed64819@news.gradwell.net><425AF2AB.1030401@v.loewis.de> <425b8948$0$38045$bed64819@news.gradwell.net> Message-ID: <425BF9AA.2040800@pythonapocrypha.com> Terry Reedy wrote: > I guess I don't understand some people's determination to not have users > install fully useable Python on their Windows machines. [snip] > To put it another way, needing a Python interpreter to run .py files is no > different from, for instance, needing a movie player to run .mpg files, and > all Windows users are or need to become familiar with that general concept. > > Also, I think it a bit 'anti-social' to hide usage of Python. If all > Python Windows programs ran with a normal, communally installed Python, > then users would gradually get the idea that having Python installed is > much like having Shockwave and other utility platforms installed, and that > is is part of a 'fully loaded' Windows system to have a .py player > installed. > > If there is something about the default install of Python on Windows that > makes it less desireable or less easy than other platforms, then maybe that > can be fixed. To make installation easier, maybe someone could write a > small .exe that could be frozen with scripts or run with installers and > that would detect the presence/absence of the needed Python version and > offer an auto download and install if needed. I mostly agree with the sentiment, but it does break down a little in practice. At least currently it does - like you said, this is fixable, but nobody has signed up to fix it yet. The main thing that's needed is a zero-input Python distribution - a Python runtime, if you will - that (1) gets installed to a "good" place (2) does so without asking the user to do anything, (3) can coexist with different versions of the runtime, and (4) is easily detectable by applications wanting to use it. One other minor component is a small launcher executable, because on Windows it's non-trivial to find out which "python.exe" in the task manager is running which Python script. Anyway, each app would have a small launcher that bootstraps the actual Python script[1]. (Or, if there's some way to trick the task manager into displaying something besides "python.exe", that'd work too) In order to "fit" into the expectations of a typical Windows user, an application installer needs the ability to check for the presence of a particular version of the Python runtime, and then install it if it's not present, and do so without asking the user to do anything. With that much in place, a lot of the need for freezing Python apps goes away (definitely not all of it, but a lot of it). Here's stuff that still needs to be considered though: 1) A way for apps to specify their compatibility with different versions of the runtime - "I work with pyrt2.3.3 through 2.4.1" 2) A way for apps to register their dependency on that runtime, so that if the user uninstalls it, there is at least an indication of what programs might break. 3) (this is a nice-to-have, but not 100% required) A way to download additional libraries once and use them for multiple programs, e.g. the installer could see if ctypes is present, and if not, go get it. Later programs would take advantage of it already being installed. Like I said, not a 100% requirement, and some of the ongoing work with code CPAN-like code repositories would shoehorn into this. 4) The security implications, e.g. an innocent app installs pywin32 and enables Python client-side scripting in Internet Explorer, and later this is used as a big door for malicious users to use. Most of these tasks don't require a lot of work; indeed this has been on my "one of these days" lists for awhile. The main reasons it hasn't been done yet: 1) The code freezing tools like py2exe are *very* good and convenient (especially since loading code from zip archives was added - even if you include all of Python, it's only a few files on disk, and now they're all in the same directory) 2) Storage space and download speeds continue to increase at a rate much faster than the rate at which the size of Python is growing - a download of a few MB isn't too bad these days, who cares if your app takes 4MB on disk, and so what if it doesn't fit on a floppy, for example. 3) As soon as you get started on such a project, almost immediately you will be overwhelmed with a desire to create a CPAN-like system while you're at it, at which point your project's status will shift from "making good progress!" to "in quagmire, developers MIA". :) -Dave [1] I built a hacky one of these launcher exe's for one project, and it was fairly reusable for apps in the same vein. Basically, the exe would would look to see what its name was, and then load a Python module of the same name. So if you have MyGame.py, you'd just take the generic launcher.exe, copy it to the same directory as your .py files, and rename it to MyGame.exe. On launch, it'd load the interpreter, load MyGame.py, and pass it the command-line args. From jepler at unpythonic.net Tue Apr 19 22:43:50 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 19 Apr 2005 21:43:50 -0500 Subject: Writing to stdout and a log file In-Reply-To: <1113958286.367038.182330@z14g2000cwz.googlegroups.com> References: <1113956275.697789.324730@o13g2000cwo.googlegroups.com> <1113958286.367038.182330@z14g2000cwz.googlegroups.com> Message-ID: <20050420024350.GC26325@unpythonic.net> In that case, it looks like you won't be able to get what you want without modifying CPython. PRINT_ITEM calls PyFile_SoftSpace, PyFile_WriteString, and PyFile_WriteObject, which all use PyFile_Check(). It might be as simple as changing these to PyFile_CheckExact() calls in PyFile_WriteString / PyFile_WriteObject, but I have no idea whether the test suite still works after this change is made. It does make this program work (it prints things from X.write): class X(file): def write(self, s): print "X.write", `s` return file.write(self, s) import sys x = X("/tmp/out.txt", "w") print >>x, 42 I don't care to be the champion of this patch, or to submit it to sourceforge; I suspect there should be a better review of PyFile_Check vs PyFile_CheckExact uses in fileobject.c, instead of just picking the few spots that make this usage work. Before being submitted as a patch, a testcase should be added too. Feel free to run with this if you feel strongly about it. Jeff Index: Objects/fileobject.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/fileobject.c,v retrieving revision 2.193 diff -u -u -r2.193 fileobject.c --- Objects/fileobject.c 7 Nov 2004 14:15:28 -0000 2.193 +++ Objects/fileobject.c 20 Apr 2005 02:41:32 -0000 @@ -2012,7 +2012,7 @@ PyErr_SetString(PyExc_TypeError, "writeobject with NULL file"); return -1; } - else if (PyFile_Check(f)) { + else if (PyFile_CheckExact(f)) { FILE *fp = PyFile_AsFile(f); #ifdef Py_USING_UNICODE PyObject *enc = ((PyFileObject*)f)->f_encoding; @@ -2082,7 +2082,7 @@ "null file for PyFile_WriteString"); return -1; } - else if (PyFile_Check(f)) { + else if (PyFile_CheckExact(f)) { FILE *fp = PyFile_AsFile(f); if (fp == NULL) { err_closed(); -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From python.tr at gmail.com Fri Apr 8 16:13:08 2005 From: python.tr at gmail.com (Hasan D) Date: Fri, 8 Apr 2005 23:13:08 +0300 Subject: Https Form Page Message-ID: <764176c10504081313501b1e1f@mail.gmail.com> I'm new on this httplib and urllib. Actually I dont know what should i use. I want to fill the form in a "https" page , and return the result . I write a test code but always gives errors. I cant find any good example about this on the net. What should I do about this ? import urlparse,urllib,httplib,string,htmllib,formatter #port="443" target="https://www.abc.com/" params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0}) http=httplib.HTTP("https://www.abc.com/",443) data='Name=x&Adress=x' headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain"} print "Sending Data On "+target+"...\n" http.putrequest("POST",target+"/xxx.asp?q=7&b=11",params) response = http.getresponse() print response.status, response.reason http.send(data) code,msg,headers = http.getreply() print "HTTP Code : ",str(code) print "HTTP Connection : ",msg print "HTTP headers : \n",headers,"\n" HTML=http.getfile().read() MyParser=htmllib.HTMLParser(formatter.NullFormatter()) MyParser.feed(HTML) # Print all the anchors from the results page print MyParser.anchorlist From tjreedy at udel.edu Wed Apr 27 02:39:47 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 27 Apr 2005 02:39:47 -0400 Subject: bytecode non-backcompatibility References: <1114418065.581779.52480@l41g2000cwc.googlegroups.com> <86wtqqm27r.fsf@guru.mired.org> <86is29n9cg.fsf@guru.mired.org> Message-ID: "Maurice LING" wrote in message news:d4mrdf$jrc$1 at domitilla.aioe.org... > From a technical perspective, I can accept that .pyc files are private > and temporary. To a certain extend, it does helps development cycle. > Every time I amend my source codes, I just run it without having to > consider or needing to re-compile the source files. >From a user perspective, source code is the run-time program. > The idea of having to release the program or library as source files does > ring alarms in many executives in corporate world. I understand that people use Python while resisting its purpose and design. But I also understand that it is *their* responsibilty to hide their code, which may possibly mean not using Python, or which may mean developing proprietary methods to translate to something designed to *not* be readable. For all we know, some of the developers have been paid to do exactly that -- and not talk about it. Python is *designed* for human readability. That is one of its big features! The same also seems somewhat true for CPython's bytecodes, especially when disassembled with the dis module that comes with the interpreter. You even get all the object names included in the code object. Terry J. Reedy From david at handysoftware.com Mon Apr 4 23:34:41 2005 From: david at handysoftware.com (David Handy) Date: Mon, 4 Apr 2005 23:34:41 -0400 Subject: Unexpected result when comparing method with variable Message-ID: <20050405033441.GA15819@arno2> I had a program fail on me today because the following didn't work as I expected: >>> class C: ... def f(self): ... pass ... >>> c = C() >>> m = c.f >>> m is c.f False I would have expected that if I set a variable equal to a bound method, that variable, for all intents and purposes, *is* that bound method, especially since I hadn't changed or deleted anything on the class or its instance. The same thing happens when attempting to compare an unbound method with a variable name bound to that unbound method: >>> M = C.f >>> M is C.f False If I were to guess what is going on here, I would say that the expression c.f invokes a descriptor that manufactures a brand new "method object" each time. The problem is, this is non-intuitive (to me) and prevented me from doing something I thought was useful. My use case is deferring operations till later, by placing tuples of a method and its arguments in a list to be processed at some future time, but doing some special-case processing only for certain methods: deferred = [] ... deferred.append((c.f, ('abc', 123))) ... for method, params in deferred: method(*params) if method is c.f: # handle a special case But I can't do that special-case handling this way, I have to resort to some other means to identify a method, "method is c.f" is always False. Which seems strange to me. This behavior is in Python 2.4, 2.3, and 2.2. The workaround really awkward: SPECIAL_METHOD = c.f ... deferred.append((SPECIAL_METHOD, ('abc', 123))) ... if method is SPECIAL_METHOD: # handle special case If I forget at any time to use the name SPECIAL_METHOD, but resort to it's "real" name of c.f, then the comparison fails. So, is this a bug or expected? If I complain about this, would I get any sympathy? ;) regards, David H. From bokr at oz.net Tue Apr 12 09:26:52 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 12 Apr 2005 13:26:52 GMT Subject: singleton objects with decorators References: <1113300588.335527.26290@o13g2000cwo.googlegroups.com> <425bac0d.185429854@news.oz.net> Message-ID: <425bbc80.189640348@news.oz.net> On Tue, 12 Apr 2005 13:26:54 +0200, "Fredrik Lundh" wrote: >Bengt Richter wrote: > >> But isn't bool supposed to be a singleton class/type ? >> >> >>> [bool(x) for x in 0, 0.0, [], {}, False] >> [False, False, False, False, False] >> >>> [id(bool(x)) for x in 0, 0.0, [], {}, False] >> [505014288, 505014288, 505014288, 505014288, 505014288] > >"False" is an ordinary global object, not an object factory or a singleton class. > UIAM, "False" is a string, or a representation of a string ;-) And the name False is typically found as __builtins__.False unless you have shadowed it locally or in some module globals, as I'm sure you know. I was just demonstrating that all the bool(x) _instances_ are the identical False object in the above, and duck-wise that quacks singleton-like, even though the True maybe makes it a dualton, since bool does return two distinct instances ;-) IMO the global False name accessibility is a red herring, since it's the object it is normally bound to that is the real subject. >>> __builtins__.False is bool(0) True UIAM, the True and False objects per se are unique and built into boolobject.c And you can bind all the names you like to them, but bool(0) is always that single unique object and so is bool(1) its unique object. I don't believe this is an optimization like that involving the first 100 integer values or so. It's a weird beast, being a subtype of int also. I'll defer to the BDFL in http://www.python.org/peps/pep-0285.html """ The values False and True will be singletons, like None. Because the type has two values, perhaps these should be called "doubletons"? The real implementation will not allow other instances of bool to be created. """ Regards, Bengt Richter From tjreedy at udel.edu Fri Apr 8 17:07:23 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 8 Apr 2005 17:07:23 -0400 Subject: Can dictionary values access their keys? References: Message-ID: > Further, is there much processing required to do the magic? When python > do introspective magic, is it memory intensive? by that I mean does it > have to make copies of the objects to do the look-ups? A Python interpreter never copies *objects* (as opposed to references to objects) except when you ask it too. (This sometimes trips up newbies when the copied reference is to an uncopied mutable object that they thought was copied.) For CPython, references are 4 (possibly 8) byte pointers, which is smaller than any object. Terry J. Reedy From eric_brunel at despammed.com Wed Apr 27 05:31:35 2005 From: eric_brunel at despammed.com (Eric Brunel) Date: Wed, 27 Apr 2005 11:31:35 +0200 Subject: tkinter text width References: Message-ID: On Tue, 26 Apr 2005 17:01:46 -0700, James Stroud wrote: > Hello All, > > I would like for a tkinter text widget to be aware of how big the frame that > contains it is, then I would like for it to reset its width to the > appropriate number of characters when this frame changes size. Errr... This is supposed to be the regular behaviour. How do you create your Text widget? Do you specify a width and height? If you do not, the default width and height are 80 and 24 respectively, and the widget won't resize to less than that. If you want a Text widget to be the smallest as possible in its container, you can do something like: ----------------------------------------------------- from Tkinter import * root = Tk() t = Text(root, width=1, height=1) t.pack(fill=BOTH, expand=1) root.geometry('500x200') root.mainloop() ----------------------------------------------------- The "trick" is to create the Text as small as possible (width=1, height=1), make it fill its whole container (pack(fill=BOTH, expand=1)), then set the dimensions for the container window (geometry('500x200')). You'll get a Text that will shrink and expand as much as you like. Is it what you were after? HTH -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17;8(%,5.Z65\\'*9--56l7+-'])" From tim.leeuwvander at nl.unisys.com Mon Apr 18 14:03:07 2005 From: tim.leeuwvander at nl.unisys.com (Tim N. van der Leeuw) Date: 18 Apr 2005 11:03:07 -0700 Subject: Behaviour of str.split In-Reply-To: <1113838796.626344.309630@l41g2000cwc.googlegroups.com> References: <4263cf31$0$26348$db0fefd9@news.zen.co.uk> <1113838796.626344.309630@l41g2000cwc.googlegroups.com> Message-ID: <1113847387.862751.61780@f14g2000cwb.googlegroups.com> runes wrote: > The behaviour of "".split("*") is not that strange as the splitpoint > always disappear. The re.split() have a nice option to keep the > splitpoint which the str.split should have, I think. > > One expectation I keep fighting within myself is that I expect > > "mystring".split('') to return ['m', 'y', 's', 't', 'r', 'i', 'n', > 'g']. But I guess it's in line with "There should be one-- and > preferably only one --obvious way to do it." that it's not so. Fortunately, this is easy to write as: list("mystring"). Actually for me it's not so counter-intuitive that "mystring".split('') doesn't work; what are you trying to split on? Anyways, I usually need to split on something more complicated so I split with regexes, usually. cheers, --Tim From onurb at xiludom.gro Fri Apr 15 09:46:39 2005 From: onurb at xiludom.gro (bruno modulix) Date: Fri, 15 Apr 2005 15:46:39 +0200 Subject: Python - interpreted vs compiled In-Reply-To: <1113566234.343746.48460@o13g2000cwo.googlegroups.com> References: <1113566234.343746.48460@o13g2000cwo.googlegroups.com> Message-ID: <425fc5c0$0$1259$636a15ce@news.free.fr> codecraig wrote: > Hi, > I have a question about Python. I know that it is an interpreted > language, Nope. A *language* is neither compiled nor interpreted. An *implementation* of a language can use strict interpretation, byte-code compilation + VM, or native code compilation (it could as well use purely mechanical stuff or whatever). CPython - the current reference implementation of Python - uses byte-code compilation + VM. Jython too, but is relies on the Java byte-code and VM. IronPython targets MS .NET CLR. > meaning a python program is converted to binary on the fly > each time it is run, or compiled. Only the main script is recompiled each time - unless you compile it by yourself. Imported code is (re)compiled only if necessary. > What would be the purpose of compiling? Having an intermediate representation that is faster to execute for the VM. What is the purpose of compiling, be it to byte-code or to native object code ? > I guess the compiled python > code (question, is compiled python code called byte code? yes. > is not readable since it is not plain text, You mean human-readable ? Depends on which human reads it !-) (NB : No, I can't read byte-code) > which may be > a reason for compiling... No, this is an effect, not a cause. Reverse-engineering Python byte-code is quite easy (idem for Java). This is not meant to "protect" code. Neither is native object-code compilation a protection against craking - or we wouldn't see so many cracked applications on Windows machines... > but why else?? Execution speed. A byte-code is kind of an assembly language for a non-existing processor (hence the 'virtual machine' concept). This is exactly the same motivation as for native-code compilation : not having to tokenise/parse/translate the code each time it's runned. The main difference here between Python and Java is that the Python runtime takes care of those details for you instead of requiring you to either manually recompile everything each time you make a change or use a complex build system (that you'll have to - manually - maintain anyway). -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From unknownsoldier93 at yahoo.com Tue Apr 5 22:53:57 2005 From: unknownsoldier93 at yahoo.com (gf gf) Date: Tue, 5 Apr 2005 19:53:57 -0700 (PDT) Subject: Calling a Perl Module from Python Message-ID: <20050406025357.85585.qmail@web20708.mail.yahoo.com> I've recently made the switch. Wow, is Python great! One thing which I haven't been able to do is replace Perl's great lib collection (HTML::Parser, for instance, can do a lot that Soup just can't). Is there anyway to call Perl modules from Python? Thanks PS Please cc me on all responses __________________________________ Do you Yahoo!? Yahoo! Mail - Find what you need with new enhanced search. http://info.mail.yahoo.com/mail_250 From gsakkis at rutgers.edu Sun Apr 3 14:17:35 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 3 Apr 2005 11:17:35 -0700 Subject: Decorater inside a function? Is there a way? References: <1112466233.403989.125810@l41g2000cwc.googlegroups.com> <1112516432.638697.193840@o13g2000cwo.googlegroups.com> <2erv41d8ilujl0vmformr26vm0tvhf689o@4ax.com> Message-ID: <1112552255.356217.81640@f14g2000cwb.googlegroups.com> >def define(func): > if not ENABLE_TYPECHECKING: > return lambda func: func > # else decorate func A small correction: The argument of the decorator is not 'func' but the parameter checks you want to enforce. A template for define would be: def define(inputTypes, outputType): if not ENABLE_TYPECHECKING: return lambda func: func def decorate(func): def typecheckedFunc(*args,**kwds): ##### TYPECHECK *args, **kwds HERE ##### r = func(*args,**kwds) ##### TYPECHECK r HERE ##### return r return typecheckedFunc return decorate Depending on how much flexibility you allow in inputTypes, filling in the typechecking logic can be from easy to challenging. For example, does typechecking have to be applied in all arguments or you allow non-typechecked aruments ? Can it handle *varargs and **kwdargs in the original function ? An orthogonal extension is to support 'templated types' (ala C++), so that you can check if something is 'a dict with string keys and lists of integers for values'. I would post my module here or the cookbook but at 560 (commented) lines it's a bit long to qualify for a recipe :-) George From claird at lairds.us Mon Apr 25 13:08:04 2005 From: claird at lairds.us (Cameron Laird) Date: Mon, 25 Apr 2005 17:08:04 GMT Subject: what is the best way to determine system OS? References: <1114436211.942212.203790@f14g2000cwb.googlegroups.com> <868y37osc7.fsf@guru.mired.org> Message-ID: In article <868y37osc7.fsf at guru.mired.org>, Mike Meyer wrote: . . . >Anyway, checking the system name is the wrong way to build portable >programs. For one thing, as you've discovered, new systems won't work >properly. For another, upgrades to existing systems may break things >as well. > >What you should do instead is check on how to use the features you >want. If you watch a typical autoconf script, you'll see it groveling >through libraries, include files, and various directories looking for >subroutines, defines and commands. That's the idea, but without >knowing which features you're looking for, I can't say how you would >check for them. > >This takes more time to write, but results in more robust code. For >instance, if some distribution changes one of the features to mimic a >"better" distribution that you already support, instead of your script >breaking, it'll just work. This is much better than having to teach >your script how to distinguish between versions of distributions. . . . Not for me. Well, not absolutely. I have a load of respect for you, Mike, and there certainly are amazing edifices built on autoconf. Also, I think it's an important part of our engineering to understand the principle of groveling around interrogating capabilities; among other things, it's good practice for duck typing and idiomatic Python exception style. I'm very uncomfortable, though, with an assertion that reliance on a fixed table of attributes is always wrong. Briefly, use of autoconf is FAR from a guarantee that everything works right when starting with a new flavor. From tiissa at nonfree.fr Wed Apr 20 16:08:39 2005 From: tiissa at nonfree.fr (tiissa) Date: Wed, 20 Apr 2005 22:08:39 +0200 Subject: What's the difference between these 2 statements? In-Reply-To: <1114026007.999930.12850@f14g2000cwb.googlegroups.com> References: <70c4ec00.0504201052.30227e93@posting.google.com> <3cnmpbF6gnlkhU1@individual.net> <4266ad9f$0$14218$636a15ce@news.free.fr> <1114026007.999930.12850@f14g2000cwb.googlegroups.com> Message-ID: <4266b6c6$0$8860$636a15ce@news.free.fr> ahmedt at gmail.com wrote: > I'm sorry, I'm not really following your logic. Can you supply the > statement with the three parameters ? > > so if I want to reverse it fully using s[len(s)-1:x:-1] what would x be > or is it impossible to express it in this way ? Contrary to what I said above x should be _strictly_ less than -len(s). You stop when you reach in the list the given end index (and don't take the item there) or if you leave the index range. But -1 as an index is the same as (len(s)-1). Therefore going from len(s)-1 down to -1 is the same as going from len(s)-1 to len(s)-1 hence an empty list. And -len(s) is the same as 0 (my mistake above) But -len(s)-1 is not in the list thus you won't discard any limit. The example: In [1]: s='12345' In [2]: s[len(s)-1:0:-1] Out[2]: '5432' In [3]: s[len(s)-1:-1:-1] Out[3]: '' In [4]: s[-1],s[len(s)-1] Out[4]: ('5', '5') In [5]: s[len(s)-1:-len(s)-1:-1] Out[5]: '54321' In [6]: s[len(s)-1:-len(s):-1] Out[6]: '5432' From codecraig at gmail.com Fri Apr 22 16:28:57 2005 From: codecraig at gmail.com (codecraig) Date: 22 Apr 2005 13:28:57 -0700 Subject: figuring out # of bytes Message-ID: <1114201737.736514.8470@l41g2000cwc.googlegroups.com> i want to the number of bytes in a string... is, len(x) accurate? so, x = "hi" len(x) == 2 ....so that means two bytes? thanks From claird at lairds.us Tue Apr 5 22:08:23 2005 From: claird at lairds.us (Cameron Laird) Date: Wed, 06 Apr 2005 02:08:23 GMT Subject: IronPython 0.7 released! References: <1111603770.909447.18070@z14g2000cwz.googlegroups.com> <1f7befae05040512422ef693d4@mail.gmail.com> Message-ID: In article , Steve Holden wrote: . . . >Presumably when we get past the embracing and on to the extending Barry >can finally retrain Spambayes to reject penis enlargement emails? . . . Hey! I'm indignant; why, if you jokers were earnest about demonstrating Python's commercial applicability, you'd apply Spambayes' algorithms to the dual, and presumably highly remunerative, problems of designing spam that readers answer. This community just isn't *serious* enough. And now, for something completely different, I'll tender a personal view: I think Mr. Gates and Python are actually destined to get along uncharacteristically well. Roughly, I suspect the habits and motivations of the two are so skew, that the usual "embrace and extend" simply won't obtain. I soberly expect IronPython to work out well for both Microsoft and Python. That changes nothing about my long-term feelings toward Microsoft and Python. From aleksander.helgaker at gmail.com Wed Apr 20 11:39:41 2005 From: aleksander.helgaker at gmail.com (aleksander.helgaker at gmail.com) Date: 20 Apr 2005 08:39:41 -0700 Subject: random number between 0 and 20 In-Reply-To: <_c-dnaseE4DQ7vvfRVn-3A@powergate.ca> References: <1114010102.027562.150840@z14g2000cwz.googlegroups.com> <_c-dnaseE4DQ7vvfRVn-3A@powergate.ca> Message-ID: <1114011580.964880.58280@l41g2000cwc.googlegroups.com> Yes I know about assigning and all that. I just stated the name of the variable so that people could easily explain how to create the random number. I needed it to practice Python. I just finished making a number guess program. I just finished it. It was much easier to do then I thought it would be. From larsmtl at yahoo.com Thu Apr 21 16:29:47 2005 From: larsmtl at yahoo.com (larsmtl at yahoo.com) Date: 21 Apr 2005 13:29:47 -0700 Subject: Python CGI Select Multiple Returning all items in box Message-ID: <1114115387.081363.109450@o13g2000cwo.googlegroups.com> Howdy all, Is there an easy way to return all items of an "HTML select multiple" even if they aren't highlighted? form=cgi.FieldStorage() form.getlist("box") only returns those that are selected. Thanks, Mark From fredrik at pythonware.com Fri Apr 22 13:13:39 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 22 Apr 2005 19:13:39 +0200 Subject: Regular Expressions - Python vs Perl References: <1114092105.964664.211430@l41g2000cwc.googlegroups.com> Message-ID: Ilpo Nyyss?nen wrote: > > Are you speculating that it might be a problem, or saying that you have > > seen it be a problem in a real-life program? > > Well, it depends, I might say yes. I have a calendar app with command > line user interface. There the use is like this: "view, add, view, > edit, view, ..." and those are separate command invocations. In that > case a second in startup speed can be a long time. And I did use the > profiler and it did show the sre compiling to be the slowest thing. so you picked the wrong file format for the task, and the slowest tool you could find for that file format, and instead of fixing that, you decided that the regular expression engine was to blame for the bad performance. hmm. > Nowdays I use libxml2-python as the XML parser and so the problem is > not so acute anymore. (That is just harder to get in running for > python compiled from source outside the rpm system and it is not so > easy to use via DOM interface.) python has shipped with a fast XML parser since 2.1, or so. From __peter__ at web.de Fri Apr 15 11:35:38 2005 From: __peter__ at web.de (Peter Otten) Date: Fri, 15 Apr 2005 17:35:38 +0200 Subject: eval function not working how i want it dag namn References: <1113567261.483667.198430@z14g2000cwz.googlegroups.com> Message-ID: Michael Hoffman wrote: >> def list_members(obj) >>l?=?dir(obj) >>return?map(lambda?x?:?eval('obj.'+x),?l) > > That works fine for me with Python 2.4. Python 2.4 (#6, Jan 30 2005, 11:14:08) [GCC 3.3.3 (SuSE Linux)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> def lm(obj): ... l = dir(obj) ... return map(lambda x: eval("obj." + x), l) ... >>> class X: ... pass ... >>> x = X() >>> x.question = "Are you sure?" >>> lm(x) Traceback (most recent call last): File "", line 1, in ? File "", line 3, in lm File "", line 3, in File "", line 0, in ? NameError: name 'obj' is not defined >>> Peter From bvande at po-box.mcgill.ca Thu Apr 21 20:58:37 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Thu, 21 Apr 2005 20:58:37 -0400 Subject: Dictionary question. In-Reply-To: <1114129715.038945.227200@o13g2000cwo.googlegroups.com> References: <1114076862.063504.256970@g14g2000cwa.googlegroups.com> <1114129715.038945.227200@o13g2000cwo.googlegroups.com> Message-ID: <42684C3D.3060705@po-box.mcgill.ca> hawkesed said unto the world upon 2005-04-21 20:28: > Actually, > I think I got it now. Here is what I did: > >>>>for num in alist: > > ... if adict.has_key(num): > ... x = adict.get(num) > ... x = x + 1 > ... adict.update({num:x}) > ... else: > ... adict.update({num:1}) > ... > >>>>adict > > {128: 2, 129: 2, 132: 1, 153: 1, 30: 1, 53: 1, 57: 1, 61: 1, 66: 2, 67: > 1, 69: 2, 71: 1, 72: 1, 73: 2, 74: 1, 75: 2, 76: 2, 77: 2, 78: 2, 82: > 1, 84: 1, 85: 4, 87: 2, 88: 3, 89: 1, 91: 1, 92: 1, 93: 2, 94: 2, 95: > 3, 96: 1, 97: 3, 98: 2, 99: 1, 100: 6, 101: 4, 102: 2, 103: 1, 104: 1, > 105: 1, 106: 2, 107: 2, 108: 2, 109: 2, 111: 3, 112: 1, 114: 3, 115: 3, > 116: 3, 118: 1, 119: 2, 122: 2, 123: 1, 125: 1, 126: 1} > Thanks all for the help and best regards! > Ed > Hi Ed, I think there is a more Pythonic way. Here's something I used in a similar context: def get_frequency_dict(sequence): '''sequence of hashables -> dictionary of frequency of members Given a sequence of items, each of which is hashable (i.e. can serve as a key in a dictionary), the function returns a dictionary, using the items as keys, and the number of their occurrences as values. Usage: >>> get_frequency_dict([1,2,2,3,3,3,4,4,4,4]) {1: 1, 2: 2, 3: 3, 4: 4} >>> get_frequency_dict([[], "will fail as list aren't hashable"]) ... TypeError: list objects are unhashable ''' frequency_dict = {} for element in sequence: frequency_dict[element] = frequency_dict.setdefault( element, 0) + 1 return frequency_dict HTH, Brian vdB From bill.mill at gmail.com Wed Apr 27 10:17:13 2005 From: bill.mill at gmail.com (Bill Mill) Date: Wed, 27 Apr 2005 10:17:13 -0400 Subject: Which IDE is recommended? In-Reply-To: <426f90ac$1_2@rain.i-cable.com> References: <426f90ac$1_2@rain.i-cable.com> Message-ID: <797fe3d405042707174a30cd9d@mail.gmail.com> On 4/27/05, monkey wrote: > Read through python site for programming tool, really plenty of choices :-) > (For c++, I just can't breath with very very limited choices) > > Tried Spe, it come with wxGlade built-in very nice(is Spe still actively > develop?). But seem that Boa Constructor and PyDev(the plug-in for Eclipse) > also worth looking. Actually which one are you guys using? and why? I think > it is also valuable for those who are new to python as me. > Believe it or not, this has been discussed before :) Some relevant links, in no particular order: http://groups-beta.google.com/group/comp.lang.python/browse_frm/thread/e58230e15f7bb072/ec34f252a00c4b31?q=boa+wing+komodo&rnum=1#ec34f252a00c4b31 http://groups-beta.google.com/group/comp.lang.python/browse_frm/thread/4ac901800452fe52/32f9a7f307d16bbd?q=boa+wing+komodo&rnum=3#32f9a7f307d16bbd http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/b4301bf4de581351/84fea0f68251b810?q=ide&rnum=14#84fea0f68251b810 http://groups-beta.google.com/group/comp.lang.python/browse_frm/thread/6018db6e62e44895/46ef2516271a51d3?tvc=1&q=vim+emacs+komodo#46ef2516271a51d3 http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/a917d15f5a16500c/d989575525959c32?q=vim+emacs+komodo&rnum=4#d989575525959c32 http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/e3a65f2908bb8ba4/12ea5915f8f09546?q=vim+emacs+komodo&rnum=5#12ea5915f8f09546 http://groups-beta.google.com/group/comp.lang.python/browse_frm/thread/8cf3565673bc4a7e/a4a84c1e7271ca1a?tvc=1&q=vim+emacs+komodo#a4a84c1e7271ca1a http://groups-beta.google.com/group/comp.lang.python/browse_frm/thread/5de87dcdd817ba26/b2ff72c8e864818b?q=vim+emacs+wing&rnum=1#b2ff72c8e864818b http://groups-beta.google.com/group/comp.lang.python/browse_frm/thread/766c24a82674da7/47d9c8157639d81e?q=vim+wing+komodo&rnum=2#47d9c8157639d81e http://groups-beta.google.com/group/comp.lang.python/browse_frm/thread/b21e43c45f183dc7/3a118074c68f1f35?q=vim+wing+komodo&rnum=3#3a118074c68f1f35 http://groups-beta.google.com/group/comp.lang.python/browse_frm/thread/2225676eb7e1b4e/cdee764dfa2b5391?q=best+IDe&rnum=1#cdee764dfa2b5391 Peace Bill Mill bill.mill at gmail.com From bronger at physik.rwth-aachen.de Wed Apr 20 08:06:46 2005 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Wed, 20 Apr 2005 14:06:46 +0200 Subject: goto statement References: <20050420092359.81900.qmail@web8409.mail.in.yahoo.com> <42664190.6010507@i.com.ua> Message-ID: <87vf6hlkix.fsf@wilson.rwth-aachen.de> Hall?chen! Maxim Kasimov writes: > [...] > > WOW, just greate! ... but i'd like to relax at some more > interesting way than to comment each of rows Then just use a good editor. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus From sjmachin at lexicon.net Sat Apr 30 08:26:43 2005 From: sjmachin at lexicon.net (John Machin) Date: Sat, 30 Apr 2005 22:26:43 +1000 Subject: Best way to parse file into db-type layout? References: <7v1371pn9gvsh52m7nld6ddjm9b9k3elgf@4ax.com> Message-ID: On Sat, 30 Apr 2005 11:35:05 +0100, Michael Hoffman wrote: >John Machin wrote: >> Real-world data is not "text". > >A lot of real-world data is. For example, almost all of the data I deal with >is text. OK, depends on one's definitions of "data" and "text". In the domain of commercial database applications, there is what's loosely called "text": entity names, and addresses, and product descriptions, and the dreaded free-text "note" columns -- all of which (not just the "notes") one can end up parsing trying to extract extraneous data that's been dumped in there ... sigh ... > >>>That's nice. Well I agree with you, if the OP is concerned about embedded >>>CRs, LFs and ^Zs in his data (and he is using Windows in the latter case), >>>then he *definitely* shouldn't use fileinput. >> >> And if the OP is naive enough not to be concerned, then it's OK, is >> it? > >It simply isn't a problem in some real-world problem domains. And if there >are control characters the OP didn't expect in the input, and csv loads it >without complaint, I would say that he is likely to have other problems once >he's processing it. Presuming for the moment that the reason for csv not complaining is that the data meets the csv non-spec and that the csv module is checking that: then at least he's got his data in the structural format he's expecting; if he doesn't do any/enough validation on the data, we can't save him from that. > >> Except, perhaps, the reason stated in fileinput.py itself: >> >> """ >> Performance: this module is unfortunately one of the slower ways of >> processing large numbers of input lines. >> """ > >Fair enough, although Python is full of useful things that save the >programmer's time at the expense of that of the CPU, and this is >frequently considered a Good Thing. > >Let me ask you this, are you simply opposed to something like fileinput >in principle or is it only because of (1) no binary mode, and (2) poor >performance? Because those are both things that could be fixed. I think >fileinput is so useful that I'm willing to spend some time working on it >when I have some. I wouldn't use fileinput for a "commercial data processing" exercise, because it's slow, and (if it involved using the Python csv module) it opens the files in text mode, and because in such exercises I don't often need to process multiple files as though they were one file. When I am interested in multiple files -- more likely a script that scans source files -- even though I wouldn't care about the speed nor the binary mode, I usually do something like: for pattern in args: # args from an optparse parser for filename in glob.glob(pattern): for line in open(filename): There is also an "on principle" element to it as well -- with fileinput one has to use the awkish methods like filelineno() and nextfile(); strikes me as a tricksy and inverted way of doing things. Cheers, John From sjmachin at lexicon.net Sat Apr 30 19:16:22 2005 From: sjmachin at lexicon.net (John Machin) Date: Sun, 01 May 2005 09:16:22 +1000 Subject: Best way to parse file into db-type layout? References: <7v1371pn9gvsh52m7nld6ddjm9b9k3elgf@4ax.com> Message-ID: <391871t746ng3pgjlm8dv801qjd5cg9qem@4ax.com> On Sat, 30 Apr 2005 09:23:16 -0400, Steve Holden wrote: >John Machin wrote: >[...] >> >> I wouldn't use fileinput for a "commercial data processing" exercise, >> because it's slow, and (if it involved using the Python csv module) it >> opens the files in text mode, and because in such exercises I don't >> often need to process multiple files as though they were one file. >> >If the process runs once a month, and take ten minutes to process the >required data, isn't that fast enough. Depends: (1) criticality: could it have been made to run in 5 minutes, avoiding the accountant missing the deadline to EFT the taxes to the government (or, worse, missing the last train home)? (2) "Many a mickle makes a muckle": the total of all run times could be such that overnight processing doesn't complete before the day shift turns up ... > It's unwise to act as though >"slow" is an absolute term. > >> When I am interested in multiple files -- more likely a script that >> scans source files -- even though I wouldn't care about the speed nor >> the binary mode, I usually do something like: >> >> for pattern in args: # args from an optparse parser >> for filename in glob.glob(pattern): >> for line in open(filename): >> >> There is also an "on principle" element to it as well -- with >> fileinput one has to use the awkish methods like filelineno() and >> nextfile(); strikes me as a tricksy and inverted way of doing things. >> >But if it happens to be convenient for the task at hand why deny the OP >the use of a tool that can solve a problem? We shouldn't be so purist >that we create extra (and unnecessary) work :-), and principles should >be tempered with pragmatism in the real world. If the job at hand is simulating awk's file reading habits, yes then fileinput is convenient. However if the job at hand involves anything like real-world commercial data processing requirements then fileinput is NOT convenient. Example 1: Requirement is, for each input file, to display name of file, number of records, and some data totals. Example 2: Requirement is, if end of file occurs when not expected (including, but not restricted to, the case of zero records) display an error message and terminate abnormally. I'd like to see some code for example 1 that used fileinput (on a list of filenames) and didn't involve "extra (and unnecessary) work" compared to the "for filename in alist / f = open(filename) / for line in f" way of doing it. If fileinput didn't exist, what do you think the reaction would be if you raised a PEP to include it in the core? From Scott.Daniels at Acm.Org Wed Apr 20 13:09:36 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 20 Apr 2005 10:09:36 -0700 Subject: (Python newbie) Using XP-SP2/MSVC6: No Python24_d.lib,winzip barfs on Python-2.4.1.tar, cannot download bzip2 In-Reply-To: References: Message-ID: <4266871c$1@nntp0.pdx.net> Bill Davy wrote: > Thanks Jaime, > > I'm making gradual progress and am finding it quite satisfying. Resorted to > tracing Python in MSVC6 to see what it was trying to IMPORT, which is a bit > heavy but thank heavens for the sources. You might try running python from a command window and running it "-v" as in: python -v prog.py -args ... --Scott David Daniels Scott.Daniels at Acm.Org From has.temp2 at virgin.net Fri Apr 22 19:12:04 2005 From: has.temp2 at virgin.net (has) Date: 22 Apr 2005 16:12:04 -0700 Subject: Python licence again In-Reply-To: <87fyxilehj.fsf@pobox.com> References: <1114197761.019100.38890@o13g2000cwo.googlegroups.com> <87fyxilehj.fsf@pobox.com> Message-ID: <1114211524.594547.227060@o13g2000cwo.googlegroups.com> John J. Lee wrote: > Yes. ISTR that licence is a British English spelling, though my > British brain has been thoroughly contaminated by US spellings and > usage by now. Oh, it only gets worse: a couple years on the illiterate intarweb and even basics like "its" and "it's" become a major struggle. ;p > (Or are they like practice and practise, which (can) > mean subtly different things in British English Yep, we aim to confuse: licence, practice = noun license, practise = verb /grammar geek From maxm at mxm.dk Wed Apr 20 03:43:36 2005 From: maxm at mxm.dk (Max M) Date: Wed, 20 Apr 2005 09:43:36 +0200 Subject: To decode the Subject =?iso-8859-2?Q?=... in email in python In-Reply-To: <1113982235.201423.32480@l41g2000cwc.googlegroups.com> References: <1113982235.201423.32480@l41g2000cwc.googlegroups.com> Message-ID: <42660779$0$226$edfadb0f@dread12.news.tele.dk> Dan Polansky wrote: > When parsing messages using python's libraries email and mailbox, the > subject is often encoded using some kind of = notation. Apparently, the > encoding used in this notation is specified like =?iso-8859-2?Q?=... or > =?iso-8859-2?B?=. Is there a python library function to decode such a > subject, returning a unicode string? The use would be like > > human_readable = cool_library.decode_equals(message['Subject']) parts = email.Header.decode_header(header) new_header = email.Header.make_header(parts) human_readable = unicode(new_header) -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From igouy at yahoo.com Fri Apr 15 12:31:36 2005 From: igouy at yahoo.com (igouy at yahoo.com) Date: 15 Apr 2005 09:31:36 -0700 Subject: Is Python appropriate for web applications? In-Reply-To: References: Message-ID: <1113582696.738685.84860@l41g2000cwc.googlegroups.com> > > How about the speed of execution? > > There is no simple answer. Both languages use C functions which are > executed at CPU speed. But with interpreted code Python seems to be > approximately 3-4 times faster than PHP (http://dada.perl.it/shootout/). The Win32 Computer Language Shootout hasn't been updated for 22 months. The Great Computer Language Shootout Benchmarks were updated 2 days ago http://shootout.alioth.debian.org/great/ For those original Doug Bagley tests click on "The Doug Bagley" From michele.simionato at gmail.com Fri Apr 8 06:17:17 2005 From: michele.simionato at gmail.com (Michele Simionato) Date: 8 Apr 2005 03:17:17 -0700 Subject: decorating functions with generic signatures (not for the faint of heart) Message-ID: <1112955437.518384.56960@g14g2000cwa.googlegroups.com> I have realized today that defining decorators for functions with generic signatures is pretty non-trivial. Consider for instance this typical code: # def traced_function(f): def newf(*args, **kw): print "calling %s with args %s, %s" % (f.__name__, args, kw) return f(*args, **kw) newf.__name__ = f.__name__ return newf @traced_function def f1(x): pass @traced_function def f2(x, y): pass # This is simple and works: >>> from traced_function import traced_function, f1, f2 >>> f1(1) calling f1 with args (1,), {} >>> f2(1,2) calling f2 with args (1, 2), {} However, there is a serious disadvantage: the decorator replaces a function with a given signature with a function with a generic signature. This means that the decorator is *breaking pydoc*! $ pydoc2.4 traced_function.f1 Help on function f1 in traced_function: traced_function.f1 = f1(*args, **kw) You see that the original signature of f1 is lost: even if I will get an error when I will try to call it with a wrong number of arguments, pydoc will not tell me that :-( The same is true for f2: $ pydoc2.4 traced_function.f2 Help on function f2 in traced_function: traced_function.f2 = f2(*args, **kw) In general all functions decorated by 'traced_function' will have the same (too much) generic signature. This is a disaster for people like me that rely heavily on Python introspection features. I have found a workaround, by means of a helper function that simplifies the creation of decorators. Let's call this function 'decorate'. I will give the implementation later, let me show how it works first. 'decorate' expects as input two functions: the first is the function to be decorated (say 'func'); the second is a caller function with signature 'caller(func, *args, **kw)'. The caller will call 'func' with argument 'args' and 'kw'. 'decorate' will return a function *with the same signature* of the original function, but enhanced by the capabilities provided by the caller. In our case we may name the caller function 'tracer', since it just traces calls to the original function. The code makes for a better explanation: # from decorate import decorate def tracer(f, *args, **kw): print "calling %s with args %s, %s" % (f.func_name, args, kw) return f(*args, **kw) def traced_function(f): "This decorator returns a function decorated with tracer." return decorate(f, tracer) @traced_function def f1(x): pass @traced_function def f2(x, y): pass # Let me show that the code is working: >>> from traced_function2 import traced_function, f1, f2 >>> f1(1) calling f1 with args (1,), {} >>> f2(1,2) calling f2 with args (1, 2), {} Also, pydoc gives the right output: $ pydoc2.4 traced_function2.f2 Help on function f1 in traced_function2: traced_function2.f1 = f1(x) $ pydoc2.4 traced_function2.f2 Help on function f2 in traced_function2: traced_function2.f2 = f2(x, y) In general all introspection tools using inspect.getargspec will give the right signatures (modulo bugs in my implementation of decorate). All the magic is performed by 'decorate'. The implementation of 'decorate' is not for the faint of heart and ultimately it resorts to 'eval' to generate the decorated function. I guess bytecode wizards here can find a smarter way to generate the decorated function. But my point is not about the implementation (which is very little tested at the moment). My point is that I would like to see something like 'decorate' in the standard library. I think somebody already suggested a 'decorator' module containing facilities to simplify the usage of decorators. This post is meant as a candidate for that module. In any case, I think 'decorate' makes a good example of decorator pattern. Here is my the current implementation (not very tested): # def _signature_gen(varnames, default_args, n_args, rm_defaults=False): n_non_default_args = n_args - len(default_args) non_default_names = varnames[:n_non_default_args] default_names = varnames[n_non_default_args:n_args] other_names = varnames[n_args:] n_other_names = len(other_names) for name in non_default_names: yield "%s" % name for name, default in zip(default_names, default_args): if rm_defaults: yield name else: yield "%s = %s" % (name, default) if n_other_names == 1: yield "*%s" % other_names[0] elif n_other_names == 2: yield "*%s" % other_names[0] yield "**%s" % other_names[1] def decorate(func, caller): argdefs = func.func_defaults or () argcount = func.func_code.co_argcount varnames = func.func_code.co_varnames signature = ", ".join(_signature_gen(varnames, argdefs, argcount)) variables = ", ".join(_signature_gen(varnames, argdefs, argcount, rm_defaults=True)) lambda_src = "lambda %s: call(func, %s)" % (signature, variables) dec_func = eval(lambda_src, dict(func=func, call=caller)) dec_func.__name__ = func.__name__ dec_func.__doc__ = func.__doc__ dec_func.__dict__ = func.__dict__.copy() return dec_func # From prabapython at yahoo.co.in Fri Apr 22 02:36:37 2005 From: prabapython at yahoo.co.in (praba kar) Date: Fri, 22 Apr 2005 07:36:37 +0100 (BST) Subject: regarding system function Message-ID: <20050422063637.47212.qmail@web8403.mail.in.yahoo.com> Dear All, In Php If I send a command to system function then It will return 1 on success and 0 on failure. So based upon that value I can to further work. But In Python If I send a command to system function then It will return 0 only for both conditions(success and failure). So What I need to do for this. I want the result like php system function. regards Prabahar ________________________________________________________________________ Yahoo! India Matrimony: Find your life partner online Go to: http://yahoo.shaadi.com/india-matrimony From demon_slayer2839 at yahoo.com Thu Apr 28 13:34:44 2005 From: demon_slayer2839 at yahoo.com (demon_slayer2839 at yahoo.com) Date: 28 Apr 2005 10:34:44 -0700 Subject: OOP Message-ID: <1114709684.096071.109960@l41g2000cwc.googlegroups.com> Hey yall, I'm new to Python and I love it. Now I can get most of the topics covered with the Python tutorials I've read but the one thats just stumping me is Object Orientation. I can't get the grasp of it. Does anyone know of a good resource that could possibly put things in focus for me? Thanks. From Domenique.Tilleuil at gmail.com Wed Apr 20 14:40:08 2005 From: Domenique.Tilleuil at gmail.com (Domenique.Tilleuil at gmail.com) Date: 20 Apr 2005 11:40:08 -0700 Subject: pyGTK on Mouse over event ? Message-ID: <1114022408.677746.287630@f14g2000cwb.googlegroups.com> hello, Is there an event simular to the java event onMouseOver ? I want to get the coordinates of the mouse pointer when it is over an image ( GTKImage widget) I've tried using the EventBox with the motion_notify but that only seems to work when the mouse is pressed ? From andrea_gavana at tin.it Tue Apr 5 16:29:50 2005 From: andrea_gavana at tin.it (andrea_gavana at tin.it) Date: Tue, 5 Apr 2005 22:29:50 +0200 Subject: Add System Path?!? Message-ID: <4200063400021F9F@ims9c.cp.tin.it> Hello NG, sorry, I forgot to mention that I am on Windows... 2000 or XP, I don't think there will be any difference. Thank you! Andrea. From brian at brianandkate.com Tue Apr 5 14:11:56 2005 From: brian at brianandkate.com (Brian Blazer) Date: Tue, 05 Apr 2005 18:11:56 GMT Subject: playing with pyGoogle - strange codec error References: <2005040410062316807%brian@brianandkatecom> Message-ID: <2005040513115616807%brian@brianandkatecom> On 2005-04-04 10:06:23 -0500, Brian Blazer said: You know, I am beginning to think that I MAY have stumbled on a bug here. At first I was thinking that this issue was related to the offending character being out of range for the Mac. Then I tried it on A MS machine and a linux box; all with the same error. This does not happen when I wrote the same script in java. This is making me wonder if there is an issue with the wrapper for the google api that was originally done in java. For the sake of it, here is the full code (minus my google key). It is going to look wierd, but those print statements are there so that I dont have to open the file it is writing to every time I want to see stuff. it has my name hard coded into the search query. The commented r.snippet.encode(mac_roman) was there to see if by changing the encoding, I could make it work (no luck). I also tried putting #-*- coding: utf-8 -*- right after the shebang (as listed here: http://www.python.org/peps/pep-0263.html). Again, no help. Anyway, here is the code ------------------------> import google google.LICENSE_KEY = 'insertKeyHere' #print google.doSpellingSuggestion('helllo') data = google.doGoogleSearch('Brian Blazer') print 'Found %d results' % len(data.results) searchData = open('searchData.txt','w') for r in data.results: # r.snippet.encode('mac_roman') searchData.write ('Title: ' + r.title + '\n' + '\n') searchData.write ('URL: ' + r.URL + '\n' + '\n') searchData.write ('Snippet: ' + r.snippet + '\n' + '\n'+'\n') print r.URL print r.title print r.snippet -- Nail a post to the Spalted Board. Free WW'ing software and forums. Regular freebies! http://www.spaltedboard.com From zghelp at mail.powerleader.com.cn Tue Apr 26 05:10:05 2005 From: zghelp at mail.powerleader.com.cn (zghelp) Date: Tue, 26 Apr 2005 17:10:05 +0800 Subject: How to pass a arg of object to python's script in a c++ program? Message-ID: /*I am sorry the prev post is a mistake...*/ //the c++ code using namespace boost::python; struct World { void set(std::string msg) { this->msg = msg; } std::string greet() { return msg; } std::string msg; }; BOOST_PYTHON_MODULE(hello) { class_("World") .def("greet", &World::greet) .def("set", &World::set) ; } int _tmain(int argc, _TCHAR* argv[]) { Py_Initialize(); if (!Py_IsInitialized()) return -1; inithello(); PyRun_SimpleString("import sys"); PyRun_SimpleString("sys.path.append('./')"); PyObject* pName,*pModule,*pDict,*pFunc,*pArgs; pName = PyString_FromString("pytest"); pModule = PyImport_Import(pName); if (!pModule) return -1; pDict = PyModule_GetDict(pModule); if (!pDict) return -1; pFunc = PyDict_GetItemString(pDict,"add"); if (!pFunc || !PyCallable_Check(pFunc)) return -1; World w; w.set("hi from main!"); pArgs = PyTuple_New(3); PyTuple_SetItem(pArgs,0,Py_BuildValue("i",3)); PyTuple_SetItem(pArgs,1,Py_BuildValue("i",4)); PyTuple_SetItem(pArgs,2,Py_BuildValue("O",&w)); try { PyObject_CallObject(pFunc,pArgs); } catch(error_already_set) { // handle the exception in some way } Py_DECREF(pName); Py_DECREF(pArgs); Py_DECREF(pModule); Py_Finalize(); getchar(); return 0; } //the python's script import hello from hello import * def add(a,b,t): print "a + b = " + str(a+b) w = hello.World() w.set("hi from script!") print w.greet() print t.greet() return but the exception occur when run to "print t.greet()" How can I solve it? From listspam at flowtheory.net Fri Apr 8 13:02:38 2005 From: listspam at flowtheory.net (Joshua Ginsberg) Date: Fri, 8 Apr 2005 11:02:38 -0600 Subject: PPC OSX vs. x86 Linux Message-ID: Hello -- I writing some python code to do some analysis of my mail logs. I took a 10,000 line snippet from them (the files are about 5-6 million usually) to test my code with. I'm developing it on a Powerbook G4 1.2GHz with 1.25GB of RAM and the Apple distributed Python* and I tested my code on the 10,000 line snippet. It took 2 minutes and 10 seconds to process that snippet. Way too slow -- I'd be looking at about 20 hours to process a single daily log file. Just for fun, I copied the same code and the same log snippet to a dual-proc P3 500MHz machine running Fedora Core 2* with 1GB of RAM and tested it there. This machine provides web services and domain control for my network, so it's moderately utilized. The same code took six seconds to execute. Granted I've got the GUI and all of that bogging down my Mac. However, I had nothing else fighting for CPU cycles and 700MB of RAM free when my testing was done. Even still, what would account for such a wide, wide, wide variation in the time required to process the data file? The code is 90% regular expressions and string finds. Theories? Thanks! -jag * versions are: Python 2.3 (#1, Sep 13 2003, 00:49:11) [GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin and Python 2.3.3 (#1, May 7 2004, 10:31:40) [GCC 3.3.3 20040412 (Red Hat Linux 3.3.3-7)] on linux2 -------------- next part -------------- A non-text attachment was scrubbed... Name: Pasted Graphic.tiff Type: image/tiff Size: 17326 bytes Desc: not available URL: -------------- next part -------------- Joshua Ginsberg -- joshg at brainstorminternet.net Brainstorm Internet Network Operations 970-247-1442 x131 From jelleferinga at gmail.com Tue Apr 26 07:31:24 2005 From: jelleferinga at gmail.com (jelle) Date: 26 Apr 2005 04:31:24 -0700 Subject: how to pass an array to a VB array via COM Message-ID: <1114515084.138728.26180@g14g2000cwa.googlegroups.com> Hi, I'm trying to script Rhino -the nurbs modeller, not the server soft- via COM. Which is good fun, except i cant seem to pass arrays to the program. I suppose its expecting VB arrays, and is not to keen when i send a tuple: RS.AddCurve(((1,2,3),(4,5,6),(7,8,9)),3) --- Traceback (most recent call last): File " ", line 1, in ? File "c:\Python23\lib\site-packages\jf\interface\RhinoScript.py", line 48, in AddCurve return self._ApplyTypes_(77, 1, (12, 0), ((12, 0), (12, 16)), 'AddCurve', None,vaPoints, vaDegree) File "c:\Python23\lib\site-packages\win32com\client\__init__.py", line 446, in _ApplyTypes_ return self._get_good_object_( com_error: (-2147352567, 'Exception occurred.', (6, 'RhinoScript_m', 'Type mismatch in parameter. One-dimensional array required.', 'C:\\Program Files\\Rhinoceros 3.0\\RhinoScript_m.HLP', 393222, 0), None) --- This is somewhat puzzling, since when i define points in the application, these are returned as a tuple of tuples: >>>s = RS.GetPoints() >>>print s ((-7.0, -30.0, 0.0), (15.0, -24.0, 0.0), (-7.0, 12.0, 0.0), (14.0, 29.0, 0.0), (28.0, 10.0, 0.0), (20.0, 1.0, 0.0)) I've been searching this list for a solution, but didnt find anything i could use. Any ideas? Cheers, Jelle From andrevnobre at gmail.com Tue Apr 5 09:27:34 2005 From: andrevnobre at gmail.com (Andre Nobre) Date: Tue, 5 Apr 2005 10:27:34 -0300 Subject: start python web programming Message-ID: I should implement a simple http/database page, based on python. I read some texts and it?s strange how python deal with html output. It?s something like Servlet... is there any diferent way to do that? Something like just bussiness code, applied in an MVC framework, or just like it. Thanks and sorry about my english. -- Andr? Nobre andrevnobre at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From steven.bethard at gmail.com Sun Apr 24 23:24:22 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 24 Apr 2005 21:24:22 -0600 Subject: Multiple tuples for one for statement In-Reply-To: <1114398216.258027.105070@g14g2000cwa.googlegroups.com> References: <1114398216.258027.105070@g14g2000cwa.googlegroups.com> Message-ID: <-fCdnSQ0XbR6__HfRVn-ug@comcast.com> Harlin Seritt wrote: > I have three tuples of the same size: tup1, tup2, tup3 > > I'd like to do something like this: > > for a,b,c in tup1, tup2, tup3: > print a > print b > print c > > Of course, you get an error when you try to run the pseudocode above. > What is the correct way to get this done? for a, b, c in zip(tup1, tup2, tup3): print a print b print c If your tuples become iterators, look into itertools.izip. STeVe From sjmaster at gmail.com Wed Apr 27 11:55:39 2005 From: sjmaster at gmail.com (Steve M) Date: 27 Apr 2005 08:55:39 -0700 Subject: compile shebang into pyc file References: <1114528783.254398.299600@z14g2000cwz.googlegroups.com> Message-ID: <1114617339.180840.128590@z14g2000cwz.googlegroups.com> I just happened across the page linked to below, and remembered this thread, and, well... here you go: http://www.lyra.org/greg/python/ Executable .pyc files Ever wanted to drop a .pyc file right into your web server's cgi-bin directory? Frustrated because the OS doesn't know what to do with a .pyc? (missing the #! line) Look no further! :-) Below is a tiny Bash script to do this. "cat" your .pyc onto the end of this and drop it wherever you need direct execution of that .pyc From tzot at sil-tec.gr Wed Apr 20 12:02:00 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 20 Apr 2005 19:02:00 +0300 Subject: goto statement References: <20050420092359.81900.qmail@web8409.mail.in.yahoo.com> <42664190.6010507@i.com.ua> <87vf6hlkix.fsf@wilson.rwth-aachen.de> <70sc615akd7mfdkmrjls956o1u5rglm74t@4ax.com> Message-ID: On Wed, 20 Apr 2005 18:47:37 +0300, rumours say that Maxim Kasimov might have written: >by the way, "goto" statement will be useful for writing more powerful obfuscators At this point in time you might want to reconsider what are the true reasons you like python (if you really do :) -- TZOTZIOY, I speak England very best. "Be strict when sending and tolerant when receiving." (from RFC1958) I really should keep that in mind when talking with people, actually... From mefjr75 at hotmail.com Fri Apr 15 17:52:42 2005 From: mefjr75 at hotmail.com (M.E.Farmer) Date: 15 Apr 2005 14:52:42 -0700 Subject: Compute pi to base 12 using Python? In-Reply-To: References: Message-ID: <1113601962.316817.113510@g14g2000cwa.googlegroups.com> Sounds good should work fine ;) M.E.Farmer From g.brandl at gmx.net Tue Apr 5 15:50:52 2005 From: g.brandl at gmx.net (Georg Brandl) Date: Tue, 05 Apr 2005 21:50:52 +0200 Subject: Best editor? In-Reply-To: <1112729823.852393.107000@o13g2000cwo.googlegroups.com> References: <1112725379.514651.66540@l41g2000cwc.googlegroups.com> <1112729823.852393.107000@o13g2000cwo.googlegroups.com> Message-ID: <3bg8flF6kd62dU1@individual.net> beliavsky at aol.com wrote: > ChinStrap wrote: >> When not using the interactive prompt, what are you using? I keep >> hearing everyone say Emacs, but I can't understand it at all. I keep >> trying to learn and understand why so many seem to like it because I >> can't understand customization even without going through a hundred >> menus that might contain the thing I am looking for (or I could go >> learn another language just to customize!). > > Epsilon http://www.lugaru.com/ is a commercial Emacs-like editor with a > built-in Python mode and will automatically treat .py files as being > Python. No fiddling is required. It works well, and I spend many of my > waking hours in front of an Epsilon (even created a Fortran mode :)). I > think Epsilon is used more on Windows than Linux/Unix, where Emacs and > XEmacs have existed for a long time, but an Epsilon license contains > binaries for Linux and other Unices as well. $250 just for an Emacs clone? Sorry, but this is a bit greedy. Sure, it does some things differently, but in the same time you learn Epsilon, you can learn Emacs. > XEmacs/Emacs frustrate me, for example constantly asking if I want to > enable a "recursive mini-buffer", which I have no clue about or > interest in. Epsilon is a well-done Emacs IMO. constantly? You seem to make fundamental mistakes using Emacs. Reading one or two tutorials could have helped. mfg Georg From harlinseritt at yahoo.com Sun Apr 24 05:20:47 2005 From: harlinseritt at yahoo.com (Harlin Seritt) Date: 24 Apr 2005 02:20:47 -0700 Subject: Decent Win32All Documentation Message-ID: <1114334447.365988.197870@o13g2000cwo.googlegroups.com> Does anyone know of any decent documenation on Mark Hammond's win32all modules? I have tried looking at the documentation .chm file that comes with it, Python Programming On Win32 (OReilly book) and ActiveState's documentation and have found them all lacking -- yes I need it broken down to me. What I am hoping to do is to work on some Python versions of PSTools. I think the win32 modules will be perfect for helping me do this, however, I am having a (more than it should be) difficult time making sense of the win32process module. Any help would be appreciated. Thanks, Harlin Seritt From codecraig at gmail.com Thu Apr 14 15:13:04 2005 From: codecraig at gmail.com (codecraig) Date: 14 Apr 2005 12:13:04 -0700 Subject: py2exe + XML-RPC problem In-Reply-To: <1113496062.959951.41150@l41g2000cwc.googlegroups.com> References: <1113496062.959951.41150@l41g2000cwc.googlegroups.com> Message-ID: <1113505983.959632.168610@f14g2000cwb.googlegroups.com> sorry, I am actually still getting the 500 internal error I reported earlier. thanks for ur input. From michele.simionato at gmail.com Mon Apr 25 02:02:49 2005 From: michele.simionato at gmail.com (Michele Simionato) Date: 24 Apr 2005 23:02:49 -0700 Subject: Decorator pattern for new-style classes ? In-Reply-To: <1114243122.753678.311960@l41g2000cwc.googlegroups.com> References: <1114243122.753678.311960@l41g2000cwc.googlegroups.com> Message-ID: <1114408969.417640.272100@o13g2000cwo.googlegroups.com> I have no time for a long discussion, but the code should speak for itself: class Container(object): def __init__(self, content): self.content = content def __str__(self): return "" % self.content class Wrapped(object): def __init__(self, obj): self._obj = obj def __getattribute__(self, name): obj = super(Wrapped, self).__getattribute__("_obj") return getattr(obj, name) w = Wrapped(Container("hello")) print w.content print w.__str__() # works print w # does not work as you would expect, see bug report SF 729913 The discussion around the bug report is worth reading, Michele Simionato From winkler1 at gmail.com Wed Apr 27 19:26:02 2005 From: winkler1 at gmail.com (Jeff Winkler) Date: 27 Apr 2005 16:26:02 -0700 Subject: Trigraph Idiom - Original? Message-ID: <1114644362.854156.317830@l41g2000cwc.googlegroups.com> I've come up with a trigraph idiom, am curious if it's been done before (probably). I like to use trigraphs occasionally. Scenario: I'm doing an RSS->Javascript conversion for our intranet. I'd like to use different CSS class if a post is new. Code: hoursOld=abs(time.time()-time.mktime(i.modified_parsed))/3600 cssClass=['rssLink','rssLinkNew'][hoursOld<12] entry='%s' % (cssClass,i['link'],i['title']) So, ['rssLink','rssLinkNew'] is index by boolean value- False:0, or True:1. I realize many will find this hideous, but 3 lines of code to do something simple seems equally bad. Thoughts? Is there a better way? - Jeff From escalation746 at yahoo.com Sun Apr 3 21:41:59 2005 From: escalation746 at yahoo.com (robin) Date: Mon, 04 Apr 2005 02:41:59 +0100 Subject: SimpleRPCServer References: <4243efb6$0$248$14726298@news.sunsite.dk> Message-ID: <7n615192gnqbjs25dvvjttpvir72fqu2ot@4ax.com> Skip Montanaro wrote: >First, from my reading of SimpleXMLRPCServer, I don't think _dispatch() >belongs at that level. It belongs in the request handler class or in a >separate dispatcher class, depending on what version of Python you're using. Quite so. As a variant I just use verify_request() to persist the client IP address, and then wait until _dispatch() to do everything else. class RPCServer(SimpleXMLRPCServer): def verify_request(self, handler, address): self.client_ip, self.client_port = address return True def _dispatch(self, method, args): do_something(self.client_ip) Though using a firewall would not be remiss. :-) -- robin From apardon at forel.vub.ac.be Mon Apr 4 09:28:53 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 4 Apr 2005 13:28:53 GMT Subject: Queue.Queue-like class without the busy-wait References: <1111707620.556818.289300@g14g2000cwa.googlegroups.com> <7xmzsshzxr.fsf@ruckus.brouhaha.com> <7x8y4cyr70.fsf@ruckus.brouhaha.com> <7xoed86lnd.fsf@ruckus.brouhaha.com> <7xfyyjcu5w.fsf@ruckus.brouhaha.com> <7xmzshvm94.fsf@ruckus.brouhaha.com> Message-ID: Op 2005-04-02, Paul Rubin schreef : > Have you looked at this? A paper about adding asynchronous exceptions > to Python. > > http://www.cs.williams.edu/~freund/papers/02-lwl2.ps Looks interresting, but I doubt python will have it in the near future. I'm very pessimitic about python development in this area. -- Antoon Pardon From ojokimu at yahoo.co.uk Mon Apr 4 20:03:56 2005 From: ojokimu at yahoo.co.uk (John Ridley) Date: Tue, 5 Apr 2005 01:03:56 +0100 (BST) Subject: Super Newbie Question In-Reply-To: 6667 Message-ID: <20050405000356.90110.qmail@web26807.mail.ukl.yahoo.com> --- joeyjwc at gmail.com wrote: > In short, how might I go about deleting just the contents of a file? > I tried several methods with my limited knowledge but had no luck. I suppose the simplest thing to do would be to write an empty string to the file: >>> f = open('tmpfile.txt', 'w') >>> f.write('') >>> f.close() # or f.flush(), if keeping open HTH John Ridley Send instant messages to your online friends http://uk.messenger.yahoo.com From alexk at mailinator.com Thu Apr 28 13:54:20 2005 From: alexk at mailinator.com (alexk) Date: 28 Apr 2005 10:54:20 -0700 Subject: split question In-Reply-To: <3sudncKb35gWh-zfRVn-vA@comcast.com> References: <1114707749.969274.293560@l41g2000cwc.googlegroups.com> <3sudncKb35gWh-zfRVn-vA@comcast.com> Message-ID: <1114710859.990276.183880@o13g2000cwo.googlegroups.com> Yes, all of you are right. Thank you all for your answers - I'll use a regex. From mylastnameruntogether at mycompanyname.com Mon Apr 11 20:31:41 2005 From: mylastnameruntogether at mycompanyname.com (Brandon J. Van Every) Date: Tue, 12 Apr 2005 00:31:41 GMT Subject: web authoring tools References: Message-ID: =?iso-8859-15?Q?Pierre-Fr=E9d=E9ric_Caillaud?= wrote in news:op.so2yz4blqfv3if at localhost: > >>>> Ideally, I would like an open source website + html design tool >>>> implemented in Python >>> >>> didn't you just say that ideally, you wanted a tool written in lisp >>> or scheme? >> >> I honestly got a little tired of the tone of the answers I was >> getting from that crowd, about what an idiot I am. My query there is >> still > > You mean you are interested in a web application programming > framework in > the spirit of Seaside, or in a HTML/CSS editor in the spirit of > Dreamweaver ? I believe Dreamweaver-esque. I see myself writing articles and eventually doing snazzy eye candy layouts. I do not see myself engaging in elaborate flow control or anything terribly programmatic. I want to concentrate on the content, not the mechanism. -- Cheers, www.indiegamedesign.com Brandon Van Every Seattle, WA "The pioneer is the one with the arrows in his back." - anonymous entrepreneur From simon.brunning at gmail.com Fri Apr 22 04:51:01 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Fri, 22 Apr 2005 09:51:01 +0100 Subject: Run Unix shell command $ parse command line arguments in python In-Reply-To: <1114151943.109628.65500@f14g2000cwb.googlegroups.com> References: <1114151943.109628.65500@f14g2000cwb.googlegroups.com> Message-ID: <8c7f10c605042201514644fa7b@mail.gmail.com> On 21 Apr 2005 23:39:03 -0700, rkoida at yahoo.com wrote: > Kindly suggest me some ideas/comments. Why don't you make a start, and come back to us with whatever problems you encounter? We're happy to help, but we aren't going to do it for you. Andrew Dalke's "Wrapping command-line programs" series might come in handy: http://www.dalkescientific.com/writings/diary/archive/2005/04/12/wrapping_command_line_programs.html -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From shalabh at cafepy.com Sat Apr 2 13:30:34 2005 From: shalabh at cafepy.com (Shalabh Chaturvedi) Date: Sat, 02 Apr 2005 10:30:34 -0800 Subject: Performance issue In-Reply-To: References: Message-ID: Tom Carrick wrote: > Hi, > > In my attempted learning of python, I've decided to recode an old > anagram solving program I made in C++. The C++ version runs in less > than a second, while the python takes 30 seconds. I'm not willing to > think it's just python being slow, so I was hoping someone could find > a faster way of doing this. Also, I was wondering if there was a more > builtin, or just nicer way of converting a string to a list (or using > the sort function on a list) than making a function for it. Others have already given a good commentary and alternate suggestions. Here is some more (and some disagreements): * Know your data structures (and how long different operations take). Like don't do del L[0] unless required. This generally comes from experience (and asking on this list). * list(any_sequence_here) will build a list from the sequence. There are usually easy ways of converting built-in types - the Python docs will help you here. * Try to write code as close to an english description of the problem as possible. For example 'for word in words:' rather than using counters and []. This is usually faster, clearer and IMO an important ingredient of being 'Pythonic'. Anyway here's my rendition of your program: ### anagram = raw_input("Find anagrams of word: ") lanagram = list(anagram) lanagram.sort() sorted_anagram = ''.join(lanagram).lower() f = open('/usr/share/dict/words', 'r') found = [] for word in f: word = word.strip('\n') if len(word)==len(sorted_anagram): sorted_word = list(word) sorted_word.sort() sorted_word = ''.join(sorted_word) if sorted_word == sorted_anagram: found.append(word) print "Anagrams of %s:" % anagram for word in found: print word ### Hopefully it is fast enough. Shalabh From laura.skosnik at gmail.com Tue Apr 19 20:09:06 2005 From: laura.skosnik at gmail.com (lauras) Date: 19 Apr 2005 17:09:06 -0700 Subject: Python SSL Socket issue Message-ID: Hello, We are having an issue with Python SSL sockets using Apache and mod_python. When we try to get an SSL connection using the following code: con = httplib.HTTPSConnection( self.HOST, self.PORT ) #con.set_debuglevel(10) con.putrequest( "POST", "" ) con.putheader( "Content-Type", "text/xml" ) con.putheader( "content-length", int(len(cmd)) ) con.endheaders() con.send( cmd ) We get the following error: con.endheaders() File "/usr/lib/python2.3/httplib.py", line 715, in endheaders self._send_output() File "/usr/lib/python2.3/httplib.py", line 600, in _send_output self.send(msg) File "/usr/lib/python2.3/httplib.py", line 567, in send self.connect() File "/usr/lib/python2.3/httplib.py", line 988, in connect ssl = socket.ssl(sock, self.key_file, self.cert_file) File "/usr/lib/python2.3/socket.py", line 73, in ssl return _realssl(sock, keyfile, certfile) TypeError: ssl() argument 1 must be _socket.socket, not _socketobject Has anyone encountered this before or has any suggestions? Thanks, Laura From farcepest at gmail.com Thu Apr 14 18:25:44 2005 From: farcepest at gmail.com (Andy Dustman) Date: 14 Apr 2005 15:25:44 -0700 Subject: database in python ? References: <1113197530.990898.46130@z14g2000cwz.googlegroups.com> <1113339252.851450.184620@z14g2000cwz.googlegroups.com> <200504130853.31989.hancock@anansispaceworks.com> Message-ID: <1113517544.835410.238190@o13g2000cwo.googlegroups.com> Steve Holden wrote: > I don't know about the whole picture, but I know form evidence on this > group that there are PostgreSQL driver modules (the name "psycopg" comes > to mind, but this may be false memory) that appear to take diabolical > liberties with DBAPI-2.0, whereas my experience with MySQLdb has been > that I can interchange the driver with mxODBC (for example) as a drop-in > replacement (modulo the differing paramstyles :-(). There are a couple reasons for the interchangability: Marc-Andre Lemburg, the author of mxODBC, was also one of the main people involed with the DB API spec (now PEP-249). MySQLdb was also written with the spec in mind. One reason for this is that prior to writing MySQLdb, I used mxODBC in an application I wrote, connecting to a database called Solid: http://www.solidtech.com/ I don't think they sell the database as a separate product any more; at least my memory from the late 90's is that they stopped doing that. I've also done a bit of database work with pyscopg (a few years back), and there's not a marked difference between that and MySQLdb, as I recall. Parameter styles are the main difference between the three (MySQLdb and psycopg use pyformat or %s, and mxODBC uses qmark or ?). MySQLdb-1.4/2.0 will most likely support both styles as the latter is what MySQL expects for the Prepared Statement API that is new in 4.1. By "support both", I mean that you'll be able to configure at run-time which style you want to use. For feature comparisons, check out: http://dev.mysql.com/tech-resources/crash-me.php These comparisons are a little old, but you can compare MySQL-4.1.1 against PostgreSQL-7.3.3 and others. If speed is a critical factor, get both (they're free), put in some representative data for your application, and start benchmarking. From john_paul_ii at vatican.va Mon Apr 4 01:10:27 2005 From: john_paul_ii at vatican.va (Ioannes Paulus PP. II (Karol Wojtyla)) Date: Mon, 4 Apr 2005 05:10:27 GMT Subject: Last rites declaration of Ioannes Paulus PP. II (Karol Wojtyla) Message-ID: "The unforgiveable sins this earth must confront and overcome are Nationalism, capitalism, and hoarding. The idea of every nation should be forgot, price should be struck from the commons, and princes should be seen for the devils they are. The sins include our church, secret societies, and other religions which make of the spirit of God a divide." Last rites declaration of Ioannes Paulus PP. II (Karol Wojtyla) 2nd April 2005 -- o SECTION II: THE MISERY OF MAN WITHOUT GOD o SECTION III: OF THE NECESSITY OF THE WAGER o SECTION IV: OF THE MEANS OF BELIEF o SECTION V: JUSTICE AND THE REASON OF EFFECTS o SECTION VI: THE PHILOSOPHERS o SECTION VII: MORALITY AND DOCTRINE o SECTION VIII: THE FUNDAMENTALS OF THE CHRISTIAN RELIGION o SECTION IX: PERPETUITY o SECTION X: TYPOLOGY o SECTION XI: THE PROPHECIES o SECTION XII: PROOFS OF JESUS CHRIST o SECTION XIII: THE MIRACLES o SECTION XIV: APPENDIX: POLEMICAL FRAGMENTS ---------------------------------------------------------------------------- PENS?ES by Blaise Pascal 1660 translated by W. F. Trotter PENS?ES SECTION I: THOUGHTS ON MIND AND ON STYLE 1. The difference between the mathematical and the intuitive mind.--In the one, the principles are palpable, but removed from ordinary use; so that for want of habit it is difficult to turn one's mind in that direction: but if one turns it thither ever so little, one sees the principles fully, and one must have a quite inaccurate mind who reasons wrongly from principles so plain that it is almost impossible they should escape notice. But in the intuitive mind the principles are found in common use and From roccomoretti at hotpop.com Sun Apr 24 17:16:29 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Sun, 24 Apr 2005 16:16:29 -0500 Subject: Variables In-Reply-To: References: <426B0283.40602@cloudthunder.com> <426b0d03_3@newspeer2.tds.net> <426B1300.6090802@cloudthunder.com> <426B1A6F.2060401@cloudthunder.com> Message-ID: Richard Blackwood wrote: > Robert Kern wrote: > >> His problem is that he doesn't respect that technical terms can have >> different meanings in different fields and contexts. No authoritative >> reference can solve his problem for him. He's being overly pedantic >> about a field in which *he* is clearly not an authority. You can't >> convince such people, only ignore them. >> > Unfortunately that's not much of an option for me. We are working on a > project together so I am forced to either prove his notion incorrect or > I give in to his conception. *throws hands in air* Why are *you* the one that his notion is incorrect? Why isn't he the one that has to prove *you* incorrect? Put forth the Wikipedia article, and then the ball is in his court to disprove the arguments therein with a more authoritative source. (At least this is my understanding of the common rules of debate.) From steven.bethard at gmail.com Mon Apr 11 14:58:09 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 11 Apr 2005 12:58:09 -0600 Subject: Creating a new instance of a class by what is sent in? In-Reply-To: <1113244930.403334.66150@z14g2000cwz.googlegroups.com> References: <1113244930.403334.66150@z14g2000cwz.googlegroups.com> Message-ID: ChinStrap wrote: > I am sorry if this is obvious, but I am not seeing it. How would I go > about creating a new type that is of the same type as a class sent into > the function? > > new = foo.__init__() refers to the current foo, not a new fresh > instance of my class. The only way I can think of is to make a large > if-elif chain of isinstances, but that loses the generality I am after. It looks like you want to create a new _instance_ of the same type as an _instance_ passed in to a function. If this is correct, you can do this by: py> def new(obj): ... return type(obj)() ... py> new('s') '' py> new(3) 0 py> new(['a', 'b']) [] py> new((5.3, 3j)) () If you need to support old-style classes, replace type(obj) with obj.__class__. If this is not the question you meant to ask, could you reword things? Creating a new _type_ that is the same _type_ as something else doesn't make much sense to me. If it's a new _type_, then it shouldn't be the same as any existing type. STeVe From http Sat Apr 2 00:13:11 2005 From: http (Paul Rubin) Date: 01 Apr 2005 21:13:11 -0800 Subject: Simple thread-safe counter? References: <7x3bu9ss22.fsf_-_@ruckus.brouhaha.com> Message-ID: <7xy8c1hic8.fsf@ruckus.brouhaha.com> Tim Peters writes: > The GIL is your friend here: > > import itertools > f = itertools.count().next Thanks, I was hoping something like this would work but was not sure I could rely on it. > A similar thing can be done with xrange. But either way sucks if you > call it often enough to exceed the size of a Python short int > (platform C long). The obvious way with an explicit mutex doesn't > have that problem. Xrange, of course :). I don't need to exceed the size of a short int, so either of these should work fine. I wonder what measures the Pypy implementers will take (if any) to make sure these things keep working, but for now I won't worry about it. Out of interest, are the above guaranteed to work under Jython? What I'm doing right now is a short-term thing that will only have to run under CPython, but I like to do things the right way when I can. From Facundo.Batista at telefonicamoviles.com.ar Thu Apr 14 13:59:14 2005 From: Facundo.Batista at telefonicamoviles.com.ar (Batista, Facundo) Date: Thu, 14 Apr 2005 14:59:14 -0300 Subject: PyAr - Python Argentina 8th Meeting, today Message-ID: The Argentine Python User Group, PyAr, will have its eighth meeting today at 7:00pm. Agenda ------ Despite our agenda tends to be rather open, this time we would like to cover these topics: - Conclusions of PyAr in PyCon 2005. - See what we'll do with the t-shirts, and how we'll export them. - Analyze a future meeting point. Where ----- We're meeting at Hip Bar, Hip?lito Yirigoyen 640, Ciudad de Buenos Aires, starting at 19hs. We will be in the back room, so please ask the barman for us. About PyAr ---------- For more information on PyAr see http://pyar.decode.com.ar (in Spanish), or join our mailing list (Also in Spanish. For instructions see http://pyar.decode.com.ar/Members/ltorre/listademail) We meet on the second Thursday of every month. . Facundo -------------- next part -------------- An HTML attachment was scrubbed... URL: From mwm at mired.org Wed Apr 13 18:48:04 2005 From: mwm at mired.org (Mike Meyer) Date: Wed, 13 Apr 2005 17:48:04 -0500 Subject: permission References: <425c8b44$1@dnews.tpgi.com.au> Message-ID: <86aco2uwd7.fsf@guru.mired.org> Skip Montanaro writes: > James> Is it possible to check if you have permission to access and or > James> change a directory or file? > > Yes, but it's generally much easier to try, then recover from any errors: Especially since the answer to the question may change between checking and trying - so you have to be prepared to deal with failure either way. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From http Sat Apr 2 02:54:13 2005 From: http (Paul Rubin) Date: 01 Apr 2005 23:54:13 -0800 Subject: Simple thread-safe counter? References: <7x3bu9ss22.fsf_-_@ruckus.brouhaha.com> Message-ID: <7xsm29txzu.fsf@ruckus.brouhaha.com> Skip Montanaro writes: > How about (untested): > > import Queue > counter = Queue.Queue() > counter.put(0) > def f(): > i = counter.get() > counter.put(i+1) > return i Hmmm, that's a bit messier than I hoped for, but it looks sure to work. I think for my immediate requirement, I'm going to use xrange as Tim suggested. However, I can't be sure that will work in non-GIL implementations. From Bill at SynectixLtd.com Mon Apr 18 11:28:00 2005 From: Bill at SynectixLtd.com (Bill Davy) Date: Mon, 18 Apr 2005 15:28:00 +0000 (UTC) Subject: (Python newbie) Using XP-SP2/MSVC6: No Python24_d.lib, winzip barfs on Python-2.4.1.tar, cannot download bzip2 References: <1113834504.919986.129180@z14g2000cwz.googlegroups.com> Message-ID: "A.B., Khalid" wrote in message news:1113834504.919986.129180 at z14g2000cwz.googlegroups.com... > Bill Davy wrote: >> I downlaoded and installed >> http://www.python.org/ftp/python/2.4.1/python-2.4.1.msi >> >> I'm trying to build an extension using SWIG 1.3.24 and the linker > needs >> python24_d.lib (I do not have the DLL either). I've not found it in > any of >> the >> downloads. > I am no expert in MSVC6, but it sounds like maybe you need to supply > the no-debug switch in your extention setup.py file: /d NDEBUG. > > In case that does not work and help on this is not forthcoming, you can > always try pyMinGW[1]. > > > Regards, > Khalid Hmm, that's one possibility but I really do need to keep the debugger version going. I'm only just getting started. Any other suggestions? From gamma-ray at dope.comcast.net Fri Apr 29 23:37:39 2005 From: gamma-ray at dope.comcast.net (Anthony D'Agostino) Date: Fri, 29 Apr 2005 23:37:39 -0400 Subject: Sorting an Edge List References: Message-ID: <3YOdncf7-p0aYO_fRVn-tA@comcast.com> I found my old bubble sort solution: ============================================ def esort(edges): while 1: swaps = 0 for j in range(len(edges)-2): if edges[j][1] != edges[j+1][0]: edges[j+1],edges[j+2] = edges[j+2],edges[j+1] # swap swaps = 1 if swaps == 0: break return edges print esort([('A','Y'), ('J','A'), ('Y','J')]) print esort([(5,0), (6, -12), (0,6), (-12, 3)]) ============================================ The list can be any length and there will always be multiple valid solutions, depending on which edge you start with. I'm using this to sort edges for mesh subdivision. I just thought there might be a more elegant way to write it. From tjreedy at udel.edu Mon Apr 4 12:36:05 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 4 Apr 2005 12:36:05 -0400 Subject: re module non-greedy matches broken References: <115040egk00tf9d@corp.supernews.com><20611953.SkRsez8GTE@news.perlig.de><11516i9g0usp235@corp.supernews.com> <1152q99c7pjjl04@corp.supernews.com> Message-ID: > what book or books on regexes A standard is Mastering Regular Expressions, 2nd ed, by xxx (sorry, forget) TJR From jbo at cannedham.ee.ed.ac.uk Wed Apr 13 06:18:10 2005 From: jbo at cannedham.ee.ed.ac.uk (Jim) Date: Wed, 13 Apr 2005 11:18:10 +0100 Subject: how to explain such codes, python's bug or mine? In-Reply-To: References: Message-ID: MaHahaXixi wrote: >>>>j = range(20) >>>>print j > > [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] > >>>>for k in j: > > if k <= 10: > j.remove(k) > > > >>>>print j > > [1, 3, 5, 7, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19] > > > > Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on > win32 > Type "copyright", "credits" or "license()" for more information. > > i think python do convert there codes to such style: > for (i = 0; i < len(j); i++) > k = j[i] > ...... > what do u think? > > I'm not quite sure of your question but with the second style you're not attempting to change the original list but make a copy. That's perfectly easy to do in Python as it is. The exampmle is a cautionary one about changing the list on which you are iterating. Jim From jjl at pobox.com Fri Apr 29 15:29:45 2005 From: jjl at pobox.com (John J. Lee) Date: 29 Apr 2005 20:29:45 +0100 Subject: Can .py be complied? References: <426ec8f7_2@rain.i-cable.com> <1114696910.862093.100690@z14g2000cwz.googlegroups.com> Message-ID: Steve Holden writes: [...] > There's nothing wrong with open source projects catering to a market, > and there's nothing wrong with running open source software on a > proprietary operating system. To behave otherwise might reduce the > growth opportunities for Python and its community. > > no-zealotry-please-ly y'rs - steve [...] I'm hesitant to label everybody who disagrees with you (and me) on that a zealot. Though I tend to take the same side you do, I'm not entirely sure it's not just laziness on my part that I think that way. Seems to me that holding opinions such as "it's a bad thing to support open source software on closed source systems, and you should not do it, for the common good" is far from crazy, even though I don't currently happen to hold that view. John From sean_mcilroy at yahoo.com Mon Apr 4 02:39:12 2005 From: sean_mcilroy at yahoo.com (Sean McIlroy) Date: 3 Apr 2005 23:39:12 -0700 Subject: the bugs that try men's souls References: <1112515167.251511.116960@o13g2000cwo.googlegroups.com> <1112534521.797702.53630@l41g2000cwc.googlegroups.com> Message-ID: Wow again. I had a real "V8 moment" when I looked at your solution (smacking my forhead, groaning ruefully, etc). You were right: my intention was simply to hide the trivial cases from view; I completely missed the fact that I was now testing for membership in a different set. I should have remembered that python "plays fair", and looked a little harder to find my mistake. Thanks again, Sean From bokr at oz.net Sun Apr 24 16:51:02 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 24 Apr 2005 20:51:02 GMT Subject: Bounding box on clusters in a 2D list References: <1114287475.805112.42550@o13g2000cwo.googlegroups.com> <426b0f51.369660724@news.oz.net> <1114361089.412010.290250@g14g2000cwa.googlegroups.com> Message-ID: <426c04ca.432501303@news.oz.net> On 24 Apr 2005 09:44:49 -0700, "superprad at gmail.com" wrote: >Richter,yes what I am looking for is for cluster with rectangular >bounding boxes as you explained in the first figure. > Sorry, not your fault, but I'm still not clear on diagonal connection/separation. E.g., (removing punctuation ;-) is this 3 boxes or do the top left and bottom right connect at their touching corners and thus become bounded with a rectangle that then also includes the little box at the top right? +-------+ +---+ 0 | 1 1 | 0 | 1 | | | +---+ 0 | 1 1 | 0 0 +-------+?------+ 0 0 0 ? 1 1 | | | 0 0 0 | 0 1 | +-------+ +-------+ +---+ +-------+???+---+ +---------------+ 0 | 1 1 | 0 | 1 | 0 | 1 1 | 0 | 1 | 0 | 1 1 0 1 | | | +---+ | | +---+ | | 0 | 1 1 | 0 0 0 | 1 1 | 0 0 ? 0 | 1 1 0 0 | +-------+?------+ =>? | +-------+ => | | 0 0 0 ? 1 1 | 0 | 0 0 1 1 | 0 | 0 0 1 1 | | | | | | | 0 0 0 | 0 1 | 0 | 0 0 0 1 | 0 | 0 0 0 1 | +-------+ +---------------+ +---------------+ And what about nested boxes? +-------------------+ 0 | 1 1 1 1 1 | | | 0 | 1 0 0 0 1 | | +---+ | 0 | 1 0 | 1 | 0 1 | | +---+ | 0 | 1 0 0 0 1 | | | 0 | 1 1 1 1 1 | +-------------------+ Regards, Bengt Richter From xah at xahlee.org Tue Apr 12 06:25:33 2005 From: xah at xahlee.org (Xah Lee) Date: 12 Apr 2005 03:25:33 -0700 Subject: [perl-python] Python documentation moronicities (continued) Message-ID: <1113301533.054410.203710@z14g2000cwz.googlegroups.com> http://python.org/doc/2.4.1/lib/module-re.html http://python.org/doc/2.4.1/lib/node114.html --------- QUOTE The module defines several functions, constants, and an exception. Some of the functions are simplified versions of the full featured methods for compiled regular expressions. Most non-trivial applications always use the compiled form UNQUOTE What does a programer who wants to use regex gets out from this piece of motherfucking irrevalent drivel? ---------- QUOTE compile( pattern[, flags]) Compile a regular expression pattern into a regular expression object, which can be used for matching using its match() and search() methods, described below. The expression's behaviour can be modified by specifying a flags value. Values can be any of the following variables, combined using bitwise OR (the | operator). UNQUOTE What exactly is it fucking saying? I wanted to use regex to find & replace on text. I've read in a file. Trying to reading this fucking doc is a pain in the ass. What are these "flags"? Do i do re.compile(r'mypat','M') or re.compile(r'mypat',M) or perhaps re.compile(r'mypat',re.M) The M isn't a fucking variable. Why does the doc incompetently use that term? And what the fuck is it unclearly meant by "OR" operator with the mother fucking bitwise jargon? All a person reading regex really wanted is to see how to use a string pattern and replace it with another. The fucking doc cannot be possibly fucking worsely written. Fuck the mother fucking coders in the IT industry. So, is re.compile(r'mypat','M') re.compile(r'mypat','MULTILINE') equivalent? and, by that fucking bitwise shit is it meant to say like re.compile(r'mypat','M'|'U') ? why cannot this piece of shit writing give a single example of usage? and motherfucking confusedly organized, with fucking variable terms the writer don't fucking understand, and meanwhile always trying to sound big asshole and don't stop at masturbation by mention a regex book and not hesitate to mention another language Perl. Fucking morons. for a exposition of IT's fucking stupid docs and their fuckhead coders, see: http://xahlee.org/Periodic_dosage_dir/t2/xlali_skami_cukta.html a cleaned up account of this post will be appended to the above exposition. -------- One final piece of advice here to sober up the fuckheads who are currently offended and defiant: you want to ask yourself this question: Can a seasoned programer, who is expert at least 2 languages, who is also a expert at Perl and knew regex well, and who has also read the official Python tutorial and has written at least 10 simple python programs over a span of a month, can such a person, who have not yet used regex in Python but now wants to use regex in Python and have just read the doc, must he, resort to many trial and error to see exactly what the doc is talking about? But, can this doc be (re-)written effectively and easily so that any programers needn't do trial'n'error post-reading? The answer to the questions are resounding yeses, you fucking asses. paypal me a hundred dollars and i'll rewrite the whole re doc in a few hours. Fuck you the standard IT morons. Excuse me for i didn't have time to write a more coherent and detailed analysis of the stupidities of the re doc. Xah xah at xahlee.org ? http://xahlee.org/PageTwo_dir/more.html ? From gabriel.cooper at mediapulse.com Tue Apr 12 17:03:41 2005 From: gabriel.cooper at mediapulse.com (Gabriel Cooper) Date: Tue, 12 Apr 2005 17:03:41 -0400 Subject: Better access to database search results In-Reply-To: <8c7f10c60504120851224736e2@mail.gmail.com> References: <425BEA2A.6020302@mediapulse.com> <8c7f10c60504120851224736e2@mail.gmail.com> Message-ID: <425C37AD.1040102@mediapulse.com> Simon Brunning wrote: >On Apr 12, 2005 4:32 PM, Gabriel Cooper wrote: > > >>Usually when I access db search results it's something like this: >> >>cursor.execute("select A1,A2,A3,A4 from B where C") >>for (a1,a2,a3,a4) in cursor.fetchall(): >> stuff() >> >>But sometimes the point at which I use the data returned is not with the >>search, and so having the ability to access the results as a dictionary >>is more useful. >> >>Let me know what you think. Could this be done simpler? >> >> >> > >Have you come across dtuple? >(). It's really easy to use >- . > > Hm. that's interesting, it's pretty much the same idea, only I do all the processing up front and return a complete variable that's generally indistinguishable from a list of dictionaries. This method (at least in the ASPN example) appears to prefer that you process each record as you come to it (which is undoubtedly more scalable). For my purposes, where as little programming logic as possible is required in the "view" section of code, I'm willing to accept the idea that I won't be using my function on immense amounts of data. To explain, I develop websites using Snakeskin (http://snakeskin-tools.sf.net/). It separates design and logic by first processing a python object with specific event triggers and then loads the requested template to accompany it. The python object does the logic, the template does the display. e.g. def page_process(self, ctx): c = ctx.request.db.cursor() c.execute("select a,b,c ....") ctx.locals.some_var = c.fetchall() # anything in ctx.locals is available as a var in the template then in the template: ... Print out A: Print out B: ... ... -------------- next part -------------- An HTML attachment was scrubbed... URL: From jzgoda at gazeta.usun.pl Thu Apr 7 16:03:19 2005 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Thu, 07 Apr 2005 22:03:19 +0200 Subject: Distributing Python Apps and MySQL In-Reply-To: References: <1112887332.324949.318960@z14g2000cwz.googlegroups.com> Message-ID: rbt napisa?(a): > I don't think one can distribute mysql within a software package w/o > buying a commercial license to do so. Check out their licensing on their > website here: > > "When your application is not licensed under either the GPL-compatible > Free Software License as defined by the Free Software Foundation or > approved by OSI, and you intend to or you may distribute MySQL software, > you must first obtain a commercial license to the MySQL product." > > http://www.mysql.com/company/legal/licensing/commercial-license.html Don't see any legal problem here, if package is on GPL-compatible or OSI-approved license. Anyway, if you want this "installer" to be multiplatform, I think you should write one. There are many good installer software packages for Windows (chief among free ones are Inno Setup and NSInstall), but I know only one for linux platform -- the one that XFCE uses and I don't know its internals, so I will speak only for Inno Setup for Windows. It's really comprehensive tool set, as you can perform many tasks during installation -- you can install subpackages, perform pre- and post-installation steps and automate many tasks, providing they can be scripted. See http://www.jrsoftware.org/isinfo.php and read documentation, it's definitely worth this. -- Jarek Zgoda http://jpa.berlios.de/ | http://www.zgodowie.org/ From reinhold-birkenfeld-nospam at wolke7.net Sun Apr 3 07:07:20 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Sun, 03 Apr 2005 13:07:20 +0200 Subject: Help with splitting In-Reply-To: <1112493381.965950.89130@o13g2000cwo.googlegroups.com> References: <1112394051.064413.250990@g14g2000cwa.googlegroups.com> <1112493381.965950.89130@o13g2000cwo.googlegroups.com> Message-ID: <3ba128F6bbqolU1@individual.net> George Sakkis wrote: > If you don't want any null strings at the beginning or the end, an > equivalent regexp is: > >>>> whitespaceSplitter_2 = re.compile("\w+|\s+") >>>> whitespaceSplitter_2.findall("1 2 3 \t\n5") > ['1', ' ', '2', ' ', '3', ' \t\n', '5'] >>>> whitespaceSplitter_2.findall(" 1 2 3 \t\n5 ") > [' ', '1', ' ', '2', ' ', '3', ' \t\n', '5', ' '] Perhaps you may want to use "\s+|\S+" if you have non-alphanumeric characters in the string. Reinhold From grig.gheorghiu at gmail.com Wed Apr 6 13:03:33 2005 From: grig.gheorghiu at gmail.com (Grig Gheorghiu) Date: 6 Apr 2005 10:03:33 -0700 Subject: Establishing connection SSH In-Reply-To: <1112779780.058547.270960@o13g2000cwo.googlegroups.com> References: <1112779780.058547.270960@o13g2000cwo.googlegroups.com> Message-ID: <1112807013.726577.323060@o13g2000cwo.googlegroups.com> Try paramiko: http://www.lag.net/paramiko/ Grig From miki.tebeka at zoran.com Tue Apr 12 09:11:48 2005 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Tue, 12 Apr 2005 16:11:48 +0300 Subject: Tkinter "withdraw" and "askstring" problem Message-ID: <20050412131148.GT2960@zoran.com> Hello All, The following script "hangs" on win32 system: from Tkinter import * from tkSimpleDialog import askstring root = Tk() root.withdraw() # <<< Problem here askstring("Yap", "What's up?") If I remove the problematic "withdraw" line the script works but there is another Tk window at the back. Any way to solve the problem? Thanks. -- ------------------------------------------------------------------------ Miki Tebeka http://tebeka.bizhat.com The only difference between children and adults is the price of the toys -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 193 bytes Desc: not available URL: From mahs at telcopartners.com Thu Apr 14 18:25:58 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Thu, 14 Apr 2005 15:25:58 -0700 Subject: Supercomputer and encryption and compression @ rate of 96% In-Reply-To: References: <1113470846.970773.4780@g14g2000cwa.googlegroups.com><1113490437.037734.158740@g14g2000cwa.googlegroups.com> <425EB9CA.1010708@transnorm.ch> Message-ID: Fredrik Lundh wrote: > Tiziano Bettio wrote: > > >>could someone please tell me that this thread wasn't a aprilsfoll day >>joke and it is for real... >> >>i'm pretty much able to go down to a single bit but what would be the >>reverse algorithm as stated by martin... > > > magic? > > I suggest running my script on a couple of small text files. when you've done that, > see if you can figure out how the decompression algorithm works. > > > Tricky - especially checking the parity of the data bit, but I believe the following works: def decompress(filename): m = '\x00\x00\x0fE\xc7\xc4' m = [(ord(i) & 0x7F) - (ord(i) & 0x80) for i in m] filename, data = open(filename, "rb").read(), filename[:-4] class Unfold(object): # Accumulator for partially unfolded data args = [] try: unfold = Unfold() data = "==".join([data,'\n']) compressed = [abs(data)] for fold in compressed: unfold.args.append(fold ** abs(fold)) except TypeError, unfold: # No more unfolds pass decoder = __import__("".join(chr(ord(i)+j) for i, j in zip(unfold.args[0], m))).decodestring return decoder(data) Michael From jerf at jerf.org Fri Apr 8 12:07:30 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Fri, 08 Apr 2005 12:07:30 -0400 Subject: args attribute of Exception objects References: Message-ID: On Fri, 08 Apr 2005 09:32:37 +0000, S?bastien de Menten wrote: > Hi, > > When I need to make sense of a python exception, I often need to parse the > string exception in order to retrieve the data. What exactly are you doing with this info? (Every time I started to do this, I found a better way. Perhaps one of them will apply for you.) (As a general comment, I'd point out that you don't have to check the entire error message; checking for a descriptive substring, while still not "safe", is at least safe*r*.) From mmrsva at gmail.com Tue Apr 26 05:20:02 2005 From: mmrsva at gmail.com (Marcio Rosa da Silva) Date: Tue, 26 Apr 2005 11:20:02 +0200 Subject: Order of elements in a dict Message-ID: Hi! In dictionaries, unlinke lists, it doesn't matter the order one inserts the contents, elements are stored using its own rules. Ex: >>> d = {3: 4, 1: 2} >>> d {1: 2, 3: 4} So, my question is: if I use keys() and values() it will give me the keys and values in the same order? In other words, it is safe to do: >>> dd = dict(zip(d.values(),d.keys())) to exchange keys and values on a dictionary? Or I can have the values and keys in a different order and end with something like this: >>> dd {2: 3 , 4: 1} instead of: >>> dd {2: 1, 4: 3} For this example it works as I wanted (the second output), but can I trust this? Also, if someone has a better way to exchange keys and values in a dict, I would like to learn. :-) Thanks! Marcio From fredrik at pythonware.com Tue Apr 5 13:40:54 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 5 Apr 2005 19:40:54 +0200 Subject: re module non-greedy matches broken References: <115040egk00tf9d@corp.supernews.com><11535p0mdgqde1@corp.supernews.com> <1155et6khhpqu8c@corp.supernews.com> Message-ID: "lothar" wrote: >a non-greedy match is implicitly defined in the documentation to be one such > that there is no proper substring in the return which could also match the > regex. no, that's not what it says. this is what is says: Adding "?" after the qualifier makes it perform the match in non-greedy or minimal fashion; as few characters as possible will be matched. note that it says "qualifier" (that is, the preceeding *, +, or ? operator). it doesn't say that the *entire* regex should be non-greedy. it does not say that search, findall, sub etc. should look for the shortest possible overall match. all it says is that the preceeding operator, and that operator only, should look for the shortest possible match, rather than the longest. > the module does not return a non-greedy match. it does. the problem is all in your head. From philippecmartin at sbcglobal.net Thu Apr 14 14:57:34 2005 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Thu, 14 Apr 2005 13:57:34 -0500 Subject: Using python from a browser Message-ID: <200504141357.34646.philippecmartin@sbcglobal.net> Hi, I have a python script I wish to call from various browsers (IE; Mozilla, Firefox ..) on Windows & Linux. I read that IE had the capability to embedd Python scripts, but what about the others ? Regards, Philippe -- ************************************* Philippe C. Martin SnakeCard, LLC www.snakecard.com +1 405 694 8098 ************************************* From fredrik at pythonware.com Sat Apr 9 04:50:19 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 9 Apr 2005 10:50:19 +0200 Subject: Counting iterations References: <1112994185.983954.234650@l41g2000cwc.googlegroups.com><4256f4c0$0$2603$da0feed9@news.zen.co.uk> <1112998861.316958.152060@g14g2000cwa.googlegroups.com> Message-ID: Derek Basch wrote: > ooops you are right. Should have been: > > pets = ["cat", "dog", "bird"] > num_pets = 0 > for i in pets: > num_pets += 1 > print "pet" + "#" + num_pets Traceback (most recent call last): File "example.py", line 5, in ? print "pet" + "#" + num_pets TypeError: cannot concatenate 'str' and 'int' objects From hongqn at gmail.com Sat Apr 16 04:20:34 2005 From: hongqn at gmail.com (Qiangning Hong) Date: 16 Apr 2005 01:20:34 -0700 Subject: distutils question: different projects under same namespace Message-ID: <1113639634.729450.191360@l41g2000cwc.googlegroups.com> To avoid namespace confliction with other Python packages, I want all my projects to be put into a specific namespace, e.g. 'hongqn' package, so that I can use "from hongqn.proj1 import module1", "from hongqn.proj2.subpack1 import module2", etc. These projects are developed and maintained and distributed seperately, so I should not make a whole 'hongqn' package with one setup.py. I must write setup.py scripts for each project. I meet a problem here. For instance, I am writing setup.py script for proj1. I use the following parameters when calling distutils.core.setup: setup( ... package_dir = {'hongqn.proj1': 'proj1'}, packages = ['hongqn.proj1'], ... ) "python setup.py install" will create /usr/lib/python2.3/hongqn/proj1 directory and copy proj1/*.py there. But this is UNUSABLE! There is NO __init__.py file under /usr/lib/python2.3/hongqn/ so that import hongqn.proj1 will fail! I am considering manually create this __init__.py by hacking the install_lib command. But before making my hands dirty, I want to know if there is an "official" solution exists or others have already success stories on this matter. As a note, I wish the solution can handle setup.py bdist and bdist_wininst well. From mylastnameruntogether at mycompanyname.com Mon Apr 11 13:31:29 2005 From: mylastnameruntogether at mycompanyname.com (Brandon J. Van Every) Date: Mon, 11 Apr 2005 17:31:29 GMT Subject: web authoring tools References: <844k515hnt5h470jf50dd5r9sumn4q59qu@4ax.com> Message-ID: Ron_Adam wrote in >> >>http://www.igda.org/seattle/ >>http://www.cyphondesign.com/ >>http://www.alphageeksinc.com/ >>http://www.gamasutra.com > > These top three where done with text editors. If you view the source, > you will notice the formatting has good consistent indenting and there > isn't a lot of extra tags or other information needlessly inserted. > > They make good use of CSS for formatting also. If this is the type of > thing you want, save the pages and study how they did it. Use your > own text and graphics of course. Thanks for that insight. It may not be the answer I exactly wanted to hear, but it does ring true with regards to my FrontPage 2000 experience. -- Cheers, www.indiegamedesign.com Brandon Van Every Seattle, WA "The pioneer is the one with the arrows in his back." - anonymous entrepreneur From pythonch at nospam.not.com Fri Apr 29 16:38:53 2005 From: pythonch at nospam.not.com (pythonchallenge) Date: Fri, 29 Apr 2005 23:38:53 +0300 Subject: Python Challenge ahead [NEW] for riddle lovers Message-ID: For the riddles' lovers among you, you are most invited to take part in the Python Challenge, the first python programming riddle on the net. You are invited to take part in it at: http://www.pythonchallenge.com From edcjones at comcast.net Fri Apr 1 20:06:33 2005 From: edcjones at comcast.net (Edward C. Jones) Date: Fri, 01 Apr 2005 20:06:33 -0500 Subject: Module subprocess: How to "communicate" more than once? Message-ID: <1eOdnVIK972XbdDfRVn-og@comcast.com> I have a program named "octave" (a Matlab clone). It runs in a terminal, types a prompt and waits for the user to type something. If I try # Run octave. oct = subprocess.Popen("octave", stdin=subprocess.PIPE) # Run an octave called "startup". oct.communicate("startup") # Change directory inside octave. oct.communicate("cd /home/path/to/my/dir") I get: Traceback (most recent call last): File "./popen.py", line 29, in ? oct.communicate("cd /home/path/to/my/dir") File "/usr/local/lib/python2.4/subprocess.py", line 1044, in communicate self.stdin.flush() ValueError: I/O operation on closed file How do I set up a subprocess so I can send it a command and get the answer, then send it another command and get an answer, etc.? From rune.strand at gmail.com Thu Apr 28 15:42:34 2005 From: rune.strand at gmail.com (runes) Date: 28 Apr 2005 12:42:34 -0700 Subject: Setting win32 console title from Python References: <1114684215.236448.212970@g14g2000cwa.googlegroups.com> <1114696780.653849.220080@o13g2000cwo.googlegroups.com> <1114698836.708809.32780@o13g2000cwo.googlegroups.com> Message-ID: <1114717354.209028.30270@z14g2000cwz.googlegroups.com> Hi Duncan, sorry, I was unprecise. I'm thinking of a script, called t.py that can be used in the console like an ordinary command. Som if I change directory from S:\scripts to d:\projects and execute the script the title changes to "projects" etc. I have that functionality today with a combination of a python script and a batch file. I just wondered if I could use python all the way. Apparently I cannot. Here are the scripts: ------ DirInPath:\t.bat -------------------------------- @echo off :: reads bare directory name from file :: created by external Python script set DIR_FILE_NAME=DOS_IS_TERRIBLE.tmp PyBareDir.py %DIR_FILE_NAME% for /F "eol=;" %%t in (%DIR_FILE_NAME%) do ( title %%t ) del /Q /F DOS_IS_TERRIBLE.tmp ------------------------------------------------------------ ------ DirInPath:\PyBareDir.py -------------------------------- # extracts bare directory name and writes # it to file with name given as argument. from os import getcwd from os.path import basename import sys try: saveAsName = sys.argv[1] lastDir = basename(getcwd()) XWwz(saveAsName, 'w+').write(lastDir + '\n;') except: print "PyBareDir failed:", sys.exc_info()[1] ----------------------------------------------------------------------- From sjmachin at lexicon.net Mon Apr 18 17:49:58 2005 From: sjmachin at lexicon.net (John Machin) Date: Tue, 19 Apr 2005 07:49:58 +1000 Subject: Behaviour of str.split References: <4263cf31$0$26348$db0fefd9@news.zen.co.uk> Message-ID: <24a8619qhstqjrfi6vdit27bo8r4afd5nf@4ax.com> On Mon, 18 Apr 2005 16:16:00 +0100, Will McGugan wrote: >Hi, > >I'm curious about the behaviour of the str.split() when applied to empty >strings. > >"".split() returns an empty list, however.. > >"".split("*") returns a list containing one empty string. > >I would have expected the second example to have also returned an empty >list. What am I missing? > You are missing a perusal of the documentation. Had you done so, you would have noticed that the actual behaviour that you mentioned is completely the reverse of what is in the documentation! """ Splitting an empty string with a specified separator returns an empty list. If sep is not specified or is None, a different splitting algorithm is applied. Splitting an empty string or a string consisting of just whitespace will return "['']". """ As you stumbled on this first, you may have the honour of submitting a patch to the docs and getting your name on the roll of contributors. Get in quickly, before X** L** does :-) Cheers, John From kent37 at tds.net Sat Apr 16 16:41:28 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat, 16 Apr 2005 16:41:28 -0400 Subject: pydoc preference for triple double over triple single quotes -- anyreason? In-Reply-To: References: Message-ID: <42617449_3@newspeer2.tds.net> Brian van den Broek wrote: > Hi all, > > I'm posting partly so my problem and solution might be more easily found > by google, and partly out of mere curiosity. > > I've just spent a frustrating bit of time figuring out why pydoc didn't > extract a description from my module docstrings. Even though I had a > well formed docstring (one line, followed by a blank line, followed by > the rest of the docstring), when I ran Module docs, my modules showed up > as having "no description". ("Module docs" referring to the shortcut > installed on Windows that launches the pydoc server.) ?? It works for me with triple-single quoted strings...from a quick look it appears that pydoc uses inspect which looks at the __doc__ attribute; do your modules have __doc__ attributes? Kent From nick at craig-wood.com Mon Apr 25 06:30:01 2005 From: nick at craig-wood.com (Nick Craig-Wood) Date: 25 Apr 2005 10:30:01 GMT Subject: Python licence again References: <1114197761.019100.38890@o13g2000cwo.googlegroups.com> <87fyxilehj.fsf@pobox.com> <1114211524.594547.227060@o13g2000cwo.googlegroups.com> Message-ID: has wrote: > licence, practice = noun > license, practise = verb Tick ;-) -- Nick Craig-Wood -- http://www.craig-wood.com/nick From kennywiggin at yahoo.com Fri Apr 29 20:11:49 2005 From: kennywiggin at yahoo.com (kennywiggin) Date: Sat, 30 Apr 2005 00:11:49 -0000 Subject: python and os.system() failure Message-ID: Hi, I'm actually not sure where the error is actually occurring, but the effects are easily reproduced, but not reproducable. By not reproducable, I mean the error does not occur exactly in the same "spot" but it always happens. I have my CD collection ripped to flac, so I have >4000 flacs. I wrote this script that will automatically encode the flacs into mp3 or ogg while transferring all the metaflac info over to id3 tag of the mp3. Generally, the script works like this: Get list of flac for each flac file: Store metaflac_info in an information class os.system(decode flac using /usr/bin/flac) os.system(encode mp3 and embed info stored in class) Now, this script will go on for some time but after 40-100 files the decode will fail with /usr/bin/flac reporting an error in reading the flac file. .flac: ERROR while decoding data state = FLAC__STREAM_DECODER_READ_FRAME The script fails to decode any more flac files until the vm crashes from having too many open files. The flac file is perfectly fine, though. Restarting the script, the flac file that "crashed" decodes/encodes just fine. Analysis by 'flac -t' or 'flac -a' show a correct flac file. How ever, if I try to decode a "bad" flac file in parallel with the script after the script has "failed", I can't decode the flac and get the same error. Yet, I can do 'flac -a' or 'flac -t' on the file and it reports 100% good in parallel to the "dead" script. It is not a disk space issue as I've checked. No stray tempfiles are created since the command to create them fails when opening the flac file. I have tried invoking garbage collection after a set number of file and sleeping the thread after running into the error, but neither worked. The most likely culprit is my script, but it seems too simple to "die" like that. I don't think it's a problem with the 'flac' application. Another possible culprit is a python VM issue that I am not aware of. Any advice would be appreciated, Kenny Debian Linux, i686 Python 2.3 (2.3.5-2) and earlier versions of 2.3 flac 1.1.1 (1.1.1-5) From mefjr75 at hotmail.com Sun Apr 17 20:16:30 2005 From: mefjr75 at hotmail.com (M.E.Farmer) Date: 17 Apr 2005 17:16:30 -0700 Subject: Finding name of running script In-Reply-To: <1113778866.595981.186480@f14g2000cwb.googlegroups.com> References: <1113778866.595981.186480@f14g2000cwb.googlegroups.com> Message-ID: <1113783390.440857.302680@l41g2000cwc.googlegroups.com> > print locals()['__file__'].split(sep)[-1] .split(sep)[-1] is pretty dense reading. try: print os.basename(locals()['__file__']) runes wrote: > Is it a more pythonic way of finding the name of the running script > than these? > > from os import sep > from sys import argv > > print argv[0].split(sep)[-1] > # or > print locals()['__file__'].split(sep)[-1] > # or > print globals()['__file__'].split(sep)[-1] M.E.Farmer From jepler at unpythonic.net Tue Apr 19 20:32:06 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 19 Apr 2005 19:32:06 -0500 Subject: Writing to stdout and a log file In-Reply-To: <1113956275.697789.324730@o13g2000cwo.googlegroups.com> References: <1113956275.697789.324730@o13g2000cwo.googlegroups.com> Message-ID: <20050420003203.GA26325@unpythonic.net> This variation works: #------------------------------------------------------------------------ class Tee: def __init__(self, *args): self.files = args def write(self, data): for f in self.files: result = f.write(data) return result def writelines(self, seq): for i in seq: self.write(i) import sys sys.stdout = Tee(sys.stdout, open("/tmp/stdout.log", "w")) print 'STDOUT', sys.stdout #------------------------------------------------------------------------ It appears that the 'print' statement always uses file.write if isinstance(sys.stdout, file). I don't know whether this has been reported as a bug before, or if there's a reason for the current behavior. It may be an accidental behavior that is left over from the days when builtin types were not subclassable. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From mlernerNO at SPAMumich.edu Thu Apr 7 12:35:20 2005 From: mlernerNO at SPAMumich.edu (Michael George Lerner) Date: Thu, 07 Apr 2005 16:35:20 GMT Subject: Best editor? References: <1112725379.514651.66540@l41g2000cwc.googlegroups.com> Message-ID: Nicolay A. Vasiliev wrote: > Hello! > What do you think all about ActiveState Komodo? Is this specifically to me? I haven't tried it, but I'm tempted. I've recently begun teaching my wife some Python in order to help her write a useful GUI app, and that makes it look particularly tempting. I'm using BoaConstructor for the GUI stuff at the moment. It has a bit of a learning curve, but it looks nice so far. -michael > Michael George Lerner wrote: > >Aahz wrote: > > > > > > > >>Use vim. 80% of the power of emacs at 20% of the learning curve. > >> > >> > > > >A system administrator said this to me about unix a long time ago, > >but it applies equally well to emacs: > > > >Emacs is a great place to live, but I'd hate to visit. > > > >-michael, an (x)emacs user > > > > > > From john at castleamber.com Mon Apr 25 15:33:54 2005 From: john at castleamber.com (John Bokma) Date: 25 Apr 2005 19:33:54 GMT Subject: Python or PHP? References: <4ef0f3a4.0504242339.56b0506d@posting.google.com> Message-ID: Alan Little wrote: > Steve Holden wrote: > >>Your statement then becomes >> >>select * from foo where bar=1; drop table foo >> >>which is clearly not such a good idea. > > I'm sure Steve is very well aware of this and was just providing a > simple and obvious example, nevertheless it might be worth pointing > out that anyody who connects their web application to their database > as a user that has DROP TABLE privileges, would clearly be in need of > a lot more help on basic security concepts than just advice on > choosing a programming language. True. But how does it stop someone who uses inserts? (I exclude the case inserts are not needed). > This goes back to the point somebody made earlier on in the thread - > many web applications can be implemented as fairly simple wrappers > around properly designed databases. "Properly designed" includes > giving some thought to table ownership and privileges. One should stop SQL injection always, no matter if the database takes care of it or not. There is no excuse (like, yeah, but I set up the privileges right) for allowing SQL injection, ever. -- John MexIT: http://johnbokma.com/mexit/ personal page: http://johnbokma.com/ Experienced programmer available: http://castleamber.com/ Happy Customers: http://castleamber.com/testimonials.html From http Wed Apr 13 21:20:06 2005 From: http (Paul Rubin) Date: 13 Apr 2005 18:20:06 -0700 Subject: Compute pi to base 12 using Python? References: Message-ID: <7x3btui27t.fsf@ruckus.brouhaha.com> Dick Moores writes: > I need to figure out how to compute pi to base 12, to as many digits > as possible. I found this reference, > , but I really don't > understand it well enough. Could someone show me how to do what I need? Using the GNU "bc" utility: $ bc -l bc 1.06 Copyright 1991-1994, 1997, 1998, 2000 Free Software Foundation, Inc. This is free software with ABSOLUTELY NO WARRANTY. For details type `warranty'. scale = 3000 # number of output places wanted obase = 12 # output base print 4 * a(1) # pi = 4*arctan(1) 3.184809493B918664573A6211BB151551A05729290A7809A492742140A60A55256A\ 0661A03753A3AA54805646880181A3683083272BBBA0A370B12265529A828903B4B2\ 56B8403759A71626B8A54687621849B849A8225616B442796A31737B229B23914898\ 53943B8763725616447236B027A421AA17A38B52A18A838B01514A51144A23315A30\ 09A8906B61B8B48A62253A88A50A43BA0944572315933664476B3AABB77583975120\ 683526B75B462060BB03B432551913772729A2147553531793848A0402B999B50585\ 35374465A68806716644039539A8431935198527B9399B112990ABB0383B10764542\ 4577A51601B3624A88B7A676A3992912121A213887B92873946A61332242217AA735\ 4115357744939112602BA4B888818A3269222B528487747839994AB223B65B876269\ 5422822669BA00A586097842A51750362073B5A768363B21BB1A97A4A19444774939\ 9804922175A068A46739461990A2065BB0A30BBAB7024A585B1A84428195489784A0\ 7A331A7B0A1574565B373B05B03A5A80A13AB87857734679985558A5373178A7B282\ 71992A3894A5776085083B9B238B2220542462888641A2BAB8B3083AB49659172A31\ 2B78518654494A068662586A181835A64440B2970A12281397589881536720890580\ 1032881449223841428763329617531239B9A657405584014534390B587625606BB8\ 0923795944B43757A431B039556282978A6A49590553490BA1844947175637A90824\ 7B50127722464441380A852B0847B5813019BB70A67663B426565434069884476132\ 193344BA55A2128A03838974606B851B2979321A408067225A5AA4B3464A1A174735\ 95333909AB9127079655B3164B68B9B28A9B818A220A025AB0934203995B7A62A7AA\ 739355340539BA3182905B193905603A43B660B9426A92294697144A896A5B233935\ 8BB2B7294BB89635B071A6351211360B820B1882AB8433B54757B87A373284B1BA18\ 2A10326476B369A4A6365B58B8018994BB152556765475A704BB94B6B2A39458971A\ 8B90512786B5029404818644323552916170B3ABB7363496427B088B68725A685700\ 40617949289077B278069A09B559324B8A66828B40549B0296065B2300330592569A\ 7B76B92BA1293585B6A9B604567A0901362856373B4B56897946256B4172B1B50474\ 351364749A33996A81BA8847347A8411B850B79A03018291672AA0945656A159AA6A\ A0A845531A592005B8A34366B882257107B190969A846474836A9800750778920BA7\ 97297A2791101B0685A86BB704B9BAA17B055293679843B35215B0A8B1182B611953\ B080AA5431B219907A8448A81B1A9493245676B88013B47033524085959415862101\ 4216619553246570601967448B470174B9244892444817453865A4003B5AA7176451\ AAB90681A949786154AA040477382BA69371041710B8728458A23979252B25423675\ 3A44A1900AA283536A227648812525743868B410A567794663359A6726A528678332\ 8135114789B7645505B047848020A730A9557B206776AA56A19682744107901306B2\ 9008808619866B4911A05264B872A46B5376383932699531B449195640B62A636228\ 30886247A47B3957169861239358041AA281333622AA15912B0A636047A489BB0726\ 282A78B96671B27305A9652496B9B999011A7BA36898891665B1A6009058978850A2\ 1B01A158A1473B84A192B8672542A2A7056581995207A436A5B3BA2824637A3112AB\ B57176468206A071200A327B3216425148100786502AA21236ABB35499277670A126\ 9730583403B1922A483856007301983989159BB688A58B602339806B63002A339A50\ B0BA533B84827793913081070A32595A101803A9A20234691B1A0B623274B69B0B44\ 688195169461059543A252BB05208720BA13118266A872B26B9B584959B44B quit $ The arctan calculation takes about 20 sec on an Athlon of around 2 ghz. From removethis.kartic.krishnamurthy at gmail.com Mon Apr 25 19:00:05 2005 From: removethis.kartic.krishnamurthy at gmail.com (Kartic) Date: Mon, 25 Apr 2005 23:00:05 GMT Subject: web based file manager in python In-Reply-To: References: Message-ID: "The Great 'Ksenia Marasanova' uttered these words" on 4/25/2005 1:04 PM: > Hi, > > I didn't suceed in finding any kind of standard web based file > manager, written in Python. There are quite a lot for PHP (the nicest > Any hints? > > Thanks! Ksenia - I recently came across this python web-based FM: http://snakelets.sourceforge.net/filemgr/index.html It is by Irmen De Jong, the author of Snakelets. Thanks, -Kartic From skip at pobox.com Thu Apr 28 10:07:54 2005 From: skip at pobox.com (Skip Montanaro) Date: Thu, 28 Apr 2005 09:07:54 -0500 Subject: regex over files In-Reply-To: <427071cc.101435286@news.oz.net> References: <426D0659.7080307@chamonix.reportlab.co.uk> <426D08BC.1040703@klix.ch> <426E021E.8000809@jessikat.fsnet.co.uk> <17006.31984.182979.430076@montanaro.dyndns.org> <426E893D.2070905@chamonix.reportlab.co.uk> <426EAA9D.2050904@jessikat.fsnet.co.uk> <426F5B62.3010801@chamonix.reportlab.co.uk> <427071cc.101435286@news.oz.net> Message-ID: <17008.60986.932705.506233@montanaro.dyndns.org> Bengt> To be fairer, I think you'd want to hoist the re compilation out Bengt> of the loop. The re module compiles and caches regular expressions, so I doubt it would affect the runtime of either version. Bengt> But also to be fairer, maybe include the overhead of splitting Bengt> correctly, at least for the simple case regex in my example -- or Bengt> is a you-goofed post for me in the usenet forwarding queues Bengt> somewhere still? ;-) I was just too lazy to incorporate (something like) your change. You will note that I was also lazy enough to simply steal your XXXXX file. Skip From ods at strana.ru Thu Apr 21 11:03:47 2005 From: ods at strana.ru (Denis S. Otkidach) Date: Thu, 21 Apr 2005 19:03:47 +0400 Subject: deprecation of has_key? In-Reply-To: References: <1114069715.945176.73750@l41g2000cwc.googlegroups.com> <426775C8.3000303@holdenweb.com> Message-ID: <20050421190347.1d1f2ab4.ods@strana.ru> On Thu, 21 Apr 2005 08:50:25 -0600 Steven Bethard wrote: SB> Huh? I'm not following your logic. Why is "item in dict" less SB> readable than "dict.has_key(item)"? Something to do with expecting SB> inverses that don't exist? SB> SB> Personally, I use "item in dict" because it's quite readable to me, SB> and generally faster. For me dictionary is a collection of key-value pairs, but not a collection of keys (that's what set is). -- Denis S. Otkidach http://www.python.ru/ [ru] From ajw140NO at SPAMyork.ac.uk Mon Apr 18 17:40:27 2005 From: ajw140NO at SPAMyork.ac.uk (Andrew Wilkinson) Date: Mon, 18 Apr 2005 22:40:27 +0100 Subject: Wrapping C++ Class Heirachy in Python Message-ID: Hi, I'm trying to wrap a C++ class hierarchy with Python types and I'd like to maintain the hierarchy in the types. I'm fairly sure this is possible, isn't it? Are there any documents explaining how to do this, the standard Python manual doesn't go into enough detail about creating types for this. I've found the tp_base and tp_bases elements and I've set them to the base type object (and a tuple containing the base type object) before I call PyType_Ready but in Python the base class isn't recognised. Is there anything obvious I'm missing? Thanks in advance for any help, Andrew Wilkinson From rockon02 at senet.com.au Sat Apr 30 21:25:37 2005 From: rockon02 at senet.com.au (Mike brown) Date: Sun, 01 May 2005 11:25:37 +1000 Subject: Ron Grossi: God is not a man References: <1114098221.580669.86300@g14g2000cwa.googlegroups.com> <1114127633.859113.292290@l41g2000cwc.googlegroups.com> <#2tJ0r3RFHA.3664@TK2MSFTNGP15.phx.gbl> <1114328806.147822.64660@z14g2000cwz.googlegroups.com> <1114329202.229148.82550@o13g2000cwo.googlegroups.com> <1114654290.690332.155200@f14g2000cwb.googlegroups.com> <3dc8hjF6s5i2uU1@individual.net> <3desu2F6qoj7aU1@individual.net> <#ATbpqMTFHA.3980@TK2MSFTNGP12.phx.gbl> <1114831490.664193.236140@l41g2000cwc.googlegroups.com> Message-ID: Just go away from RMMGA From sjmachin at lexicon.net Wed Apr 6 21:26:32 2005 From: sjmachin at lexicon.net (John Machin) Date: Thu, 07 Apr 2005 11:26:32 +1000 Subject: sorting a list and counting interchanges References: <1112826641.728979.278530@f14g2000cwb.googlegroups.com> <1112835544.302702.294570@z14g2000cwz.googlegroups.com> Message-ID: On 6 Apr 2005 17:59:04 -0700, "Jordan Rastrick" wrote: >Unless I'm mistaken, this doesnt quite work, because it switches the >parity of phase every time a comparison is made, rather than every time >a swap is made. So: > ># >phase = 1 >def mycmp(x,y): > global phase > c = cmp(x,y) > if c > 0: # i.e. a swap will be performed in the sort That's rather a wild assumption. It's not part of the language definition that the first argument is at a lower index in the list than the second argument. Perhaps it's been coded as though: c = cmp(y, x); if c < 0: swap() In any case I doubt if the OP's Data Structures & Algorithms 101 tutor is interested in anything so practical as the implementation of Python's list.sort() method :-) > phase = -phase > return c From a.r.ferreira at gmail.com Tue Apr 19 15:07:44 2005 From: a.r.ferreira at gmail.com (Adriano Ferreira) Date: Tue, 19 Apr 2005 16:07:44 -0300 Subject: Why does python class have not private methods? Will this never changed? In-Reply-To: <311b5ce105041902165a0969a0@mail.gmail.com> References: <311b5ce105041902165a0969a0@mail.gmail.com> Message-ID: <73ddeb6c05041912072f335677@mail.gmail.com> >but why does it hava not private methods? Because it does not need them, ain't it? >Private stuff always makes programming much easier. Does it? Sometimes contortion is needed to get rid of declarations that restrain access, for example, when writing tests. I think the point-of-view of Python is very akin to many others in communities related to dynamic languages. Privacy is most convention. If sometimes you decide to look under the hood, you are not forbidden to, but you are on your own. Two quotes that make sense in this issue: (from "perlmodlib"): It [the programming language] would prefer that you stayed out of its living room because you weren't invited, not because it has a shotgun. (from Roberto Ierusalimschy, Lua's designer): If you don't want to do something, just don't. I think it is a cultural thing. Python has no "real" private methods and fields, because it did not grow worried about that. And that doesn't stop programmers from being productive. Regards, Adriano. From grante at visi.com Wed Apr 13 13:50:10 2005 From: grante at visi.com (Grant Edwards) Date: Wed, 13 Apr 2005 17:50:10 -0000 Subject: Compute pi to base 12 using Python? References: <1113390479.738210.49530@z14g2000cwz.googlegroups.com> <425d3b01$1@nntp0.pdx.net> <1113412899.536885.285890@g14g2000cwa.googlegroups.com> Message-ID: <115qmuin44mnie0@corp.supernews.com> On 2005-04-13, Dan Bishop wrote: > Pi has an interesting representation in bases between 0 and 1, > exclusive. There are a finite number of digits after the radix point, > but an infinite number _before_ it. You really oughtn't make me think so hard right after lunch. -- Grant Edwards grante Yow! I'd like some JUNK at FOOD... and then I want to visi.com be ALONE -- From steve at ferg.org Mon Apr 18 23:01:52 2005 From: steve at ferg.org (Steve) Date: 18 Apr 2005 20:01:52 -0700 Subject: Proposal: an unchanging URL for Python documentation Message-ID: <1113878396.500420.256230@g14g2000cwa.googlegroups.com> posted on: comp.lang.python emailed to: docs at python.org I have a suggestion/request that will, I think, improve the Python documentation. Currently, the Python documentation in HTML format is stored at URLs that change with each new release of Python. That is, for example, the documentation for the os module is at http://python.org/doc/2.3/lib/module-os.html for release 2.3 of Python, at http://python.org/doc/2.4/lib/module-os.html for release 2.4 and so on. I propose that an additional a URL be set up for the Python HTML documentation. This URL will always contain the current version of the documentation. Suppose we call it "current". Then (while 2.4 is still the current version) the documentation for the os module would also be available at http://python.org/doc/current/lib/module-os.html. There are three advantages to this proposal. (1) It is cheap and easy to do. (2) If a person regularly refers to the documentation for the os module, he can bookmark http://python.org/doc/current/lib/module-os.html and always be sure of getting the most current version. (3) This would give Pythonistas -- basically as a freebie -- annotatable documentation. You may be familiar with Wikalong ( http://www.wikalong.org/ ). Wikalong basically allows you to annotate any URL. If we had a "current" URL for Python documentation, people could add Wikalong notes to the current documentation without worrying that the annotations would not survive the release of the next version of Python. Being able to use Wikalong would provide the Python community with the opportunity to experiment with annotatable documents (not to mention, ride the leading edge of the Wikalong wave). And those who dislike annotated documentation can easily ignore it or turn it off the Wikalong sidebar (assuming that they have Wikalong installed in the first place). -- Steve Ferg From mefjr75 at hotmail.com Sat Apr 30 13:12:27 2005 From: mefjr75 at hotmail.com (M.E.Farmer) Date: 30 Apr 2005 10:12:27 -0700 Subject: Micro-PEP: str.translate(None) to mean identity translation In-Reply-To: <42732ed7.280902606@news.oz.net> References: <4272e00c.260731842@news.oz.net> <1114835238.762478.236940@o13g2000cwo.googlegroups.com> <42732ed7.280902606@news.oz.net> Message-ID: <1114881147.510389.129570@o13g2000cwo.googlegroups.com> After I re-read your post in daylight and read your followup the "Aha!" hit me .I am a little slow at times. I have always just iterated thru the badchars and replaced with "" . What you suggest would be very nice indeed! Thanks for the time and explanation, and you too Peter ! For what it is worth +1 ;) On another note why is maketrans in the string module.... I was a bit lost finding it the first time should it be builtin? transtable = "abcdefg".maketrans("qwertyu") Probably missing something. M.E.Farmer From fuzzyman at gmail.com Wed Apr 6 03:14:43 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 6 Apr 2005 00:14:43 -0700 Subject: Python Google Server In-Reply-To: References: <1112696434.623557.97000@g14g2000cwa.googlegroups.com> <1112706994.922193.5610@z14g2000cwz.googlegroups.com> <1112714083.674249.44370@g14g2000cwa.googlegroups.com> Message-ID: <1112771683.431054.82930@l41g2000cwc.googlegroups.com> vegetax wrote: > Fuzzyman wrote: > > > Of course - sorry. Thanks for the fix. Out of interest - why are you > > using this... just for curiosity, or is it helpful ? > > because is fun to surf on the google cache, =) Ha - cool ! The bizarre thing is, that for me it's actually useful. I doubt anyone else will be in the same situation though. Best Regards, Fuzzy http://www.voidspace.org.uk/python From eurleif at ecritters.biz Sat Apr 23 19:13:20 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Sat, 23 Apr 2005 23:13:20 GMT Subject: Python or PHP? In-Reply-To: References: Message-ID: John Bokma wrote: > my $sort = $cgi->param( "sort" ); > my $query = "SELECT * FROM table WHERE id=? ORDER BY $sort"; And the equivalent Python code: cursor.execute('SELECT * FROM table WHERE id=%%s ORDER BY %s' % sort, [some_id]) You're right, of course, about being *able* to write code with SQL injection vulnerabilities in Python. But it's not even close to being as easy as in PHP. From bokr at oz.net Fri Apr 1 17:21:33 2005 From: bokr at oz.net (Bengt Richter) Date: Fri, 01 Apr 2005 22:21:33 GMT Subject: Case-insensitive dict, non-destructive, fast, anyone? References: Message-ID: <424dc33c.55623752@news.oz.net> On Fri, 01 Apr 2005 18:52:00 GMT, "Raymond Hettinger" wrote: >[Ville Vainio] >> I need a dict (well, it would be optimal anyway) class that stores the >> keys as strings without coercing the case to upper or lower, but still >> provides fast lookup (i.e. uses hash table). > > >>>> class S(str): > def __hash__(self): > return hash(self.lower()) > def __eq__(self, other): > return self.lower() == other.lower() > > >>>> d = {} >>>> d[S('ThE')] = 'quick' >>>> d[S('the')] >'quick' >>>> d >{'ThE': 'quick'} > Building on your S to sneak in a generalized idea ;-) >>> class idict(dict): ... def __setitem__(self, key, value): ... dict.__setitem__(self, S(key), value) ... def __getitem__(self, key): ... return dict.__getitem__(self, S(key)) ... >>> d = idict() >>> d['ThE'] = 'quick' >>> d['the'] 'quick' >>> d {'ThE': 'quick'} Ok, the idea: I wonder if a dict with a general override hook for hashing all keys would be useful. E.g., a dict.__keyhash__ that would take key as arg and default as now returning key.__hash__() but that you could override. Seems like this could potentially be more efficient than key wrappers, and would also make it so you wouldn't have to chase all the affected methods in doing an idict like the above (e.g., get, setdefault, update etc. etc.) Regards, Bengt Richter From prabapython at yahoo.co.in Wed Apr 13 01:49:46 2005 From: prabapython at yahoo.co.in (praba kar) Date: Wed, 13 Apr 2005 06:49:46 +0100 (BST) Subject: Doubt regarding sorting of a list specific field In-Reply-To: 6667 Message-ID: <20050413054946.99185.qmail@web8409.mail.in.yahoo.com> Dear All, I have doubt regarding sorting. I have a list that list have another list (eg) list = [[1234,'name1'],[2234,'name2'],[0432,'name3']] I want to sort only numeric value having array field. How I need to do for that. with regards Prabahar ________________________________________________________________________ Yahoo! India Matrimony: Find your life partner online Go to: http://yahoo.shaadi.com/india-matrimony From kent37 at tds.net Tue Apr 26 06:03:46 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 26 Apr 2005 06:03:46 -0400 Subject: Do I need a nested lambda to do this? In-Reply-To: <1114472061.732832.283540@l41g2000cwc.googlegroups.com> References: <1114472061.732832.283540@l41g2000cwc.googlegroups.com> Message-ID: <426e0dac_2@newspeer2.tds.net> raoul wrote: > I can't figure this one out. Trying to be unnecessarily functional I > suspect. > > I have the following lists. > > vals = [1.000,2.344,4.2342] > tab = [((0,1),(0,3),(0,4)), > ((2,2),(3,0),(3,9)), > ((3,4),(6,3),(7,1))] > > I'm trying to create a one liner using map/reduce/lambda/zip(* etc to > do replace the first element of each pair in each row by the the values > in vals as follows: > > tab = [((1.000,1),(1.000,3),(1.000,4)), > ((2.344,2),(2.344,0),(2.344,9)), > ((4.2342,4),(4.2342,3),(4.2342,1))] I don't know about map/etc but it's pretty easy using list comp and gen exp: print [ tuple( (val, t[1]) for t in tt ) for val, tt in zip(vals, tab) ] Kent From radam2 at tampabay.rr.com Tue Apr 19 18:40:54 2005 From: radam2 at tampabay.rr.com (Ron) Date: Tue, 19 Apr 2005 22:40:54 GMT Subject: pre-PEP: Suite-Based Keywords - syntax proposal In-Reply-To: <1113800859.317109.27720@f14g2000cwb.googlegroups.com> References: <1113720183.913168.184770@f14g2000cwb.googlegroups.com> <42621c83.157344138@news.oz.net> <1113755254.226237.138550@z14g2000cwz.googlegroups.com> <1113800859.317109.27720@f14g2000cwb.googlegroups.com> Message-ID: Kay Schluehr wrote: > Steven Bethard wrote: > > >>So the object of a "where" is then always an ordered dict? > > > Yes. > > >>If so, then >>I guess I like this proposal best so far. >> >>However, it does seem to have the problem that you can't have any >>additional local variables so, for example, list comprehensions are >>probably not usable... >> >>Or can you still drop the argument to "where" and just use the names >>directly? E.g.: >> >>x = property(fget=fget, doc=doc) where: >> doc = "I'm the 'x' property." >> def fget(self): >> return self.__x > > > I can't see why this shouldn't work? > > The specifiers behind "where" are present to determine the matching > behaviour. The order of a dict is caused by different specifiers i.e. a > dict- or tuple-like specifier. If a specifier is not present only names > can be matched regardless of a sequence and this is always possible > because we still have a dict with names as keys. > > What should not be possible are statements like this: > > x = property(a, b) where: > doc = "I'm the 'x' property." > def fget(self): > return self.__x > > because there is no rule to match doc and fget onto a and b. In this > case we would need specifiers: > > x = property(a, b) > where **a: > doc = "I'm the 'x' property." > where **b: > def fget(self): > return self.__x > > Ciao, > Kay Just throwing in another slight variation to Kay's example here. How about using ***name in the same way as *name, and **name are used? It extends the current argument options in a consistent manner and 'I believe' is easy to explain and visually says something different is happening here. This builds on the already present arg, *arg, **arg, and so why not a ***arg to represent the 4th alternative, a suite? You would also need to use it in the def statement as well, and probably would want to anyway if your argument suite is that long. def property(***a, ***b): a: doc = "I'm the default 'x' property." b: def foo(arg): return arg return arg x = property(***a, ***b) a: doc = "I'm the 'x' property." b: def fget(self): return self.__x With the ***name syntax, making it's obvious it's different (a good thing), and you might be able to drop the 'with' or 'where'. The (***name) == (name: suite) relationship may be useful in other places as well. I'm not sure on the returns for the def above, just trying to make it more complete. I presuming foo would be the default if 'b' isn't given in the function call. I suppose the ***b, and b: suite, in the function call can be optional. Same for the ***a and a: suite. By having them named, either one could be absent and the order could be swapped in the call if it makes it more readable. Cheers, Ron_Adam From pballard at ozemail.com.au Mon Apr 4 04:39:48 2005 From: pballard at ozemail.com.au (Peter Ballard) Date: 4 Apr 2005 01:39:48 -0700 Subject: DIY Spam Filter in Python Message-ID: <9d5509fa.0504040039.526c93b6@posting.google.com> Hi all, I've no idea if this will be of any use to anyone. But since I've gone to the effort of writing it, I might as well make it publicly available... Until last year, spam filtering was a source of frustration for me. Freeware packages I tried (specifically, spamassassin and dspam) were difficult to use. Custom rules using procmail were a pain. Then I noticed that python came with email parsing capabilities in the email module. So I thought that maybe custom rules in python would be easier than (a) custom rules in procmail, or (b) deciphering the documentation of a package. And a lot more fun. It turned out to be very easy. I got the filter up in a few evenings, and I've been using it successfully, and slowly enhancing it, over a number of months. In short: a success story for "using the batteries" - at least in my opinion. Source code, and a bit of documentation, is at: http://members.ozemail.com.au/~pballard/diyspamfilter.html -- Regards, Peter Ballard Adelaide, AUSTRALIA http://members.ozemail.com.au/~pballard/ From nsgraham at ece.ualberta.ca Thu Apr 14 00:47:56 2005 From: nsgraham at ece.ualberta.ca (Nicholas Graham) Date: Wed, 13 Apr 2005 22:47:56 -0600 Subject: String manipulation Message-ID: I'm writing a program that requires some string manipulations. Let's say I have a string s='x' Now, the ascii code for 'x' is 0x78. I want to be able to perform operations on this number, and print the character corresponding to the results of the operation. For example, the pseudo-code looks like: -read in string s from external file (for simplicity, we'll keep s='x') -determine the code for s (should be 0x78 or 120 in base 10), store it in variable c -add a literal to c (let's say c=c+1) -find out which character corresponds to the new code c=0x79 -store the character in a new string s2 At the end of this, I want s2='y' Any suggestions? NG From ritterhaus at yahoo.com Wed Apr 6 15:27:29 2005 From: ritterhaus at yahoo.com (ritterhaus at yahoo.com) Date: 6 Apr 2005 12:27:29 -0700 Subject: Python sleep doesn't work right in a loop? In-Reply-To: <1112815288.465004.74840@z14g2000cwz.googlegroups.com> References: <1112814877.560518.229530@z14g2000cwz.googlegroups.com> <1112815288.465004.74840@z14g2000cwz.googlegroups.com> Message-ID: <1112815649.741176.233850@l41g2000cwc.googlegroups.com> This is running in the interactive 'PyShell', but in truth those print statements are part of a gui app that flashes a control in wx.widgets by toggling it's background color. The same behavior either way. From bokr at oz.net Sat Apr 16 03:14:50 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 16 Apr 2005 07:14:50 GMT Subject: pre-PEP: Suite-Based Keywords References: Message-ID: <4260b4e3.65280488@news.oz.net> On Fri, 15 Apr 2005 19:32:02 -0700, James Stroud wrote: >I_vote_yes(James): > I_understand_what_it_does = True > Makes_code_formatting_way_more_managable_in_tough_cases = True > Makes_code_way_more_readable = True > To_cool = True > >On Friday 15 April 2005 04:45 pm, Brian Sabbey wrote: >> Here is a pre-PEP for what I call "suite-based keyword arguments". The >> mechanism described here is intended to act as a complement to thunks. >> Please let me know what you think. >> Kind of cool. If we had full lambdas aka as anonymous defs (def foo(...) with foo left out ;-) would this be concise sugar for the equivalents shown below your examples? (The rule for parsing the suite of an anonymous def is that the left column of the first non-space character of the first suite statement following the def(): becomes the suite indent reference, and a dedent to the left of that ends the def(): or a closing bracket not opened in the def(): suite also ends it. Otherwise it is standard suite indentation) >> Suite-Based Keyword Arguments >> ----------------------------- >> >> Passing complicated arguments to functions is currently awkward in Python. >> For example, the typical way to define a class property winds up polluting >> the class's namespace with the property's get/set methods. By allowing >> keyword arguments to be defined in a suite following a function call, >> complicated arguments can be passed in a cleaner, easier way. >> >> Examples >> ======== >> >> Using suite-based keyword arguments, the code >> >> f(x = 1) >> >> is equivalent to >> >> f(): >> x = 1 f(**def(): x = 1 return vars()) >> >> In general, a suite following a function call creates a new scope. The >> bindings created in this scope get passed to the function as keyword >> arguments. >> >> Suite-based keyword arguments can be mixed with regular arguments: >> >> f(1, 2, y = 4): >> x = 1 f(1, 2, y = 4, **def(): x =1 return vars()) >> >> Motivation >> ========== >> >> One motivation for suite-based keywords is to allow cleaner definitions of >> properties. Currently, properties are typically define as in this >> example: >> >> class C(object): >> def getx(self): >> return self.__x >> def setx(self, value): >> self.__x = value >> def delx(self): >> del self.__x >> x = property(getx, setx, delx, "I'm the 'x' property.") >> >> The 'getx', 'setx', and 'delx' methods get defined in the namespace of the >> class even though one wants only to pass them to 'property'. Ideally, one >> would want these methods to be defined in their own namespace. Also, it >> would be helpful when reading the code if the layout of the code gave >> visual indication that their only purpose is to be used in a property. >> >> Using suite-based keyword arguments, and without any changes to the >> 'property' type, this code can be written as: >> >> class C(object): >> x = property(): >> doc = "I'm the 'x' property." >> def fget(self): >> return self.__x >> def fset(self, value): >> self.__x = value >> def fdel(self): >> del self.__x clas C(object): x = property( **def(): doc = "I'm the 'x' property." def fget(self): return self.__x def fset(self, value): self.__x = value def fdel(self): del self.__x return vars()) >> >> Here, 'fget', 'fset' and 'fdel' do not wind up as methods of the class, >> and it is visually clear that they are methods only for the 'x' property. >> Also, this code is less bug-prone since the name of each method need >> appear only once. >> >> Passing callbacks in other situations is made similarly easier and >> cleaner: >> >> setHandlers(): >> def success(): >> print 'success' >> def failure(): >> print 'an error has occured' >> def apocalypse(): >> print 'a serious error has occured' setHandlers(**def(): def success(): print 'success' def failure(): print 'an error has occured' def apocalypse(): print 'a serious error has occured' return vars()) >> >> a = [1,3,2] >> a.sort(): >> def cmpfunc(x,y): >> return cmp(x,y) a.sort(**def(): def cmpfunc(x,y) return vars()) >> >> Situations that do not require callbacks can also be better organized >> using suite-based keywords. For example, here is code as it would >> currently be written in Python: >> >> if a: >> x = 1 >> else: >> x = 2 >> f(x=x) >> >> When reading this code, one reaches the 'if' statment without knowing what >> its purpose is-- layout of the code does not indicate that the 'if' >> statement is calculating an argument to 'f'. Also, it requires a binding >> that serves no purpose other than to hold an argument to 'f', yet this >> binding persists for the rest of the surrounding function. >> >> Here is the same code using suite-based keyword arguments >> >> f(): >> if a: >> x = 1 >> else: >> x = 2 >> f(**def(): if a: x = 1 else: x = 2 return vars()) >> When reading this code, it is easy to skip over everything that is >> involved in calling 'f', if one so desires. Since the suite has its own >> namespace, one does not have to worry that the suite creates some bindings >> that will be important later in the function. > Obviously leaving out the "**def(" and the "return vars())" makes it cleaner ;-) Regards, Bengt Richter From bokr at oz.net Sat Apr 16 22:24:12 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 17 Apr 2005 02:24:12 GMT Subject: pre-PEP: Suite-Based Keywords References: <42607b0f$1_2@newspeer2.tds.net> Message-ID: <4261c067.133764643@news.oz.net> On Sat, 16 Apr 2005 13:58:38 -0700, Brian Sabbey wrote: [...] > >Yes, my description of the syntax was ambiguous. To clarify, I intended >the syntax to be backwardly compatible. That is, one would not be able to >use a suite to define keywords if there already exists a suite for other >reasons. So, one would not be able to use a suite to pass keywords to 'f' >in this situation: > >if f(): > x = 1 > >This code should behave exactly as it does now. > >I agree that the ellipsis idea probably makes the code more readable, and >it may be a good idea to have them for that reason. However, ellipses are >not necessary as a way to disambiguate the syntax; all statements >containing suites currently begin with a keyword, and keyword suites would >not. > Using my expression where: trailer, the above if could be spelled if f(x) where: x=1: # where: acts like '' other than its semantics. do_something() I was debating whether to use a where: that applied to a whole previous statement and its suite, indenting as if the where were a following statment, e.g., if f(x): do_something() where: x = 1 But I thought that could get too far away, and not cover many use cases that could be done other ways. The thing that where does though is create a transient namespace for the suite bindings, so they don't clobber the calling namespace the way just prefixing a setup would x = 1 # clobber x if f(x): do_something() Shoot, I just has another idea about the :: expression -- instead of returning a tuple, it could return an order-maintaining subtype of dict with methods for items(), keys() and values() and that would make better spellings for many examples in Kay's post ;-/ Also suite-based keyword calling would just become f(10, 4, **:: # note ease of including other parameters if part of the signature x = 1 y = 2 ) and you could do print (:: x = 1 y = 2 ).keys() => ['x', 'y'] or call foo foo(self, whatever, *(:: x = 1 y = 2).values()) Oh well, that's the way ideas evolve ;-) Regards, Bengt Richter From andrew at nospam.com Sun Apr 17 11:46:53 2005 From: andrew at nospam.com (Andrew E) Date: Sun, 17 Apr 2005 17:46:53 +0200 Subject: sscanf needed In-Reply-To: References: Message-ID: Uwe Mayer wrote: > Hi, > > I've got a ISO 8601 formatted date-time string which I need to read into a > datetime object. > Is there a shorter way than using regular expressions? Is there a sscanf > function as in C? in addition to the other comments... I like re, because it gives me the most control. See below. import re import datetime class Converter: def __init__( self ): self.isoPattern = re.compile( "(\d\d\d\d)-(\d\d)-(\d\d)[tT ](\d\d):(\d\d):(\d\d)" ) def iso2date( self, isoDateString ): match = self.isoPattern.match( isoDateString ) if not match: raise ValueError( "Not in ISO format: '%s'" % isoDateString ) return datetime.datetime( int(match.group(1)), int(match.group(2)), int(match.group(3)), int(match.group(4)), int(match.group(5)), int(match.group(6)) ) c = Converter() def demo( iso ): try: date = c.iso2date( iso ) print "Input '%s' -> datetime: %s" % ( iso, date ) except ValueError, e: print str(e) demo( "2005-04-21T12:34:56" ) demo( "2005-04-21 12:34:57" ) demo( "2005-04-2 12:34:57" ) From aahz at pythoncraft.com Sat Apr 9 19:33:32 2005 From: aahz at pythoncraft.com (Aahz) Date: 9 Apr 2005 16:33:32 -0700 Subject: Best editor? References: <1112725379.514651.66540@l41g2000cwc.googlegroups.com> <86k6nbww6z.fsf@guru.mired.org> Message-ID: In article <86k6nbww6z.fsf at guru.mired.org>, Mike Meyer wrote: >aahz at pythoncraft.com (Aahz) writes: >> >> Use vim. 80% of the power of emacs at 20% of the learning curve. > >Hmm. Can I read mail/news/web pages in vim? I can in emacs. Yup, that's why emacs stands for Eighty Megabytes And Constantly Swapping. ;-) >Emacs is a computing environment. I read mail and news in it, so I >don't have to worry about learning some applications custom editor >(ok, a good MUA/newsreader will invoke my favorite editor - but that's >Emacs, so why bother). I use emacs for the heavy lifting. Doesn't work so well when you want to use an application that isn't emacs, yet still invoke a custom editor. But yeah, if you consider emacs a Way of Life, then you're making sense. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "The joy of coding Python should be in seeing short, concise, readable classes that express a lot of action in a small amount of clear code -- not in reams of trivial code that bores the reader to death." --GvR From postmaster at castleamber.com Wed Apr 20 16:19:57 2005 From: postmaster at castleamber.com (John Bokma) Date: 20 Apr 2005 20:19:57 GMT Subject: goto statement References: <20050420092359.81900.qmail@web8409.mail.in.yahoo.com> <426645bb$0$3129$8fcfb975@news.wanadoo.fr> Message-ID: Do Re Mi chel La Si Do wrote: > +1 I am modded up :-D -- John MexIT: http://johnbokma.com/mexit/ personal page: http://johnbokma.com/ Experienced programmer available: http://castleamber.com/ Happy Customers: http://castleamber.com/testimonials.html From WLigtenberg at gmail.com Thu Apr 21 09:17:48 2005 From: WLigtenberg at gmail.com (Willem Ligtenberg) Date: Thu, 21 Apr 2005 15:17:48 +0200 Subject: XML parsing per record References: <426640b6$1_1@newspeer2.tds.net> Message-ID: Sorry I just decided that I want to use your solution, but I am wondering is cElemenTree in expat or is that something different? On Wed, 20 Apr 2005 08:03:00 -0400, Kent Johnson wrote: > Willem Ligtenberg wrote: >>>Willem Ligtenberg wrote: >>> >>>>I want to parse a very large (2.4 gig) XML file (bioinformatics >>>>ofcourse :)) But I have no clue how to do that. Most things I see read >>>>the entire xml file at once. That isn't going to work here ofcourse. >>>> >>>>So I would like to parse a XML file one record at a time and then be >>>>able to store the information in another object. How should I do >>>>that? >> >> The XML file I need to parse contains information about genes. >> So the first element is a gene and then there are a lot sub-elements with >> sub-elements. I only need some of the informtion and want to store it in >> my an object called gene. Lateron this information will be printed into a >> file, which in it's turn will be fed into some other program. >> This is an example of the XML >> >> >> >> >> >> >> > > This should get you started with cElementTree: > > import cElementTree as ElementTree > > source = 'Entrezgene.xml' > > for event, elem in ElementTree.iterparse(source): > if elem.tag == 'Entrezgene': > # Process the Entrezgene element > geneid = elem.findtext('Entrezgene_track-info/Gene-track/Gene-track_geneid') > print 'Gene id', geneid > > # Throw away the element, we're done with it > elem.clear() > > Kent From vedanta.barooah at gmail.com Fri Apr 22 15:47:58 2005 From: vedanta.barooah at gmail.com (Vedanta Barooah) Date: Sat, 23 Apr 2005 01:17:58 +0530 Subject: rpm-python help!! Message-ID: Hello All, Has anyone worked with rpm-python, i am kinda stuck in the addErase() function, Any help will be appreciated! Thanks, Vedanta Here is the code: #!/bin/env python import os,rpm,md5,sys class rpm_cb: def __init__(self): self.fdno={} def callbackInstall(self, what, amount, total, mydata, wibble): if what == rpm.RPMCALLBACK_TRANS_START: pass elif what == rpm.RPMCALLBACK_INST_OPEN_FILE: hdr, path = mydata print "Installing %s\r" % (hdr["name"]) fdno = os.open(path, os.O_RDONLY) nvr = '%s-%s-%s' % ( hdr['name'], hdr['version'], hdr['release'] ) self.fdno[nvr] = fdno return fdno elif what == rpm.RPMCALLBACK_INST_CLOSE_FILE: hdr, path = mydata nvr = '%s-%s-%s' % ( hdr['name'], hdr['version'], hdr['release'] ) os.close(self.fdno[nvr]) elif what == rpm.RPMCALLBACK_INST_PROGRESS: hdr, path = mydata print "%s: %.5s%% done\r" % (hdr["name"], (float(amount) / total) * 100) def callbackRemove(self, what, amount, total, mydata, wibble): if what == rpm.RPMCALLBACK_TRANS_START: pass #elif what == rpm.RPMCALLBACK_INST_OPEN_FILE: # hdr, path = mydata # print "Installing %s\r" % (hdr["name"]) # fdno = os.open(path, os.O_RDONLY) # nvr = '%s-%s-%s' % ( hdr['name'], hdr['version'], hdr['release'] ) # self.fdno[nvr] = fdno # return fdno #elif what == rpm.RPMCALLBACK_INST_CLOSE_FILE: # hdr, path = mydata # nvr = '%s-%s-%s' % ( hdr['name'], hdr['version'], hdr['release'] ) # os.close(self.fdno[nvr]) elif what == rpm.RPMCALLBACK_UNINST_START: elif what == rpm.RPMCALLBACK_INST_PROGRESS: hdr, path = mydata print "%s: %.5s%% done\r" % (hdr["name"], (float(amount) / total) * 100) class myrpm: def queryInstalledPackage(self,rpmname): ts = rpm.ts() mi = ts.dbMatch("name",rpmname) for hdr in mi: print "%s-%s-%s" % (hdr['name'],hdr['version'],hdr['release']) def queryInstalledPackages(self,pattern): ts = rpm.ts() mi = ts.dbMatch() mi.pattern("name",rpm.RPMMIRE_GLOB,pattern) for hdr in mi: print "%s-%s-%s" % (hdr['name'],hdr['version'],hdr['release']) def queryPackage(self,rpmlocation): ts = rpm.ts() fdno=os.open(rpmlocation,os.O_RDONLY) try: hdr = ts.hdrFromFdno(fdno) except: fdno=os.open(rpmlocation,os.O_RDONLY) ts.setVSFlags(rpm._RPMVSF_NOSIGNATURES) hdr = ts.hdrFromFdno(fdno) os.close(fdno) print "%s-%s-%s : %s" % (hdr['name'],hdr['version'],hdr['release'],hdr['description']) def install(self,rpmlocation): ts = rpm.ts() fdno=os.open(rpmlocation,os.O_RDONLY) try: hdr = ts.hdrFromFdno(fdno) except: fdno=os.open(rpmlocation,os.O_RDONLY) ts.setVSFlags(rpm._RPMVSF_NOSIGNATURES) hdr = ts.hdrFromFdno(fdno) os.close(fdno) ts.addInstall(hdr,(hdr,rpmlocation),"u") cb=rpm_cb() ts.run(cb.callbackInstall,'') def remove(self,rpmname): ts = rpm.ts() mi = ts.dbMatch(rpm.RPMTAG_NAME,rpmname) mi.pattern(rpm.RPMTAG_ARCH,rpm.RPMMIRE_DEFAULT,"i386") for idx in mi: instance = mi.instance() #ts.addErase(instance) print type(instance); if __name__=="__main__": x=myrpm() # query a particular installed package #x.queryInstalledPackage(sys.argv[1]) # query many installed packages using regex #x.queryInstalledPackages(sys.argv[1]) # query a package that exists in rpmlocation, but is not installed #x.queryPackage(sys.argv[1]) # install a package #x.install(sys.argv[1]) # uninstall a package x.remove(sys.argv[1]) -- *~:~*~:~*~:~*~:~*~:~*~:~*~:~*~:~*~:~*~:~* Vedanta Barooah YM! - vedanta2006 Skype - vedanta2006 -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin.witte at gmail.com Sat Apr 30 08:26:52 2005 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 30 Apr 2005 05:26:52 -0700 Subject: Writing to log file when script is killed In-Reply-To: <1114851873.072376.225820@z14g2000cwz.googlegroups.com> References: <1114851873.072376.225820@z14g2000cwz.googlegroups.com> Message-ID: <1114864012.637007.295800@z14g2000cwz.googlegroups.com> If you run on unix you can use the signal module to intercept a kill - see http://docs.python.org/lib/node368.html for a quick example From jorgen.cederberg at gmail.com Tue Apr 19 10:22:37 2005 From: jorgen.cederberg at gmail.com (=?ISO-8859-1?Q?J=F8rgen_Cederberg?=) Date: Tue, 19 Apr 2005 16:22:37 +0200 Subject: Update Label when Scale value changes In-Reply-To: <1113919325.498539.323190@o13g2000cwo.googlegroups.com> References: <1113916746.841747.274550@l41g2000cwc.googlegroups.com> <9Z79e.969$cL6.77@news.get2net.dk> <1113919325.498539.323190@o13g2000cwo.googlegroups.com> Message-ID: codecraig wrote: > Yea that is what i needed. Can you recommend a good Tkinter site (or > book, but preferably site) about learning Tkinter. > > I've tried: > http://www.python.org/moin/TkInter > http://www.pythonware.com/library/tkinter/introduction/ > > But I am looking for more about events, etc. > > Thanks > Hi the above links are good. Also check out http://infohost.nmt.edu/tcc/help/pubs/tkinter/ which has a lot of information on events. /Jorgen Cederberg From zanesdad at bellsouth.net Thu Apr 14 18:47:57 2005 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Thu, 14 Apr 2005 18:47:57 -0400 Subject: SimpleXMLRPCServer - disable output In-Reply-To: <1113517877.473126.259590@o13g2000cwo.googlegroups.com> References: <1113509250.602995.25500@o13g2000cwo.googlegroups.com> <1113517877.473126.259590@o13g2000cwo.googlegroups.com> Message-ID: <425EF31D.5060806@bellsouth.net> codecraig wrote: >Jeremy Jones wrote: > > >>codecraig wrote: >> >> >> >>>Hi, >>> I thought I posted this, but its been about 10min and hasnt shown >>> >>> >up > > >>>on the group. >>> Basically I created a SimpleXMLRPCServer and when one of its >>> >>> >methods > > >>>gets called and it returns a response to the client, the server >>> >>> >prints > > >>>some info out to the console, such as, >>> >>>localhost - - [14/Apr/2005 16:06:28] "POST /RPC2 HTTP/1.0" 200 - >>> >>>Anyhow, is there a way I can surpress that so its not printed to the >>>console? I looked at SimpleXMLRPCServer.py ...it doesn't explicitly >>>print that, I think perhaps std is...but not sure. Any ideas?? >>> >>>thanks. >>> >>> >>> >>> >>> >>Here's the entire SimpleMLRPCServer class from SimpleXMLRPCServer.py: >> >> >>class SimpleXMLRPCServer(SocketServer.TCPServer, >> SimpleXMLRPCDispatcher): >> """Simple XML-RPC server. >> >> Simple XML-RPC server that allows functions and a single instance >> to be installed to handle requests. The default implementation >> attempts to dispatch XML-RPC calls to the functions or instance >> installed in the server. Override the _dispatch method inhereted >> from SimpleXMLRPCDispatcher to change this behavior. >> """ >> >> def __init__(self, addr, >> >> >requestHandler=SimpleXMLRPCRequestHandler, > > >> logRequests=1): >> self.logRequests = logRequests >> >> SimpleXMLRPCDispatcher.__init__(self) >> SocketServer.TCPServer.__init__(self, addr, requestHandler) >> >>You should be able to change logRequests to 0 and that should fix it. >> >> > I just tested it at a prompt and it worked just fine. > > >>Jeremy Jones >> >> > >Jeremy, > So can you explain what I can do to set logRequests = 0? Do i just >do.. > >server = SimpleXMLRPCServer(0) ??? > >I am sorta new to python thanks. > > > You've got a couple of options. You can either set it in the constructor (server = SimpleXMLRPCServer(addr, requestHandler=somehandler, logRequests=0)) or you can set it after you have an instance of it (<>; foo.logRequests = 0). HTH, Jeremy Jones -------------- next part -------------- An HTML attachment was scrubbed... URL: From farcepest at gmail.com Thu Apr 14 18:46:16 2005 From: farcepest at gmail.com (Andy Dustman) Date: 14 Apr 2005 15:46:16 -0700 Subject: database in python ? References: <1113197530.990898.46130@z14g2000cwz.googlegroups.com> <1113216765.784331.156820@f14g2000cwb.googlegroups.com> <1113231173.277597.226710@g14g2000cwa.googlegroups.com> Message-ID: <1113518776.127481.10550@l41g2000cwc.googlegroups.com> Mage wrote: > Andy Dustman wrote: > > > > >Transactions available since 3.23.17 (June 2000) > > > > > Transactions only supported on slow database types like innodb. > > If you ever tried it you cannot say that mysql supports transactions. No. > Last time when I tried mysql 4.x did explicit commit if you simply > disconnected inside a transaction block. It was a year ago, but I will > never forget it. You know that the default server setting has autocommit on, right? > >>foreign keys, > >> > >> > > > >Foreign keys available since 3.23.44 (Oct 2001) > > > > > They are syntactically accepted but not forced. http://dev.mysql.com/doc/mysql/en/innodb-foreign-key-constraints.html http://dev.mysql.com/doc/mysql/en/error-handling.html # Error: 1215 SQLSTATE: HY000 (ER_CANNOT_ADD_FOREIGN) Message: Cannot add foreign key constraint # Error: 1216 SQLSTATE: 23000 (ER_NO_REFERENCED_ROW) Message: Cannot add or update a child row: a foreign key constraint fails # Error: 1217 SQLSTATE: 23000 (ER_ROW_IS_REFERENCED) Message: Cannot delete or update a parent row: a foreign key constraint fails Foreign keys work. Prior to 3.23, it was just syntactical support. But that was 5 years ago. > I have seen real benchmarks. MySQL 5 is slower than postgresql and it's > also slower than firebird if you do some real work. So use the database that works best for your application. MySQL is not a panacea, but there are a lot of applications it works well for. From codecraig at gmail.com Fri Apr 15 18:17:44 2005 From: codecraig at gmail.com (codecraig) Date: 15 Apr 2005 15:17:44 -0700 Subject: py2exe - create one EXE In-Reply-To: References: <1113579012.150708.118990@o13g2000cwo.googlegroups.com> Message-ID: <1113603464.174120.121970@f14g2000cwb.googlegroups.com> fredrik... any ideas on my last post? (copied below for u) oh and Fredrik, i tried the SingleInstaller link....which points to a script using NSIS. I followed those instructions which generated an .exe. HOwever, when i run the .exe nothing happens (meaning no process starts, no output, no errors, nothing). any ideas on that? have ever used it? thanks From antonyliu2002 at yahoo.com Tue Apr 19 22:52:17 2005 From: antonyliu2002 at yahoo.com (Anthony Liu) Date: Tue, 19 Apr 2005 19:52:17 -0700 (PDT) Subject: Importing some functions from a py file In-Reply-To: 6667 Message-ID: <20050420025217.46333.qmail@web54501.mail.yahoo.com> --- Michael Soulier wrote: > On 4/19/05, Anthony Liu > wrote: > > But every time, I run code2.py, the main() of > code1.py > > is run. > > You probably did not protect your main function in > both modules. > > ie. > > if __name__ == '__main__': main() > You are certainly right, because I don't know how to protect the main functions. Where do I put if __name__ == '__main__': main() ? __________________________________ Do you Yahoo!? Yahoo! Mail - Find what you need with new enhanced search. http://info.mail.yahoo.com/mail_250 From cam.ac.uk at mh391.invalid Sun Apr 17 03:45:12 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sun, 17 Apr 2005 08:45:12 +0100 Subject: ANN: Python 2.3.2 for PalmOS available In-Reply-To: <1113608405.558884.235890@f14g2000cwb.googlegroups.com> References: <1113608405.558884.235890@f14g2000cwb.googlegroups.com> Message-ID: lucio.torre at gmail.com wrote: > Some months ago i did a port of the Python2.3.2 interpreter to PalmOS. > I didnt port any C module or created modules for PalmOS API's. Just port ctypes. Then we'll be good to go. Seriously, this looks like a cool beginning. -- Michael Hoffman From hongqn at gmail.com Sat Apr 30 23:00:57 2005 From: hongqn at gmail.com (Qiangning Hong) Date: 30 Apr 2005 20:00:57 -0700 Subject: compare two voices Message-ID: <1114916457.795332.45220@f14g2000cwb.googlegroups.com> I want to make an app to help students study foreign language. I want the following function in it: The student reads a piece of text to the microphone. The software records it and compares it to the wave-file pre-recorded by the teacher, and gives out a score to indicate the similarity between them. This function will help the students pronounce properly, I think. Is there an existing library (C or Python) to do this? Or if someone can guide me to a ready-to-implement algorithm? From g.brandl at gmx.net Mon Apr 4 12:53:47 2005 From: g.brandl at gmx.net (Georg Brandl) Date: Mon, 04 Apr 2005 18:53:47 +0200 Subject: "specialdict" module In-Reply-To: <3bd9jgF6heia2U1@individual.net> References: <3bamhhF6j009lU1@individual.net> <3bb433F6fn6t3U1@individual.net> <1112631551.683072.80970@f14g2000cwb.googlegroups.com> <3bd9jgF6heia2U1@individual.net> Message-ID: <3bd9nnF6heia2U2@individual.net> Georg Brandl wrote: > Michele Simionato wrote: >> About not using super: you might have problems in multiple inheritance. >> Suppose I want to use both your defaultdict and a thirdpartdict. A >> subclass >> >> class mydict(defaultdict, thirdpartdict): >> pass >> >> would not work if thirdpartdict requires a non-trivial __init__ , since >> without super in defaultdict.__init__ you would just call dict.__init__ >> and not thirdpartdict. > > Right. I thought about a combined defaultdict/keytransformdict, > which seems to be easy to create with the current implementation: > > class defaultkeytransformdict(defaultdict, keytransformdict): > pass > > At least I hope so. This is another argument against the initializing > of defaultfactory or keytransformer in __init__. > > mfg > Georg > > Here comes the current module (keytransformdict should be working now > for all dict methods): > > # specialdict - subclasses of dict for common tasks > # > > class NoDefaultGiven(Exception): > pass > > class defaultdict(dict): > __slots__ = ['_default'] > > def __init__(self, *args, **kwargs): > self._defaulttype = 0 ^^^^^^^^^^^^^^^^^^^^^ This must read "self.cleardefault()", of course. mfg Georg From tjreedy at udel.edu Wed Apr 27 12:23:22 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 27 Apr 2005 12:23:22 -0400 Subject: bytecode non-backcompatibility References: <1114418065.581779.52480@l41g2000cwc.googlegroups.com> <426F2C3A.80402@v.loewis.de> Message-ID: "Maurice LING" wrote in message news:d4nrhu$rl3$1 at domitilla.aioe.org... > So my alternative solution is that PyPI have a mechanism to maintain what > had been installed in the site-package directory and to download the > libraries and install into the new site-package directory... > What do you think? I doubt anyone disputes that upgrades are more hassle than we would like. My main point was that freezing CPython's technology is not the solution. Any other upgrade helper that you can contribute will be welcome. Terry J. Reedy From mefjr75 at hotmail.com Sat Apr 30 12:31:38 2005 From: mefjr75 at hotmail.com (M.E.Farmer) Date: 30 Apr 2005 09:31:38 -0700 Subject: interactive web graphics In-Reply-To: References: Message-ID: <1114878698.151389.73560@l41g2000cwc.googlegroups.com> Blender has nothing to do with Mozilla. It is a 3d creation suite it contains more things than you would believe ;) Blender is deep and wide, so it can be daunting to use at first but once you have basic 3d concepts under you belt it is playtime. Blender is the first software package to be bought from a private company by a community to be put into opensource. Really cool stuff has been happening ever since they went opensource. The game engine has taken the longest to put back together, it was removed because of licensing issues. So the old game plugin might not be up to date but it will eventually be revamped when the 'new' game engine is stable. Until then you might be able to use the old one but I have had many problems getting it to work reliably on Firefox or Mozilla, it works well with I.E. but ........ Have fun and experiment. M.E.Farmer From jerf at jerf.org Tue Apr 26 23:53:13 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Tue, 26 Apr 2005 23:53:13 -0400 Subject: delete will assure file is deleted? References: <1114510350.912358.21990@f14g2000cwb.googlegroups.com> <8664y9n8hy.fsf@guru.mired.org> <1114512016.930540.164920@g14g2000cwa.googlegroups.com> <86r7gxkldl.fsf@guru.mired.org> Message-ID: On Tue, 26 Apr 2005 21:24:06 -0500, Mike Meyer wrote: > Jeremy Bowers writes: > >> On Tue, 26 Apr 2005 03:40:16 -0700, ajikoe at gmail.com wrote: >> os.remove, as the module name implies, tells the OS to do something. I >> would consider an OS that returned from a "remove" call, but still let you >> access that file, highly broken. > > Um - not if you have permission to read the file, but don't have > permission to remove it. You snipped: >> assuming the file is there, you have permissions, etc., basically that >> the call succeeds, First paragraph. From rganesan at myrealbox.com Wed Apr 20 02:06:14 2005 From: rganesan at myrealbox.com (Ganesan Rajagopal) Date: 20 Apr 2005 11:36:14 +0530 Subject: Why Python does *SLICING* the way it does?? References: <1113976729.450677.261130@o13g2000cwo.googlegroups.com> Message-ID: >>>>> "seberino at spawar" == seberino at spawar navy mil writes: > Many people I know ask why Python does slicing the way it does..... > Can anyone /please/ give me a good defense/justification??? Try http://www.everything2.com/index.pl?node_id=1409551 Ganesan -- Ganesan Rajagopal (rganesan at debian.org) | GPG Key: 1024D/5D8C12EA Web: http://employees.org/~rganesan | http://rganesan.blogspot.com From harold.fellermann at upf.edu Thu Apr 14 12:39:14 2005 From: harold.fellermann at upf.edu (harold fellermann) Date: Thu, 14 Apr 2005 18:39:14 +0200 Subject: curses for different terminals Message-ID: <0e347ff142b50459ee579b8d44e91d9b@upf.edu> Hi all, I want to use curses in a server application that provides a GUI for telnet clients. Therefore, I need the functionality to open and handle several screens. Concerning http://dickey.his.com/ncurses/ncurses-intro.html#init this can be done using the function newterm(type,ofp,ifp). However, this function seems not to be defined in the python library. Does anyone know how this can be done in python? cheers, - harold - -- Life is what happens while you're busy making other plans -- John Lennon From serpent17 at gmail.com Wed Apr 27 12:46:27 2005 From: serpent17 at gmail.com (serpent17 at gmail.com) Date: 27 Apr 2005 09:46:27 -0700 Subject: How do I parse this ? regexp ? In-Reply-To: References: Message-ID: <1114620387.283743.163460@z14g2000cwz.googlegroups.com> Thank you, it works, but I guess not all the way: for instance, I have this: 04242005 18:20:42-0.024329, 271.2469504, [-4.097900390625, 3.4332275390625, 105.062255859375], [0.0384521484375, 0.08416748046875, -1.026885986328125], [0.00640869140625, 0.00885009765625, 0.00701904296875] translates into '04242005 18:20:42-0.024329 271.2469504 -4.097900390625 3.4332275390625 105.062255859375 0.0384521484375 0.08416748046875 -1.026885986328125 0.00640869140625 0.00885009765625 0.00701904296875 \n' but I need to remove the first - between 18:20:42 and 0.024329 but not the others. Thank you in advance, Jake. From db3l at fitlinxx.com Tue Apr 19 18:16:36 2005 From: db3l at fitlinxx.com (David Bolen) Date: 19 Apr 2005 18:16:36 -0400 Subject: email: Content-Disposition and linebreaks with long filenames References: Message-ID: Martin K?rner writes: > I am using email module for creating mails with attachment (and then > sending via smtplib). > > If the name of the attachment file is longer than about 60 characters > the filename is wrapped in the Content-Disposition header: > > Content-Disposition: attachment; > filename="This is a sample file with a very long filename > 0123456789.zip" > > > This leads to a wrong attachment filename in email clients - the space > after "filename" is not shown or the client displays a special > character (the linbreak or tab before 0123456789.zip). Yes, it would appear that the default Generator used by the Message object to create a textual version of a message explicitly uses tab (\t) as a continuation character rather than space - probably because it looks a little nicer when printed. Interestingly enough, the default Header continuation character is just a plain space which would work fine here. I should point out that I believe this header format could be considered correct, although I find RFC2822 a bit ambiguous on this point. It talks about runs of FWS (folding white space) in an unfolding operation as being considered a single space (section 3.2.3). However, I suppose someone might argue if "runs" includes a single character. I think it should, but obviously some e-mail clients disagree :-) (...) > Is it possible to prevent the linebreak? Should be - two approaches I can think of (msg below is the email.Message): 1) Create your own Header object for the specific header line rather than just storing it as a string via add_header. For that specific header you can then override the default maximum line length. Something like: from email.Header import Header cd_header = Header('Content-Disposition: attachment; filename="....."', maxlinelen=998) msg['Content-Disposition'] = cd_header Note that because Header defaults to a space continuation character, you could also leave maxlinelen alone and let it break the line, but since it would break with a single space it would work right in clients. 2) Use your own Generator object to generate the textual version of the message (which is when the wrapping is occurring), and during the flattening process, disable (or set a longer value for) header wrapping. Something like: Assuming "fp" is an output File-like object: from email.Generator import Generator g = Generator(fp) g.flatten(msg, maxheaderlen=998) (or maxheaderlen=0 to disable wrapping) -- David From sjmachin at lexicon.net Tue Apr 12 18:07:06 2005 From: sjmachin at lexicon.net (John Machin) Date: Wed, 13 Apr 2005 08:07:06 +1000 Subject: [perl-python] Python documentation moronicities (continued) References: <1113301533.054410.203710@z14g2000cwz.googlegroups.com> Message-ID: On Tue, 12 Apr 2005 13:06:36 +0200, Roman Neuhauser wrote: > > Unfortunately, the python community seems to bathe in the > misorganized half-documentation, see e. g. > http://marc.theaimsgroup.com/?l=python-list&m=111303919606261&w=2 > especially the reply that (as I read it) suggested reverse > engineering as a viable alternative to documentation. As I read the reply, it was a smart-arse attempt at humour, a *PUN* on the word "list" (mailing list versus Python list). What I would call "introspection" (not "reverse engineering") was then suggested. Moreover, both of the concepts mentioned in the quoted thread (sequence.index() and the "in" operator) are IMESHO adequately documented. Do you have any examples of what you regard as "misorganized half-documentation"? Here's a puzzle for you: Where does this list appear? What's missing? "..., Mullender, Nagata, Ng, Oner, Oppelstrup, ..." From strombrg at dcs.nac.uci.edu Thu Apr 7 19:31:02 2005 From: strombrg at dcs.nac.uci.edu (Dan Stromberg) Date: Thu, 07 Apr 2005 23:31:02 GMT Subject: bourne shell parser in python Message-ID: Hi folks. We have a huge collection of sysadmin knowledge that's encoded in a vast array of bourne shell scripts. I'm now beginning to think that a transition to cfengine or similar might be a good idea, but I'm loathe to toss out all that /bin/sh code that's kept us from having to worry about neglecting this, that and the other thing for so long. So I guess my question is: "Is there a /bin/sh parser written in one of the many python-based parser-generator systems?" Thanks! From fredrik at pythonware.com Tue Apr 12 14:17:13 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 12 Apr 2005 20:17:13 +0200 Subject: Removing comments... tokenize error References: <2ab23d7a.0504120857.14ef094a@posting.google.com> Message-ID: "qwweeeit" wrote: > I don't know if this has already been corrected (I use Python 2.3) > or perhaps is a mistake on my part... it's a mistake on your part. adding a print statement to the for- loop might help you figure it out: > nLastLine=0 > for i in tokenize.generate_tokens(f.readline): print i > . if nLastLine != (i[2])[0]: # the 3rd element of the tuple is > . . nLastLine = (i[2])[0] # (startingRow, startingCol) > . . fOut.write(i[4]) (hints: what happens if a token spans multiple lines? and how does the tokenize module deal with comments?) From achrist at easystreet.com Sat Apr 9 17:15:38 2005 From: achrist at easystreet.com (Al Christians) Date: Sat, 09 Apr 2005 14:15:38 -0700 Subject: ntvdm problem on win2k In-Reply-To: <1742sqz77o8kb.dlg@usenet.alexanderweb.de> References: <115g61r25jhbaac@corp.supernews.com> <1742sqz77o8kb.dlg@usenet.alexanderweb.de> Message-ID: <115ghgd6gbamob2@corp.supernews.com> Alexander Schremmer wrote: > Windows tries to execute the cygwin symbolic link and fails. > Correcting your path works (as you said). One thing about that: I re-installed python (ie upgraded to python 2.3.5) and it did not solve the error. I assume that the python 2.3.5 installer is so well-mannered that it did not put itself at the head of the path, but saw that it was already in the path somewhere, and left itself there. This is nice, but it was disappointing, in that I did a fresh install to no avail. And, is it not fairly common for other installers of less refined software to add to the head of the path each time that they run, no matter how many times the same entry is repeated. So, by being very nice, python is sort of non-conformist or nearly eccentric, which I wish everyone would be. But how can one despise 99% of everything? When I installed cygwin, I checked it for python. It had something like python2.4.1.exe visible, but that symbolic link was not. No big deal. Al From Bill at SynectixLtd.com Thu Apr 21 04:20:32 2005 From: Bill at SynectixLtd.com (Bill Davy) Date: Thu, 21 Apr 2005 08:20:32 +0000 (UTC) Subject: (Python newbie) Using XP-SP2/MSVC6: No Python24_d.lib, winzip barfs on Python-2.4.1.tar, cannot download bzip2 References: <4266871c$1@nntp0.pdx.net> Message-ID: Hi Scott, Nice idea. Tried that but no more information about where the file was (not) found (see below). But many thanks for a useful flag. I did not see them in the documentation. What should I be lkooking for? [StopPres: Ah ha -h why did I not think of that?] Bill # installing zipimport hook import zipimport # builtin # installed zipimport hook # C:\Python24\lib\site.pyc matches C:\Python24\lib\site.py import site # precompiled from C:\Python24\lib\site.pyc # C:\Python24\lib\os.pyc matches C:\Python24\lib\os.py import os # precompiled from C:\Python24\lib\os.pyc import nt # builtin # C:\Python24\lib\ntpath.pyc matches C:\Python24\lib\ntpath.py import ntpath # precompiled from C:\Python24\lib\ntpath.pyc # C:\Python24\lib\stat.pyc matches C:\Python24\lib\stat.py import stat # precompiled from C:\Python24\lib\stat.pyc # C:\Python24\lib\UserDict.pyc matches C:\Python24\lib\UserDict.py import UserDict # precompiled from C:\Python24\lib\UserDict.pyc # C:\Python24\lib\copy_reg.pyc matches C:\Python24\lib\copy_reg.py import copy_reg # precompiled from C:\Python24\lib\copy_reg.pyc # C:\Python24\lib\types.pyc matches C:\Python24\lib\types.py import types # precompiled from C:\Python24\lib\types.pyc # C:\Python24\lib\locale.pyc matches C:\Python24\lib\locale.py import locale # precompiled from C:\Python24\lib\locale.pyc import _locale # builtin # C:\Python24\lib\codecs.pyc matches C:\Python24\lib\codecs.py import codecs # precompiled from C:\Python24\lib\codecs.pyc import _codecs # builtin import encodings # directory C:\Python24\lib\encodings # C:\Python24\lib\encodings\__init__.pyc matches C:\Python24\lib\encodings\__ini t__.py import encodings # precompiled from C:\Python24\lib\encodings\__init__.pyc # C:\Python24\lib\encodings\aliases.pyc matches C:\Python24\lib\encodings\aliase s.py import encodings.aliases # precompiled from C:\Python24\lib\encodings\aliases.py c # C:\Python24\lib\encodings\cp1252.pyc matches C:\Python24\lib\encodings\cp1252. py import encodings.cp1252 # precompiled from C:\Python24\lib\encodings\cp1252.pyc # C:\Python24\lib\warnings.pyc matches C:\Python24\lib\warnings.py import warnings # precompiled from C:\Python24\lib\warnings.pyc # C:\Python24\lib\linecache.pyc matches C:\Python24\lib\linecache.py import linecache # precompiled from C:\Python24\lib\linecache.pyc Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import sys # C:\Python24\lib\encodings\cp850.pyc matches C:\Python24\lib\encodings\cp850.py import encodings.cp850 # precompiled from C:\Python24\lib\encodings\cp850.pyc >>> import SHIP Traceback (most recent call last): File "", line 1, in ? ImportError: No module named SHIP >>> import SHIP_d Traceback (most recent call last): File "", line 1, in ? ImportError: No module named SHIP_d >>> import _SHIP Traceback (most recent call last): File "", line 1, in ? ImportError: No module named _SHIP >>> import _SHIP_d Traceback (most recent call last): File "", line 1, in ? ImportError: DLL load failed: The specified module could not be found. >>> _SHIP_d Traceback (most recent call last): File "", line 1, in ? NameError: name '_SHIP_d' is not defined >>> "Scott David Daniels" wrote in message news:4266871c$1 at nntp0.pdx.net... > Bill Davy wrote: >> Thanks Jaime, >> >> I'm making gradual progress and am finding it quite satisfying. Resorted >> to tracing Python in MSVC6 to see what it was trying to IMPORT, which is >> a bit heavy but thank heavens for the sources. > You might try running python from a command window and running it "-v" as > in: > > python -v prog.py -args ... > > --Scott David Daniels > Scott.Daniels at Acm.Org From thn at mail.utexas.edu Thu Apr 14 19:54:16 2005 From: thn at mail.utexas.edu (Thomas Nelson) Date: Thu, 14 Apr 2005 18:54:16 -0500 Subject: new to mac OS10 Message-ID: I'm on a mac OS X (10.3.8), and I seem to have accidentally destroyed the default python installation. How should I put it on? Do I need to use the unix version? any help would be greatly appreciated. THN From skip at pobox.com Fri Apr 1 08:07:12 2005 From: skip at pobox.com (Skip Montanaro) Date: Fri, 1 Apr 2005 07:07:12 -0600 Subject: Spider - path conflict [../test.htm,www.nic.nl/index.html] In-Reply-To: <1112357294.881735.287370@o13g2000cwo.googlegroups.com> References: <1112357294.881735.287370@o13g2000cwo.googlegroups.com> Message-ID: <16973.18304.369331.290488@montanaro.dyndns.org> martijn> I thought I was ready with my own spider... But then there was martijn> a bug, or in other words a missing part in my code. martijn> I forget that people do this in website html: martijn> is oke martijn> error martijn> error pydoc urlparse.urljoin Skip From tomlongridge at gmail.com Mon Apr 18 07:42:17 2005 From: tomlongridge at gmail.com (Tom Longridge) Date: 18 Apr 2005 04:42:17 -0700 Subject: Strings and Lists Message-ID: My current Python project involves lots repeatating code blocks, mainly centred around a binary string of data. It's a genetic algorithm in which there are lots of strings (the chromosomes) which get mixed, mutated and compared a lot. Given Python's great list processing abilities and the relative inefficiencies some string operations, I was considering using a list of True and False values rather than a binary string. I somehow doubt there would be a clear-cut answer to this, but from this description, does anyone have any reason to think that one way would be much more efficient than the other? (I realise the best way would be to do both and `timeit` to see which is faster, but it's a sizeable program and if anybody considers it a no-brainer I'd much rather know now!) Any advice would be gladly recieved. From kent37 at tds.net Fri Apr 29 06:49:32 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 29 Apr 2005 06:49:32 -0400 Subject: large dictionary creation takes a LOT of time. In-Reply-To: <1114757468.367583.210840@z14g2000cwz.googlegroups.com> References: <1114757468.367583.210840@z14g2000cwz.googlegroups.com> Message-ID: <42720ccb$1_2@newspeer2.tds.net> possibilitybox wrote: > this code here: > > > def wordcount(lines): > for i in range(len(lines)/8): > words = lines[i].split(" ") > if not locals().has_key("frequency"): > frequency = {} > for word in words: > if frequency.has_key(word): > frequency[word] += 1 > else: > frequency[word] = 1 > return frequency > wordcount(lines) > > is taking over six minutes to run on a two megabyte text file. i > realize that's a big text file, a really big one (it's actually the > full text of don quixote.). i'm trying to figure out how. is there a > better way for me to do a frequency count of all the words in the text? > it seems to me like this should scale linearly, but perhaps it isn't? > i don't know much about algorithmic complexity. if someone could give > a breakdown of this functions complexity as well i'd be much obliged. > > lines is expected to be a list of lines as provided by file.readline() > Here is a little cleaner version. It takes about a second to run on my PC. What hardware are you running on? path = 'DonQuixote.txt' frequency = {} for line in open(path): for word in line.split(): if frequency.has_key(word): frequency[word] += 1 else: frequency[word] = 1 print len(frequency), 'words' Kent From olsongt at verizon.net Wed Apr 13 12:23:17 2005 From: olsongt at verizon.net (olsongt at verizon.net) Date: 13 Apr 2005 09:23:17 -0700 Subject: terminate exectutioin in PythonWin In-Reply-To: References: <4u6dnQT8_ecAk8DfRVn-pA@comcast.com> Message-ID: <1113409397.223863.253400@l41g2000cwc.googlegroups.com> > > > > > D'oh. I didn't think of that. > > Thanks > > Jim A little off-topic, but here's a little more fun with pythonwin. You can spawn the debugging environment from a normal python script running outside of pythonwin with: import pywin.debugger;pywin.debugger.set_trace() Also note that 'pywin.debugger.set_trace()' can be used anywhere if you're trying to 'keep' breakpoints in the code without relying an an IDE or project tracking them for you. From danb_83 at yahoo.com Wed Apr 13 13:21:39 2005 From: danb_83 at yahoo.com (Dan Bishop) Date: 13 Apr 2005 10:21:39 -0700 Subject: Compute pi to base 12 using Python? References: <1113390479.738210.49530@z14g2000cwz.googlegroups.com> <425d3b01$1@nntp0.pdx.net> Message-ID: <1113412899.536885.285890@g14g2000cwa.googlegroups.com> Scott David Daniels wrote: > Roy Smith wrote: > > In article <1113390479.738210.49530 at z14g2000cwz.googlegroups.com>, > > "Dan Bishop" wrote: > > > >>But there's no reason other than tradition why you should arrange them > >>into groups of 10. > > > > Well, it is traditional for people to have 10 fingers :-) > > > > Other fun things to think about are negative bases. For example, 3(10) = > > 111(-2). That's 1*(-2)^2 + 1*(-2)^1 + 1*(-2)^0 = 4 - 2 + 1. I can't > > think of any use for negative bases, but they are a fun game to play with > > (if you're into that sort of stuff). > > > > Non-integer bases are fun too. Pi has an interesting representation in bases between 0 and 1, exclusive. There are a finite number of digits after the radix point, but an infinite number _before_ it. > If you think those are fun, try base (1j - 1) I think Knuth wrote something about complex bases back in the year 1000200000001000000010001. From cmedcoff at hotmail.com Sun Apr 3 09:00:43 2005 From: cmedcoff at hotmail.com (Chuck) Date: Sun, 3 Apr 2005 09:00:43 -0400 Subject: Newsgroup Programming Message-ID: I've found and used the nntplib module for newgroup programming. Can anyone suggest a library, technique or reference on how to combine mutliple messages with attachments such as mp3's, .wmv, *.avi, etc.? From eurleif at ecritters.biz Fri Apr 29 14:25:45 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Fri, 29 Apr 2005 18:25:45 GMT Subject: Reusing object methods? In-Reply-To: References: Message-ID: Ivan Voras wrote: > I want to 'reuse' the same method from class A in class B, and without > introducing a common ancestor for both of them - is this possible in an > elegant, straightforward way? >>> import new >>> >>> class A: ... def foo(self): ... print "Hello, %s!" % self.__class__.__name__ ... >>> class B: ... def __init__(self): ... self.foo = new.instancemethod(A.foo.im_func, self, B) ... >>> A().foo() Hello, A! >>> B().foo() Hello, B! From andre.roberge at gmail.com Wed Apr 20 12:03:01 2005 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9_Roberge?=) Date: Wed, 20 Apr 2005 13:03:01 -0300 Subject: Troll? was: Re: goto statement In-Reply-To: References: <20050420092359.81900.qmail@web8409.mail.in.yahoo.com> <42664190.6010507@i.com.ua> <87vf6hlkix.fsf@wilson.rwth-aachen.de> <70sc615akd7mfdkmrjls956o1u5rglm74t@4ax.com> Message-ID: Maxim Kasimov wrote: > > by the way, "goto" statement will be useful for writing more powerful > obfuscators > Let me get that clear: you want a goto to help with debugging. And you want to obfuscate your code even more? !? Perhaps you need to write in Perl, or some other similar language. Writing in Python is for those that seek clarity (not obfuscation) and less bugs. Which is why a goto statement should definitely never be part of Python! Andr? From gry at ll.mit.edu Thu Apr 14 09:17:28 2005 From: gry at ll.mit.edu (gry at ll.mit.edu) Date: 14 Apr 2005 06:17:28 -0700 Subject: Inelegant In-Reply-To: <2v3s51dg0f69mlduo7akt8i66s22qihfrn@4ax.com> References: <2v3s51dg0f69mlduo7akt8i66s22qihfrn@4ax.com> Message-ID: <1113484648.201612.249450@g14g2000cwa.googlegroups.com> I sometimes use the implicit literal string concatenation: def SomeFunction(): if SomeCondition: MyString = 'The quick brown fox ' \ 'jumped over the ' \ 'lazy dog' print MyString SomeFunction() The quick brown fox jumped over the lazy dog It looks pretty good, I think. One could use triple quotes too, if the string contains quotes. -- George From mensanator at aol.com Wed Apr 13 18:16:55 2005 From: mensanator at aol.com (mensanator at aol.com) Date: 13 Apr 2005 15:16:55 -0700 Subject: Compute pi to base 12 using Python? References: <1113390479.738210.49530@z14g2000cwz.googlegroups.com> Message-ID: <1113430615.592715.78440@f14g2000cwb.googlegroups.com> Dan Bishop wrote: > Dick Moores wrote: > > I need to figure out how to compute pi to base 12, to as many digits > as > > possible. I found this reference, > , > > but I really don't understand it well enough. > > How many stars are in "*************************"? > > You probably answered "25". This means that, for convenience, you've > broken down the row of stars into ********** + ********** + *****, that > is, 2 tens with 5 left over, which the base-10 numeral system denotes > as "25". > > But there's no reason other than tradition why you should arrange them > into groups of 10. For example, you could write it as ******** + > ******** + ******** + *, or 3 eights plus 1. In octal (base-8) > notation, this is written as "31"; the "tens" place in octal represents > eights. > > In general, in the base-r numeral system, the nth digit to the left of > the ones digit represents r^n. For example, in the binary number > 11001, the place values for each digit are, right to left, 1, 2, 4, 8, > and 16, so the number as a whole represents > 1?16+1?8+0?4+0?2+1?1=16+8+1=25. This analogous to 25=2?10+5 in > base-10. > > It's also possible to write it as 3?8+0?4+0?2+1?1 = 3001 base 2, > but by convention, base-r only uses the digits in range(r). This > ensures a unique represenation for each number. This makes "11001" the > unique binary representation for decimal 25. > > Note that for bases larger than 10, the digits will be numbers that are > not single digits in base 10. By convention, letters are used for > larger digits: A=10, B=11, C=12, ... Z=35. For example, the number > (dec) 2005 = 1?12?+1?12?+11?12+1?1 is represented in base-12 by > "11B1". > > Fractions are handled in a similar manner. The nth place to the right > of the radix point (i.e., the "decimal point", but that term is > inaccurate for bases other than ten) represents the value radix**(-n). > > For example, in binary, > 0.1 = 1/2 = dec. 0.5 > 0.01 = 1/4 = dec. 0.25 > 0.11 = 1/2 + 1/4 = 3/4 = dec. 0.75 > 0.001 = 1/8 = dec. 0.125 > 0.01010101... = 1/4 + 1/16 + 1/64 + ... = 1/3 > 0.0001100110011... = 1/10 = dec. 0.1 > > The last row explains why Python gives: > > >>> 0.1 > 0.10000000000000001 > > Most computers store floating-point numbers in binary, which doesn't > have a finite representation for one-tenth. The above result is > rounded to 53 signficant bits > (1.100110011001100110011001100110011001100110011010?2^-4), which is > exactly equivalent to decimal > 0.1000000000000000055511151231257827021181583404541015625, but gets > rounded to 17 significant digits for display. > > Similarly, in base-12: > > 0.1 = 1/12 > 0.14 = 1/12 + 4/144 = 1/9 > 0.16 = 1/12 + 6/144 = 1/8 > 0.2 = 2/12 = 1/6 > 0.3 = 3/12 = 1/4 > 0.4 = 4/12 = 1/3 > 0.6 = 6/12 = 1/2 > 0.8 = 8/12 = 2/3 > 0.9 = 9/12 = 3/4 > 0.A = 10/12 = 5/6 > > Notice that several common fractions have simpler representations in > base-12 than in base-10. For this reason, there are people who believe > that base-12 is superior to base-10. > (http://www.dozenalsociety.org.uk) > > > Could someone show me how to do what I need? > > You'll need 3 things: > > (1) An algorithm for computing approximations of pi. > > The simplest one is 4*(1-1/3+1/5-1/7+1/9-1/11+...), which is based on > the Taylor series expansion of 4*arctan(1). > > There are other, faster ways. Search Google for them. That one's way too slow. I found the one I use below on Mathworld. > > (2) An unlimited-precision numeric representation. The standard > "float" isn't good enough: It has only 53 bits of precision, which is > only enough for 14 base-12 digits. > > The "decimal" module will probably work, although of course its base-10 > internal representation will introduce slight inaccuracies. I'm using GMPY (see code). > > (3) A function for converting numbers to their base-12 representation. GMPY can do this also. > > For integers, this can be done with: > > DIGITS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" > def itoa(num, radix=10): > is_negative = False > if num < 0: > is_negative = True > num = -num > digits = [] > while num >= radix: > num, last_digit = divmod(num, radix) > digits.append(DIGITS[last_digit]) > digits.append(DIGITS[num]) > if is_negative: > digits.append("-") > digits.reverse() > return ''.join(digits) > > For a floating-point number x, the representation with d "decimal" > places count be found by taking the representation of int(round(x * > radix ** d)) and inserting a "." d places from the right. # better pi/2 = 1 + 1/3 + (1*2)/(3*5) + (1*2*3)/(3*5*7) + ... import gmpy # unlimited precision math library def pialso(n,b): # input number of digits (n) in requested base (b) p = gmpy.mpq(1,1) # gmpy rationals are unlimited precision sn = 1 sd = 3 c = gmpy.mpq(sn,sd) # create the next term to be summed num = gmpy.mpf(p.numer()) # seperately convert the numerator den = gmpy.mpf(p.denom()) # and denominator to gmpy floats f = (num/den) * 2 # to get unlimited precision float olds = gmpy.fdigits(f,b,n,0,1,2) # extract the requested digits and do base conversion done = 0 while done==0: p = p + c # sum next term of pi equation sn += 1 # set numerator sd += 2 # and demoniator c = c * gmpy.mpq(sn,sd) # to create term for next iteration num = gmpy.mpf(p.numer()) # meanwhile, convert this iteration den = gmpy.mpf(p.denom()) f = (num/den) * 2 # to an unlimited precision float s = gmpy.fdigits(f,b,n,0,1,2) if s[0]==olds[0]: # we're done when the number of digits done = 1 # we want stops changing else: # otherwise, keep iterating until we reach the olds = s # the desired convergence print s[0],sn # prints the digits and how many iterations it took print """ The first 100 digits of pi in base 10. >>> pialso(100,10) 3141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067 327 The first 100 digits of pi in base 12. >>> pialso(100,12) 3184809493b918664573a6211bb151551a05729290a7809a492742140a60a55256a0661a03753a3aa54805646880181a3682 353 Note it took more iterations (longer to converge) because base 12 digits are "bigger" than base 10. """ From mwm at mired.org Tue Apr 26 03:54:01 2005 From: mwm at mired.org (Mike Meyer) Date: Tue, 26 Apr 2005 02:54:01 -0500 Subject: Python or PHP? References: <1114254894.512656.297040@l41g2000cwc.googlegroups.com> <87hdhxwj6s.fsf@debian.kirkjobsluder.is-a-geek.net> <1114274632.128667.281820@l41g2000cwc.googlegroups.com> <86br85rvfw.fsf@guru.mired.org> <863bthrmtg.fsf@guru.mired.org> <86y8b8rgg5.fsf@guru.mired.org> <86d5skr2l3.fsf@guru.mired.org> <86y8b7pydc.fsf@guru.mired.org> <86u0lvph0n.fsf@guru.mired.org> <86mzrmo5j8.fsf@guru.mired.org> <86is2anqbj.fsf@guru.mired.org> Message-ID: <86r7gym0rq.fsf@guru.mired.org> John Bokma writes: > Mike Meyer wrote: > >> John Bokma writes: >>> You already showed code like: >> Actually, I never showed you this code. > hence *like*, and yes you did, in a footnote. Yes, but *I* didn't say like, because I wanted to point out that you had purposely uglified it. >> In this case, the good rewrite invokes the well-known logical operator >> "not": >> >> if not condition then >> something > > unless condition then > something > > Weird, we use constructions like that in normal language all the time, > and when we program it's suddenly bloat? If you want to program in a normal language, I recommend COBOL. Natural languages have a different purpose than programming languages, which are designed to communicate algorithms clearly and concisely. In that domain, it's just bloat. >>>>> it makes the code more readable. >>>> Then why do most Perl programmers consider unless "! a good idea"? >>> Reread the last part of the last sentence you quoted above. >> I can't - in being argumentative, you neglected to include it. > *sigh* in your obsession to call me argumentative, your skipped over it: > "it makes the code more readable" Let's get the facts straight here. I may have skipped over it the first time, but I didn't call you argumentative then. It wasn't until you argumentative until after you deleted it that I said you were argumentative. >> What you created was a list. Not in Python or Perl, but in English. > I doubt if any Perl programmer in the given context would have any > problem with it, but lets drop it. No, let's not. It's a perfect example of why having multiple ways to do things is a bad idea. >> Oh, I understood it. > Sure, is that why you talked about a tuple? But, lets drop it. No, I talked about a tuple to point out that doing it right made something a machine could parse properly, with no thought at all. >> And so far, I've only said *two* things were wrong with Perl. One is >> that it provides more than one way to do things - which point you've >> made for me by arguing about how you did/didn't choose the right one >> in an example. > If you think I gave a wrong example, give the right one. The only reason > for an argument was your lack of knowledge about split and map, which > only tells something about you, not Perl. I already gave the right one. The one with the optional parens put back in. >> to a >> scalar when you wanted a list was bad. You haven't argued that I was >> wrong about Perl in either case. > *sigh* if you want a list, you assign it to something that can handle a > list. If you assing a list to a scalar, you get the count. So if you > want to select items out of a list on a criteria, you use grep in a list > context, if you want to count the items, guess... You still haven't argued that I'm wrong about Perl. You're arguing about whether or not a behavior is bad, not the behavior. Trying to argue that I'm wrong because I'm wrong about Perl's behavior being bad would be a lot more effective if you pointed out where the descriptions of bad behavior were incorrect. >>> It's also a restriction. Why do you think in Java one can call the gc >>> explicitly? >> If it's a restriction, there must be something it restricts you from >> doing. Care to tell me exactly what garbage collection keeps you from >> doing? > real time guaranteed memory allocation/deallocation (which might be > fixed by now in Java) That's an implementation feature, not a language feature. That's an implementation feature, not a language feature. I might also note that you're wrong about alloc/free, in that you don't get real time guaranteed memory allocation/deallocation with it, either. Care to try again? >>> In my case it saves time the other way around, I consider correct >>> usage trivial, but the typing all the time... >> I guess you haven't had to chase many bugs related to missing free's > In my own code? I can't remember. In code written by other people: in > the cases they forget to free memory they did so many other things wrong > that I sincerly hope they have found other work by now. I'd say you've never done anything but trivial >> skilled programmers, and makes wrong choices painful. TMTOWTDI makes >> wrong choices - or ugly code - easy. > Especially if one keeps mixing up map and grep :-D Righ - you once again avoid the real issue. >> So the jvm implementations you're familiar with have really bad >> garbage collectors. > I have no idea if this has changed recently. The last thing I read about > it is that there are 4 kinds of garbage collection one can select in > Sun's implementation. If you had enough experience with jvm's, you'd know that Sun's wasn't the only one out ther. >> A good programmer won't immediately abandon either >> Java or garbage collection. They'd check out other implementations of >> the jvm to see if one of those has a better garbage collector. > Uhm, people often pick Java because of write once, run everywhere. So > that is not always, or even rarely an option. Switching jvm's doesn't mean you switch away from Java. It means you switch the implementation of the jvm that Java is running on. "Run anywhere" has nothing to do with this. >> another. There are probably others as well. You can't simply tag one >> as "better" without knowing what the problem domain is. > I didn't say better, what I meant: there are situations real time > free/alloc is prefered, unless my knowledge of gc in general is > outdated. Your knowledge of free/alloc is wrong. They don't guarantee real time behavior. Nor do they guarantee memory allocations. I'm beginning to think your programming experience is limited. >>> I haven't been using *foreach* for quite some time, I use *for* all >>> the time. Which is just because I am lazy. >> >> You make my case for me. You write in a subset of Perl that excludes >> "foreach". Is that the "absolute beginner" or the "beginner" subet? >> Or maybe it's a subset that doesn't depend on the skill level of the >> programmer. > > "The foreach keyword is just a synonym for the for keyword, so you can > just use foreach and for interchangeably, whichever you think is more > readable in a given situation" (Programming Perl, 3rd edition, p118) You didn't bother refuting the point that you've created a subset of Perl which never uses "foreach". >>>> A good programmer will compare the toolset to others he's familiar >>>> with, >>> which only can be done when he/she knows both (almost) equally well. >> >> Nope. A quick survey of a toolset is all that's needed to make a first >> approximation as to it's quality - to someone who's familiar with >> enough toolsets, anyway. > Weird: I am going study Python for at least one year. Unless you call > that a quick survey :-D. That's enough time to become proficient in a language. Which isn't required if all you want to do is decide if it's well-designed. >> A good understanding of toolset design allows you to point out flaws >> in a toolset without becoming intimately familiar with it. For >> instance, mutliple nearly identical ways to express the same construct >> is always a flaw in a toolset. Which has been the point I've been >> making the whole time. > So a hammer is a bad tool, since one can use a scewdriver... I didn't say a word about bad tools. > I always wondered why an artist, like for example a painter, has so many > nearly identical tools... Because they do different things with them. while and if are nearly identical tools - they both have a keyword, a boolean and a block of code. But they do different things. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From rupole at hotmail.com Mon Apr 18 21:20:11 2005 From: rupole at hotmail.com (Roger Upole) Date: Mon, 18 Apr 2005 21:20:11 -0400 Subject: Updating Windows File Summary Data References: <1113860278.876481.210270@z14g2000cwz.googlegroups.com> Message-ID: <42645d94$1_1@127.0.0.1> Pywin32 has functions to read and write these properties. Take a look at testStorage.py in the \win32\test directory for an example of how to use them. Roger "Denrael" wrote in message news:1113860278.876481.210270 at z14g2000cwz.googlegroups.com... >I am looking for a way in Python to update Windows File Summary > Metadata. By that I mean the data (Title, Subject, Keywords, Comments) > found when you right click a windows file, select properties and then > summary. Can anyone point me in the right direction? > ----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups ----= East and West-Coast Server Farms - Total Privacy via Encryption =---- From rpmuller at gmail.com Fri Apr 1 17:20:51 2005 From: rpmuller at gmail.com (RickMuller) Date: 1 Apr 2005 14:20:51 -0800 Subject: Help with splitting Message-ID: <1112394051.064413.250990@g14g2000cwa.googlegroups.com> I'm trying to split a string into pieces on whitespace, but I want to save the whitespace characters rather than discarding them. For example, I want to split the string '1 2' into ['1',' ','2']. I was certain that there was a way to do this using the standard string functions, but I just spent some time poring over the documentation without finding anything. There's a chance I was instead thinking of something in the re module, but I also spent some time there without luck. Could someone point me to the right function, if it exists? Thanks in advance. R. From superprad at gmail.com Sat Apr 23 16:26:19 2005 From: superprad at gmail.com (superprad at gmail.com) Date: 23 Apr 2005 13:26:19 -0700 Subject: Handling lists In-Reply-To: References: <1114285850.091749.188680@f14g2000cwb.googlegroups.com> Message-ID: <1114287979.253782.61360@g14g2000cwa.googlegroups.com> yes that makes sense.But the problem I am facing is if list= [300,301,303,305] I want to consider it as one cluster and include the range as [300,305] so this is where I am missing the ranges. so If the list has l = [300,301,302,308,401,402,403,408] i want to include it as [[300,308],[401,408]]. From mahs at telcopartners.com Fri Apr 8 16:03:10 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Fri, 08 Apr 2005 13:03:10 -0700 Subject: curious problem with large numbers - Due to subprocess - using pickle In-Reply-To: References: <723eb693050407124816431b6a@mail.gmail.com> <4255cd93$1@nntp0.pdx.net> <4256a676@nntp0.pdx.net> <4256b80b.34130777@news.oz.net> <4256b774$1@nntp0.pdx.net> <4256c65c$1@nntp0.pdx.net> Message-ID: Michael Spencer wrote: >> > Problem is associated with executing iteractive input in a subprocess. > > >python idle.py -n > > IDLE 1.1 ==== No Subprocess ==== > >>> 1e10000 > 1.#INF > >>> > > Michael > > It seems that the culprit is pickle - used to send messages between the IDLE shell and the execution server. >>> import pickle >>> pickle.dumps(1e10000) 'F1.#INF\n.' >>> pickle.loads(_) Traceback (most recent call last): File "", line 1, in ? File "c:\python24\lib\pickle.py", line 1394, in loads return Unpickler(file).load() File "c:\python24\lib\pickle.py", line 872, in load dispatch[key](self) File "c:\python24\lib\pickle.py", line 968, in load_float self.append(float(self.readline()[:-1])) ValueError: invalid literal for float(): 1.#INF >>> import cPickle as pickle >>> pickle.dumps(1e10000) 'F1.#INF\n.' >>> pickle.loads(_) Traceback (most recent call last): File "", line 1, in ? ValueError: could not convert string to float >>> It seems that somewhere IDLE traps this error and shows '1.0' instead. However, I can't follow the IDLE output code, so I won't try to track this down any further IDLE 1.1 >>> 2e10000 1.0 >>> 3e10000 1.0 >>> 100e10000 1.0 >>> 999e1000 1.0 >>> Michael From fabio.pliger at siavr.it Wed Apr 13 09:12:41 2005 From: fabio.pliger at siavr.it (Fabio Pliger) Date: Wed, 13 Apr 2005 13:12:41 GMT Subject: printing with wxPython References: Message-ID: Yeah, There are two about printing... there is also an example in the wxDemo... but they all talk about printing text... In my case i need to print (or at least to make a print preview) a bitmap (or a panel...) "Peter Hansen" ha scritto nel messaggio news:FKydnWvMkrSIasbfRVn-3g at powergate.ca... > Fabio Pliger wrote: > > Hi! > > I'm using wxPython to handle my application gui.. So, I have a notebook > > widget and i have to print the object inside it's tab ... Maybe doing a > > preview before printing... I know that wx has many objects to handle > > printing.. i've tryied to use them, but i wasn't able to... Any hint? By > > now, i solved the problem saving a screenshot if the screen in an image(bmp) > > and then sending it to printer... (a print preview would be cool...) > > tnx > > Maybe the recipes on the wxPython wiki page would > help: > http://wiki.wxpython.org/index.cgi/RecipesOther > > There are at least two dealing with "Printing". From dh47302 at yahoo.com Tue Apr 19 03:31:19 2005 From: dh47302 at yahoo.com (Klaus Alexander Seistrup) Date: Tue, 19 Apr 2005 07:31:19 +0000 (UTC) Subject: ANN: Python 2.3.2 for PalmOS available References: <1113608405.558884.235890@f14g2000cwb.googlegroups.com> <1113830286.364709.164740@z14g2000cwz.googlegroups.com> Message-ID: Lucio Torre wrote: > Make sure you write the expression in the lower text-area, and > then press the send button. This should do it. Ah, that's the trick! It wasn't obvious that there were two text areas, and I intuitively wrote commands at the python prompt. Problem solved. Say, are floats implemented? Comparisons seem to work, but print'ing doesn't: #v+ >>> 1.0 > 0.5 True >>> print 1.23 %.*g >>> #v- -- Klaus Alexander Seistrup Magnetic Ink, Copenhagen, Denmark http://magnetic-ink.dk/ From saravanand at vsnl.net Mon Apr 25 10:14:21 2005 From: saravanand at vsnl.net (Saravanan) Date: 25 Apr 2005 07:14:21 -0700 Subject: Python23.pdb Message-ID: <1114438461.753620.324570@z14g2000cwz.googlegroups.com> Hello, 1) Is is possible to get the pdb files for the Python version 2.3.3? Python 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit (Intel)] on win32 2) Is there way to enable symptom collection/traces in the Python Core modules? Thanks in advance. - Saravanan D From huzaifa at hostway.com Tue Apr 26 10:56:09 2005 From: huzaifa at hostway.com (Huzaifa Tapal) Date: Tue, 26 Apr 2005 09:56:09 -0500 Subject: TypeError: ssl() argument 1 must be _socket.socket, not _socketobject Message-ID: <426E5689.1010706@hostway.com> I am getting this error from python 2.3.5 when making secure socket connections from my mod_python based application. It is very odd because we cannot replicate this in the development environment, only in production on a cluster of 2 debian boxes with Apache2 MPM Worker w/ Mod Python 3.13. Does anybody have any ideas as to what could be causing this error? Here is the full traceback: Traceback: File "/home/orderform/www/cgi-bin/OrderForm_bundle/hwmodules/register/dp_registrar/DPRegistrar.py", line 95, in _ _execCmd con.endheaders() File "/usr/lib/python2.3/httplib.py", line 715, in endheaders self._send_output() File "/usr/lib/python2.3/httplib.py", line 600, in _send_output self.send(msg) File "/usr/lib/python2.3/httplib.py", line 567, in send self.connect() File "/usr/lib/python2.3/httplib.py", line 988, in connect ssl = socket.ssl(sock, self.key_file, self.cert_file) File "/usr/lib/python2.3/socket.py", line 73, in ssl return _realssl(sock, keyfile, certfile) TypeError: ssl() argument 1 must be _socket.socket, not _socketobject The thing is that if we restart the web server, it works fine for about 20 minutes after which we start getting these errors. Any help would be appreciated. Hozi From fuzzyman at gmail.com Tue Apr 12 11:03:21 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 12 Apr 2005 08:03:21 -0700 Subject: Northampton, UK Message-ID: <1113315607.375554.171070@f14g2000cwb.googlegroups.com> Just on the off chance.... I thought I'd ask if there were any Pythoneers out there local to Northampton UK ? Best Regards, Fuzzy http://www.voidspace.org.uk/python From edcjones at comcast.net Sun Apr 10 16:15:14 2005 From: edcjones at comcast.net (Edward C. Jones) Date: Sun, 10 Apr 2005 16:15:14 -0400 Subject: numarray.array can be VERY slow Message-ID: Steven Bethard wrote: > As mentioned, this has nothing to do with numarray, and everything to > do with your inexplicable use of lists. Why don't you just write this > as: > > arr = numarray.ones((8, 8, 256, 256), Float64) The code I posted was simplified from a larger program which I have now revised. But I still ask: why did it take 4.3 seconds to run? From mwm at mired.org Fri Apr 22 02:05:21 2005 From: mwm at mired.org (Mike Meyer) Date: Fri, 22 Apr 2005 01:05:21 -0500 Subject: python LEX References: Message-ID: <864qdztkgu.fsf@guru.mired.org> Miki Tebeka writes: > Hello jozo, > >> I have to work on python lexical definition in Lex. I spent lots of my >> time to find regular expresions written for Lex of Python language but >> nothing. >> Can somebody help me? > http://www.antlr.org/grammar/list (search for Python) > > You can search in projects like Pyrex and Parrot for their parser > implementation. The python grammar is included with the Python sources, and is used to build the compiler. > HTH. Trouble is, he wants a lexer, not a parser. The lexer in the sources is an ad-hoc package, contained in Parser/tokenizer.c. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From flupke at nonexistingdomain.com Sat Apr 9 13:21:46 2005 From: flupke at nonexistingdomain.com (flupke) Date: Sat, 09 Apr 2005 17:21:46 GMT Subject: workaround for generating gui tools In-Reply-To: <3bqgh6F6larilU1@individual.net> References: <1113061810.530359.172720@g14g2000cwa.googlegroups.com> <3bqgh6F6larilU1@individual.net> Message-ID: Reinhold Birkenfeld wrote: > Have to disagree strongly. > > It's evil anyway (for more complex applications) to put GUI construction > in your code. GUI should be described appropriately in data files. > > Glade does this very good, and with pygtk it's no problem to use the XML files. > > Reinhold So the GUI should be seperate from the code. Is the way i described valid then? Extending from the gui class and putting event handlers in the derived classes? Or is there a better way to seperate the GUI from the code? Benedict From vze4rx4y at verizon.net Thu Apr 14 18:08:37 2005 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Thu, 14 Apr 2005 22:08:37 GMT Subject: New-style classes, iter and PySequence_Check References: Message-ID: [Tuure Laurinolli] > Someone pasted the original version of the following code snippet on > #python today. I started investigating why the new-style class didn't > work as expected > classes apparently don't return true for PyInstance_Check, which causes > a problem in PySequence_Check, since it will only do an attribute lookup > for instances. > > Things probably shouldn't be this way. Should I go to python-dev with this? PyInstance_Check is defined as checking for instances of old style classes. Hence, it appropriate that it does not return True for instances of new-style classes. PySequence_Check is pretty good shape. In general, it is not always possible to tell a mapping from a sequence, but the function does try to take advantage of all available information. In particular, it has a separate code path for new-style instances which sometimes have additional information (i.e. dict and its subclasses fill the tp_as_mapping->mp_subscript slot instead of the tp_as_sequence->sq_slice slot). Old style classes never inherit from dict, tuple, list, etc. so that slot distinction isn't meaningful. Accordingly, PySequence_Check simply checks to see if an object defines __getitem__ and that check entails an attribute lookup. The posted code snippet uses a __getattr__ gimmick to supply an affirmative answer to that check. The docs do not make guarantees about how iter(o) will determine whether object o is a sequence. Currently, it does the best it can and that entails having different implementation logic for new-style and old-style objects as described above. The provided snippet uses the __getattr__ gimmick to reveal the implementation specific behavior. Mystery solved. In contrast, the docs do make guarantees about explicit attribute lookup (i.e. that an attribute lookup will actually occur and that slot checking logic will not be substituted). The posted snippet reveals that these guarantees are intact for both new and old-style classes. Knowing all of this reveals the behavior to be a feature rather than a bug -- the feature being that operator.IsMappingType and operator.IsSequenceType do a remarkable job (few false positives and no false negatives) across a huge variety of object types. It has been tested with instances of set, int, float, complex, long, bool, str, unicode, UserString, list, UserList, tuple, deque, NoneType, NotImplemented, new and old style instances with and without defining __getitem__. Also, tested were subclasses of the above types. The false positives are limited to user defined classes (new or old-style) defining __getitem__. Since the mapping API overlaps with the sequence API, it is not always possible to distinguish the two. Of course, you found that it is possible to throw a monkey wrench in the process using __getattr__ to exploit undefined, implementation specific behavior. Don't do that. If a class needs to be iterable, then supply an __iter__ method. If that method needs to be retargeted dynamically, then take advantage of the guarantee that iter(o) will always find a defined __iter__ method. Perhaps, define __iter__ as lambda obj: obj(obj.__getattr__(obj, '__iter__')) or somesuch. IOW, to guarantee that iter() performs an __iter__ lookup, fill the slot with something that does that lookup. Raymond Hettinger E = mc**2 # Einstein E = IR # Ohm's law therefore IR = mc**2 # Raymond's grand unified theory From bedouglas at earthlink.net Fri Apr 22 20:33:36 2005 From: bedouglas at earthlink.net (bruce) Date: Fri, 22 Apr 2005 17:33:36 -0700 Subject: internet explorer/firefox plugin/toolbar Message-ID: <008201c5479c$18222b90$0301a8c0@Mesa.com> hi... this probably isn't the correct mailing list, but we're giving it a shot!! does anyone have any ideas as to how to go about creating a plugin/toolbar for both/either the IE/Firefox browsers? We're curious as to how to do this, and what languages/technologies you'd use to do this.. could it be done in python??? searching google didn't really turn up anything for the IE side of things... any comments/assistance/etc would be useful... thanks bruce bedouglas at earthlink.net From __peter__ at web.de Sun Apr 3 03:54:47 2005 From: __peter__ at web.de (Peter Otten) Date: Sun, 03 Apr 2005 09:54:47 +0200 Subject: StopIteration in the if clause of a generator expression References: <424db34c.51543105@news.oz.net> Message-ID: Raymond Hettinger wrote: (quoting Bengt) >> I assumed that all standard sequence consumers (including list, of >> course) would intercept the StopIteration of a sequence given them in the >> form of a generator expression, so your lyst example would have an >> analogue for other sequence consumers as well, right? >> I.e., there's not a hidden list(genex) in those others I would hope ;-) > > Right. I see I followed the historical evolvement and saw generator expressions as a lazy listcomp rather than a cool new way to write a generator. That turned out to be the road to confusion. Thanks Carl, thanks Raymond for setting me straight. > I would call it an unfortunate assymmetry -- one the never comes up unless > you're up to no good ;-) Do you see any chance that list comprehensions will be redefined as an alternative spelling for list()? Peter From zanesdad at bellsouth.net Thu Apr 14 16:41:45 2005 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Thu, 14 Apr 2005 16:41:45 -0400 Subject: SimpleXMLRPCServer - disable output In-Reply-To: <1113509250.602995.25500@o13g2000cwo.googlegroups.com> References: <1113509250.602995.25500@o13g2000cwo.googlegroups.com> Message-ID: <425ED589.7090209@bellsouth.net> codecraig wrote: >Hi, > I thought I posted this, but its been about 10min and hasnt shown up >on the group. > Basically I created a SimpleXMLRPCServer and when one of its methods >gets called and it returns a response to the client, the server prints >some info out to the console, such as, > >localhost - - [14/Apr/2005 16:06:28] "POST /RPC2 HTTP/1.0" 200 - > >Anyhow, is there a way I can surpress that so its not printed to the >console? I looked at SimpleXMLRPCServer.py ...it doesn't explicitly >print that, I think perhaps std is...but not sure. Any ideas?? > >thanks. > > > Here's the entire SimpleMLRPCServer class from SimpleXMLRPCServer.py: class SimpleXMLRPCServer(SocketServer.TCPServer, SimpleXMLRPCDispatcher): """Simple XML-RPC server. Simple XML-RPC server that allows functions and a single instance to be installed to handle requests. The default implementation attempts to dispatch XML-RPC calls to the functions or instance installed in the server. Override the _dispatch method inhereted from SimpleXMLRPCDispatcher to change this behavior. """ def __init__(self, addr, requestHandler=SimpleXMLRPCRequestHandler, logRequests=1): self.logRequests = logRequests SimpleXMLRPCDispatcher.__init__(self) SocketServer.TCPServer.__init__(self, addr, requestHandler) You should be able to change logRequests to 0 and that should fix it. I just tested it at a prompt and it worked just fine. Jeremy Jones From steve at holdenweb.com Tue Apr 12 03:31:00 2005 From: steve at holdenweb.com (Steve Holden) Date: Tue, 12 Apr 2005 03:31:00 -0400 Subject: web authoring tools In-Reply-To: References: Message-ID: Brandon J. Van Every wrote: > =?iso-8859-15?Q?Pierre-Fr=E9d=E9ric_Caillaud?= wrote in > news:op.so2yz4blqfv3if at localhost: > > >>>>>Ideally, I would like an open source website + html design tool >>>>>implemented in Python >>>> >>>>didn't you just say that ideally, you wanted a tool written in lisp >>>>or scheme? >>> >>>I honestly got a little tired of the tone of the answers I was >>>getting from that crowd, about what an idiot I am. My query there is >>>still >> >> You mean you are interested in a web application programming >> framework in >>the spirit of Seaside, or in a HTML/CSS editor in the spirit of >>Dreamweaver ? > > > I believe Dreamweaver-esque. I see myself writing articles and eventually > doing snazzy eye candy layouts. I do not see myself engaging in elaborate > flow control or anything terribly programmatic. I want to concentrate on > the content, not the mechanism. > > I've stayed out of this one so far because of a natural disinclination to join religious discussions, but sine we are now talking good common sense I'd like to ask whether a *batch-oriented* system for folding database content into a static web site with common look-and-feel would be of interest. Now PyCon is over I've been able to blog about the techniques used to generate the web site at http://www.holdenweb.com/, and most recently about using reStructured Text in the database to ease authorship problems for the less-taxing content. See http://www.holdenweb.com/blogs/2005/04/versioned-reviews-implemented-post.html to determine whether the overall approach would work for you. regards Steve -- Steve Holden +1 703 861 4237 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ From cweimann at k12hq.com Mon Apr 4 17:47:43 2005 From: cweimann at k12hq.com (Christopher Weimann) Date: Mon, 4 Apr 2005 17:47:43 -0400 Subject: re module non-greedy matches broken In-Reply-To: <1152q99c7pjjl04@corp.supernews.com> References: <1152q99c7pjjl04@corp.supernews.com> Message-ID: <20050404214743.GF82152@tektite.k12usa.internal> On 04/04/2005-04:20PM, lothar wrote: > > how then, do i specify a non-greedy regex > <1st-pat>*? > > that is, such that non-greedy part *? > excludes a match of <1st-pat> > jet% cat vwre2.py #! /usr/bin/env python import re vwre = re.compile("V[^V]W") vwlre = re.compile("V[^V]WL") if __name__ == "__main__": newdoc = "V1WVVV2WWW" vwli = re.findall(vwre, newdoc) print "vwli[], expect", ['V1W', 'V2W'] print "vwli[], return", vwli newdoc = "V1WLV2WV3WV4WLV5WV6WL" vwlli = re.findall(vwlre, newdoc) print "vwlli[], expect", ['V1WL', 'V4WL', 'V6WL'] print "vwlli[], return", vwlli jet% ./vwre2.py vwli[], expect ['V1W', 'V2W'] vwli[], return ['V1W', 'V2W'] vwlli[], expect ['V1WL', 'V4WL', 'V6WL'] vwlli[], return ['V1WL', 'V4WL', 'V6WL'] From jstroud at mbi.ucla.edu Sun Apr 24 13:26:42 2005 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 24 Apr 2005 10:26:42 -0700 Subject: Rudeness on this list [Re: rudeness was: Python licence again] In-Reply-To: <20050424135926.GA24384@phenix.progiciels-bpi.ca> References: <20050424135926.GA24384@phenix.progiciels-bpi.ca> Message-ID: <200504241026.42684.jstroud@mbi.ucla.edu> On Sunday 24 April 2005 06:59 am, so sayeth Fran?ois Pinard: > As seen from here, the Python mailing list quality has been degrading > significantly for the last half-year or so. That's funny. That's exactly as long as I've been on this list. I wonder if the correlation is causal? -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From roy at panix.com Mon Apr 4 10:21:03 2005 From: roy at panix.com (Roy Smith) Date: 4 Apr 2005 10:21:03 -0400 Subject: unittest vs py.test? References: <6I-dnbpiIZJNJNPfRVn-hA@powergate.ca> <6oQ3e.10378$db.6219@trndny07> Message-ID: Peter Hansen wrote: >It seems possible to me that I might have helped him >solely by pointing out that unittest might not be so >"heavy" as some people claimed. I got the impression >that he might be swayed by some unfounded claims not >even to look further at unittest, which I felt would >be a bad thing. I'm the "him" referred to above. I've been using unittest ever since it was first added to the standard library (actually, now that I think about it, I believe I may have been using it even before then). And yes, I think unittest brings along a certain amount of baggage. There is something attractive about having the same basic framework work in many languages (PyUnit, JUnit, C++Unit, etc), but on the other hand, it does add ballast. I use it, I certainly don't hate it, but on the other hand, there are enough things annoying about it that it's worth investing the effort to explore alternatives. >From the few days I've been playing with py.test, I think I like what I see, but it's got other issues. The "optimization elides assert" issue we've been talking about is one. It's also neat that I can write unittest-style test classes or go the simplier route of just writing static test functions, but there's a certain amount of TIMTOWTDI (did I spell that right?) smell to that. I'm also finding the very terse default output from unittest (basicly a bunch of dots followed by "all N tests passed") highly preferable to py.test's verbosity. In short, I haven't made up my mind yet, but I do appreciate the input I've gotten. From radam2 at tampabay.rr.com Tue Apr 5 14:59:32 2005 From: radam2 at tampabay.rr.com (Ron_Adam) Date: Tue, 05 Apr 2005 18:59:32 GMT Subject: Docorator Disected References: <4p9t419ockcg8578g6guse3a14t16orebf@4ax.com> <424f04d0.137947037@news.oz.net> <1112500967.391604.289760@f14g2000cwb.googlegroups.com> <0mqu41pham7n91vb1qgtoe567unn1cffb6@4ax.com> <424f982c.175671582@news.oz.net> <42506757.1010404@v.loewis.de> <4251fba7.328610657@news.oz.net> Message-ID: <0d9551t2ulpdihk2v1vo2dqi53ltoqoitv@4ax.com> On Tue, 05 Apr 2005 06:52:58 GMT, bokr at oz.net (Bengt Richter) wrote: >>Ok, yes, besides the globals, but I figured that part is obvious so I >>didn't feel I needed to mention it. The function call works the same >>even though they are not nested functions. > >I am afraid that is wrong. But be happy, this may be the key to what ISTM >is missing in your concept of python functions ;-) The expression in the form of "function(args)(args)" is the same pattern in two "different" cases, which was all that I was trying to say. Not that the exact process of the two different cases were the same. >So, no, it does not "work the same." In fact, it is a misconception to talk about >a nested fee as if it existed ready to call in the same way as foo. It doesn't >exist that way until the fee def is EXECUTED, producing the callable fee. Ok, I'm going to have to be more careful in how I phrase things I think, I tend to over-genralize a bit. I said they were "the same", but meant similar, a mistake in wording, but not in my understanding. But this is a good point. In my example the calling expression does not yet know who the next tuple of arguments will go to until foo returns it. That part is the same, but as you point out in a nested scope foo defines fee then returns it. And in the non nested example fee is already defined before foo is called. And they must use globals to communicate because they are not share the same name space. They differ because fee is temporary, in the nested version, only existing until the expression foo(arg)(arg) is evaluated. It never gets assigned a name in foo's parent name space. Do I have that correct? >We can use dis to see the above clearly: Love the byte code walk through, Thanks. Is there a resource that goes in depth on python byte code and the compiler? I haven't been able to find much on it on google. > >>> import time > >>> def globalfun(): return '[%s]'%time.ctime() > ... > >>> foo() > > >>> foo()(111, 222) > (111, 222) > >>> foo()(333) > (333, '[Mon Apr 04 22:31:23 2005][Mon Apr 04 22:31:23 2005]') > >>> foo()(333) > (333, '[Mon Apr 04 22:31:37 2005][Mon Apr 04 22:31:37 2005]') I like your idea of using time stamps to trace code! :) >[...] >>Today I believe I have the correct view as I've said this morning. I >>could be wrong yet again. I hope not though I might have to give up >>programming. :/ >Don't give up. It would be boring if it were all instantly clear. >The view is better after an enjoyable hike, and some of the flowers >along the way may turn out prettier than whatever the vista at the >top may be ;-) I won't give up, at most I would take a break, but I love programming too much to give it up. ;-) >Maybe the above will help make functions and decorators a little easier >to understand. I understand functions, sometimes it's difficult to describe just what it is I don't understand yet, and sometimes I fool myself by jumping to an invalid conclusion a little too quickly. But I do this for enjoyment and learning, so I'm not constrained by the need to not make mistakes, (those are just part of learning in my oppinion), as I would if my job depended on it. However it's a little frustrating when my inability to write well, gets in the way of expressing myself accurately. But a few questions remain... When a @decorator statement is found, How does the compiler handle it? Let me see if I can figure this out...using dis. :) >>> from dis import dis >>> def deco1(d1): return d1 >>> def func1(f1): @deco1 def func2(f2): return f2 return func2(f1) >>> func1(2) 2 >>> dis(deco1) 1 0 LOAD_FAST 0 (d1) 3 RETURN_VALUE >>> dis(func1) 2 0 LOAD_GLOBAL 0 (deco1) 3 LOAD_CONST 1 (", line 2>) 6 MAKE_FUNCTION 0 9 CALL_FUNCTION 1 12 STORE_FAST 1 (func2) 5 15 LOAD_FAST 1 (func2) 18 LOAD_FAST 0 (f1) 21 CALL_FUNCTION 1 24 RETURN_VALUE I'm not sure how to interpret this... Line 5 and below is the return expression. The part above it is the part I'm not sure about. Is the first CALL_FUNCTION calling deco1 with the result of the defined functions reference, as it's argument? Then storing the result of deco1 with the name func2? If so the precompiler/parser is replacing the @deco1 with a call to the deco1 function like this. deco1( (def func2(f2):return f2) ) But this causes an illegal syntax error on the def statement. So you can't do it directly. Or is there yet another way to view this? :) Cheers, Ron From srijit at yahoo.com Sat Apr 2 11:13:09 2005 From: srijit at yahoo.com (Srijit Kumar Bhadra) Date: 2 Apr 2005 08:13:09 -0800 Subject: Example Code : Shared Memory with Mutex (pywin32 and ctypes) Message-ID: <1112458389.683375.274990@g14g2000cwa.googlegroups.com> Hello, Here is some sample code with pywin32 build 203 and ctypes 0.9.6. Best regards, /Srijit File: SharedMemCreate_Mutex_win32all.py # This application should be used with SharedMemAccess_Mutex_ctypes.py or SharedMemAccess_Mutex_win32all.py #~ a) Creates a shared memory #~ b) Creates or Opens a mutex #~ c) Reads the contents (null terminated string) of shared memory #~ d) Acquires a mutex and then writes a null terminated string to the shared memory #~ e) Sleeps upto 2 seconds. Sleep time is generated by a random number #~ f) Repeats steps (c), (d) and (e) indefintely import mmap, random, time import win32event, pywintypes, win32api def main(): SHMEMSIZE = 256 ERROR_ALREADY_EXISTS = 183 szName = "MyFileMappingObject" szMsg1 = "Message from first process using win32all and mmap - " szMutex = "MyMutexObject" shmem = mmap.mmap(0, SHMEMSIZE, szName, mmap.ACCESS_WRITE) try: hMutex = win32event.CreateMutex(None, pywintypes.FALSE, szMutex) if (win32api.GetLastError() == ERROR_ALREADY_EXISTS): print"Opened existing mutex object", szMutex else: print "Created new mutex" i=0 random.seed() while 1: szMsg1 = szMsg1 + hex(i) + "\0" if (len(szMsg1) > SHMEMSIZE): print "Current size of string message is", len(szMsg1), "and greater than", SHMEMSIZE break shmem_read = shmem.read(SHMEMSIZE) shmem_read = shmem_read.rstrip(chr(0)) shmem_read = shmem_read.rstrip(" ") print "RECEIVED from SECOND Process: ", shmem_read shmem.seek(0) wait_result = win32event.WaitForSingleObject(hMutex, 1000) if (wait_result == win32event.WAIT_OBJECT_0): shmem.write(szMsg1) while (shmem.tell() != SHMEMSIZE): shmem.write_byte(" ") shmem.seek(0) print "WROTE in FIRST process: ", szMsg1 win32event.ReleaseMutex(hMutex) elif(wait_result == win32event.WAIT_TIMEOUT): print "COULD NOT ACQUIRE MUTEX. TIMEOUT OCCURED" elif (wait_result == win32event.WAIT_ABONDONED): print "WAIT ABANDONED" i = i + 1 szMsg1 = "Message from first process using win32all and mmap - " time.sleep(random.random()*2) except pywintypes.error, (errno, object, strerror): print "Error in", object, ":", strerror if __name__ == "__main__": main() File: SharedMemCreate_Mutex_ctypes.py # This application should be used with SharedMemAccess_Mutex_ctypes.py or SharedMemAccess_Mutex_win32all.py #~ a) Creates a shared memory #~ b) Creates or Opens a mutex #~ c) Reads the contents (null terminated string) of shared memory #~ d) Acquires a mutex and then writes a null terminated string to the shared memory #~ e) Sleeps upto 2 seconds. Sleep time is generated by a random number #~ f) Repeats steps (c), (d) and (e) indefintely # There are two options to implement this code - Option A or Option B. If Option B(A) is chosen then # Option A(B) should be commented. import random, time from ctypes import * def main(): try: SHMEMSIZE = 256 TRUE = 1 FALSE = 0 ERROR_ALREADY_EXISTS = 183 FILE_MAP_ALL_ACCESS = 0xF001F WAIT_OBJECT_0 = 0 WAIT_TIMEOUT = 0x102 WAIT_ABANDONED = 0x80 PAGE_READWRITE = 0x04 INVALID_HANDLE_VALUE = 0xFFFFFFFF szName = "MyFileMappingObject" szMsg1 = "Message from first process using ctypes - " szMutex = "MyMutexObject" hMutex = windll.kernel32.CreateMutexA(None, FALSE, szMutex) if (hMutex == 0): raise WinError() elif (windll.kernel32.GetLastError() == ERROR_ALREADY_EXISTS): print"Opened existing mutex object", szMutex else: print "Created new mutex" hMap = windll.kernel32.CreateFileMappingA(INVALID_HANDLE_VALUE, None, PAGE_READWRITE, 0, SHMEMSIZE, szName) if (hMap == 0): print "Could not open file mapping object" raise WinError() MapViewOfFile = windll.kernel32.MapViewOfFile MapViewOfFile.restype = POINTER(c_char) # Option A pBuf = MapViewOfFile(hMap, FILE_MAP_ALL_ACCESS, 0, 0, 0) if (pBuf == 0): raise WinError() i=0 random.seed() while 1: szMsg1 = szMsg1 + hex(i) + "\0" pBuf_str = cast(pBuf, c_char_p) # Option A if (len(szMsg1) > SHMEMSIZE): print "Current size of string message is", len(szMsg1), "and greater than", SHMEMSIZE break print "RECEIVED from SECOND Process: ", pBuf_str.value # Option A #~ print "RECEIVED from SECOND Process: ", string_at(pBuf) # Option B wait_result = windll.kernel32.WaitForSingleObject(hMutex, 1000) if (wait_result == WAIT_OBJECT_0): memset(pBuf, ord(" "), SHMEMSIZE) cdll.msvcrt.strcpy(pBuf_str, szMsg1) # Option A #~ cdll.msvcrt.strcpy(pBuf, szMsg1) # Option B print "WROTE in FIRST process: ", szMsg1 release_mutex = windll.kernel32.ReleaseMutex(hMutex) if (release_mutex == 0): print "CANNOT RELEASE ACQUIRED MUTEX" elif(wait_result == WAIT_TIMEOUT): print "COULD NOT ACQUIRE MUTEX. TIMEOUT OCCURED" elif (wait_result == WAIT_ABONDONED): print "WAIT ABANDONED" i = i + 1 szMsg1 = "Message from first process using ctypes - " time.sleep(random.random()*2) windll.kernel32.UnmapViewOfFile(pBuf) windll.kernel32.CloseHandle(hMap) return except WindowsError, (strerror): print strerror if (pBuf != 0): windll.kernel32.UnmapViewOfFile(pBuf) if (hMap != 0): windll.kernel32.CloseHandle(hMap) return if __name__ == "__main__": main() File : SharedMemAccess_Mutex_win32all.py # This application should be used with SharedMemCreate_Mutex_ctypes.py or SharedMemCreate_Mutex_win32all.py #~ a) Opens an existing shared memory #~ b) Opens an existing mutex #~ c) Reads the contents (null terminated string) of shared memory #~ d) Acquires a mutex and then writes a null terminated string to the shared memory #~ e) Sleeps upto 2 seconds. Sleep time is generated by a random number #~ f) Repeats steps (c), (d) and (e) indefintely import mmap, random, time import win32event, pywintypes def main(): SHMEMSIZE = 256 STANDARD_RIGHTS_REQUIRED = 0xF0000 SYNCHRONIZE = 0x100000 MUTANT_QUERY_STATE = 0x1 MUTEX_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | MUTANT_QUERY_STATE szName = "MyFileMappingObject" szMsg1 = "Message from second process using win32all and mmap - " szMutex = "MyMutexObject" shmem = mmap.mmap(0, SHMEMSIZE, szName, mmap.ACCESS_WRITE) try: hMutex = win32event.OpenMutex(MUTEX_ALL_ACCESS, pywintypes.FALSE, szMutex) print"Opened existing mutex object", szMutex i = 0; random.seed() while 1: szMsg1 = szMsg1 + hex(i) + "\0" if (len(szMsg1) > SHMEMSIZE): print "Current size of string message is", len(szMsg1), "and greater than", SHMEMSIZE break shmem_read = shmem.read(SHMEMSIZE) shmem_read = shmem_read.rstrip(chr(0)) shmem_read = shmem_read.rstrip(" ") print "RECEIVED from FIRST Process: ", shmem_read shmem.seek(0) wait_result = win32event.WaitForSingleObject(hMutex, 1000) if (wait_result == win32event.WAIT_OBJECT_0): shmem.write(szMsg1) while (shmem.tell() != SHMEMSIZE): shmem.write_byte(" ") shmem.seek(0) print "WROTE in SECOND process: ", szMsg1 win32event.ReleaseMutex(hMutex) elif(wait_result == win32event.WAIT_TIMEOUT): print "COULD NOT ACQUIRE MUTEX. TIMEOUT OCCURED" elif (wait_result == win32event.WAIT_ABONDONED): print "WAIT ABANDONED" i = i + 1 szMsg1 = "Message from second process using win32all and mmap - " time.sleep(random.random()*2) except pywintypes.error, (errno, object, strerror): print "Error in", object, ":", strerror shmem.close() return if __name__ == "__main__": main() File: SharedMemAccess_Mutex_ctypes.py # This application should be used with SharedMemCreate_Mutex_ctypes.py or SharedMemCreate_Mutex_win32all.py #~ a) Opens an existing shared memory #~ b) Opens an existing mutex #~ c) Reads the contents (null terminated string) of shared memory #~ d) Acquires a mutex and then writes a null terminated string to the shared memory #~ e) Sleeps upto 2 seconds. Sleep time is generated by a random number #~ f) Repeats steps (c), (d) and (e) indefintely # There are two options to implement this code - Option A or Option B. If Option B(A) is chosen then # Option A(B) should be commented. import random, time from ctypes import * def main(): SHMEMSIZE = 256 FILE_MAP_ALL_ACCESS = 0xF001F STANDARD_RIGHTS_REQUIRED = 0xF0000 SYNCHRONIZE = 0x100000 MUTANT_QUERY_STATE = 0x1 MUTEX_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | MUTANT_QUERY_STATE WAIT_OBJECT_0 = 0 WAIT_TIMEOUT = 0x102 WAIT_ABANDONED = 0x80 TRUE = 1 FALSE = 0 szName = "MyFileMappingObject" szMsg1 = "Message from second process using ctypes - " szMutex = "MyMutexObject" hMap = 0 pBuf = 0 hMutex = 0 try: hMap = windll.kernel32.OpenFileMappingA(FILE_MAP_ALL_ACCESS, FALSE, szName) if (hMap == 0): raise WinError() MapViewOfFile = windll.kernel32.MapViewOfFile MapViewOfFile.restype = POINTER(c_char) # Option A pBuf = MapViewOfFile(hMap, FILE_MAP_ALL_ACCESS, 0, 0, 0) if (pBuf == 0): raise WinError() hMutex = windll.kernel32.OpenMutexA(MUTEX_ALL_ACCESS, FALSE, szMutex) if (hMutex == 0): raise WinError() else: print"Opened existing mutex object", szMutex i=0 random.seed() while 1: szMsg1 = szMsg1 + hex(i) + "\0" pBuf_str = cast(pBuf, c_char_p) # Option A if (len(szMsg1) > SHMEMSIZE): print "Current size of string message is", len(szMsg1), "and greater than", SHMEMSIZE break print "RECEIVED from FIRST Process: ", pBuf_str.value # Option A #~ print "RECEIVED from FIRST Process: ", string_at(pBuf) # Option B wait_result = windll.kernel32.WaitForSingleObject(hMutex, 1000) if (wait_result == WAIT_OBJECT_0): memset(pBuf, ord(" "), SHMEMSIZE) cdll.msvcrt.strcpy(pBuf_str, szMsg1) # Option A #~ cdll.msvcrt.strcpy(pBuf, szMsg1) # Option B print "WROTE in SECOND process: ", szMsg1 release_mutex = windll.kernel32.ReleaseMutex(hMutex) if (release_mutex == 0): print "CANNOT RELEASE ACQUIRED MUTEX" elif(wait_result == WAIT_TIMEOUT): print "COULD NOT ACQUIRE MUTEX. TIMEOUT OCCURED" elif (wait_result == WAIT_ABONDONED): print "WAIT ABANDONED" i = i + 1 szMsg1 = "Message from second process using ctypes - " time.sleep(random.random()*2) windll.kernel32.UnmapViewOfFile(pBuf) windll.kernel32.CloseHandle(hMap) return except WindowsError, (strerror): print strerror if (pBuf != 0): windll.kernel32.UnmapViewOfFile(pBuf) if (hMap != 0): windll.kernel32.CloseHandle(hMap) return if __name__ == "__main__": main() From mefjr75 at hotmail.com Sun Apr 17 00:54:29 2005 From: mefjr75 at hotmail.com (M.E.Farmer) Date: 16 Apr 2005 21:54:29 -0700 Subject: whitespace , comment stripper, and EOL converter References: <2ab23d7a.0504120857.14ef094a@posting.google.com> <2ab23d7a.0504130738.622a3605@posting.google.com> <1113410094.102181.315080@l41g2000cwc.googlegroups.com> <1113680973.635576.310510@g14g2000cwa.googlegroups.com> Message-ID: <1113713669.255207.39580@f14g2000cwb.googlegroups.com> Thanks Jean, I have thought about adding docstrings several times, but I was stumped at how to determine a docstring from a regular tripleqoted string ;) I have been thinking hard about the problem and I think I have an idea. If the line has nothing before the start of the string it must be a docstring. Sounds simple enough but in Python there are 12 or so 'types' of strings . Here is my crack at it feel free to improve it ;) I reversed the logic on the comments and docstrings so I could add a special mode to docstring stripping ...pep8 mode . Pep8 mode only strips double triple quotes from your source code leaving the offending single triple quotes behind. Probably just stupid but someone might find it usefull. ###################################################################### # Python source stripper ###################################################################### import os import sys import token import keyword import StringIO import tokenize import traceback __credits__ = ''' J?rgen Hermann M.E.Farmer Jean Brouwers ''' __version__ = '.8' __author__ = 'M.E.Farmer' __date__ = 'Apr 16, 2005,' \ 'Jan 15 2005,' \ 'Oct 24 2004' \ ###################################################################### class Stripper: """Python source stripper """ def __init__(self, raw): self.raw = raw def format(self, out=sys.stdout, comments=0, docstrings=0, spaces=1, untabify=1, eol='unix'): """ strip comments, strip docstrings, strip extra whitespace and lines, convert tabs to spaces, convert EOL's in Python code. """ # Store line offsets in self.lines self.lines = [0, 0] pos = 0 # Strips the first blank line if 1 self.lasttoken = 1 self.temp = StringIO.StringIO() self.spaces = spaces self.comments = comments self.docstrings = docstrings if untabify: self.raw = self.raw.expandtabs() self.raw = self.raw.rstrip()+' ' self.out = out # Have you ever had a multiple line ending script? # They can be nasty so lets get them all the same. self.raw = self.raw.replace('\r\n', '\n') self.raw = self.raw.replace('\r', '\n') self.lineend = '\n' # Gather lines while 1: pos = self.raw.find(self.lineend, pos) + 1 if not pos: break self.lines.append(pos) self.lines.append(len(self.raw)) self.pos = 0 # Wrap text in a filelike object text = StringIO.StringIO(self.raw) # Parse the source. ## Tokenize calls the __call__ ## method for each token till done. try: tokenize.tokenize(text.readline, self) except tokenize.TokenError, ex: traceback.print_exc() # Ok now we write it to a file # but we also need to clean the whitespace # between the lines and at the ends. self.temp.seek(0) # All this should be written into the # __call__ method just haven't yet... # Mac CR if eol == 'mac': self.lineend = '\r' # Windows CR LF elif eol == 'win': self.lineend = '\r\n' # Unix LF else: self.lineend = '\n' for line in self.temp.readlines(): if spaces == -1: self.out.write(line.rstrip()+self.lineend) else: if not line.isspace(): self.lasttoken=0 self.out.write(line.rstrip()+self.lineend) else: self.lasttoken+=1 if self.lasttoken<=self.spaces and self.spaces: self.out.write(self.lineend) def __call__(self, toktype, toktext, (srow,scol), (erow,ecol), line): """ Token handler. """ # calculate new positions oldpos = self.pos newpos = self.lines[srow] + scol self.pos = newpos + len(toktext) # kill comments if self.comments: if toktype == tokenize.COMMENT: return # kill doc strings if self.docstrings: # Assume if there is nothing on the # left side it must be a docstring if toktype == tokenize.STRING and \ line.lstrip(' rRuU')[0] in ["'",'"']: t = toktext.lstrip('rRuU') if (t.startswith('"""') and (self.docstrings == 'pep8' or self.docstrings =='8')): return elif t.startswith('"""') or t.startswith("'''"): return # handle newlines if toktype in [token.NEWLINE, tokenize.NL]: self.temp.write(self.lineend) return # send the original whitespace if newpos > oldpos: self.temp.write(self.raw[oldpos:newpos]) # skip indenting tokens if toktype in [token.INDENT, token.DEDENT]: self.pos = newpos return # send text to the temp file self.temp.write(toktext) return ###################################################################### def Main(): import sys if sys.argv[1]: filein = open(sys.argv[1]).read() Stripper(filein).format(out=sys.stdout, comments=0, docstrings=1, untabify=1, eol='win') ###################################################################### if __name__ == '__main__': Main() From jfouhy at paradise.net.nz Tue Apr 26 18:59:18 2005 From: jfouhy at paradise.net.nz (jfouhy at paradise.net.nz) Date: 26 Apr 2005 15:59:18 -0700 Subject: goto statement References: <20050420092359.81900.qmail@web8409.mail.in.yahoo.com> <42664190.6010507@i.com.ua> <87vf6hlkix.fsf@wilson.rwth-aachen.de> Message-ID: <1114556358.676481.16500@o13g2000cwo.googlegroups.com> Maxim Kasimov wrote: > > Maxim Kasimov writes: > >>WOW, just greate! ... but i'd like to relax at some more > >>interesting way than to comment each of rows > but what if i just can't to do this becouse i'm working thrue ssh, and have to > use only installed editors (such as vi) A slightly less arcane way of commenting out multiple lines in vi: To comment out the current line, and the next 5: :,+5s/^/#/ explanation: :x,y -- specifies a line range. If x is omitted, start with the current line. If y is +z, interpret it as z lines below the current line. ^ -- regular expression matching the start of the line. s/foo/bar/ -- replace foo with bar. so s/^/#/ replaces the start of the line with the # character. You can undo this with :,+5s/^#// which replaces a # at the start of the line with the empty string (ie: deletes it). HTH. -- John. From seefeld at sympatico.ca Tue Apr 12 17:36:30 2005 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Tue, 12 Apr 2005 17:36:30 -0400 Subject: Missing Module when calling 'Import' _omnipy In-Reply-To: <1113336595.556003.196620@z14g2000cwz.googlegroups.com> References: <1113258389.432002.323790@f14g2000cwb.googlegroups.com> <425AC803.70704@sympatico.ca> <1113336595.556003.196620@z14g2000cwz.googlegroups.com> Message-ID: <2J_6e.3363$MZ2.588132@news20.bellglobal.com> gerald.maher at waytohere.com wrote: > I found the fike _omnipy.pyd is that what you mean? yep. > Here is my Lib Path: [...] As a first step you may consider adding the directory containing '_omnipy.pyd' to your PYTHONPATH variable. Second, you may read any documentation you can find at http://omniorb.sourceforge.net/, and finally ask any unanswered question on the omniORB ML. Sorry, it has been a long while since I last used omniORB. Regards, Stefan From enjoy_linux at hotmail.com Thu Apr 14 02:03:00 2005 From: enjoy_linux at hotmail.com (MaHahaXixi) Date: Thu, 14 Apr 2005 14:03:00 +0800 Subject: how to explain such codes, python's bug or mine? References: Message-ID: yes. i understand now. but i use another trick. list is in vary size, so i do not wanna copy it. "Jim" wrote in message news:d3irjm$msg$1 at scotsman.ed.ac.uk... > MaHahaXixi wrote: > >>>>j = range(20) > >>>>print j > > > > [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] > > > >>>>for k in j: > > > > if k <= 10: > > j.remove(k) > > > > > > > >>>>print j > > > > [1, 3, 5, 7, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19] > > > > > > > > Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on > > win32 > > Type "copyright", "credits" or "license()" for more information. > > > > i think python do convert there codes to such style: > > for (i = 0; i < len(j); i++) > > k = j[i] > > ...... > > > what do u think? > > > > > > I'm not quite sure of your question but with the second style you're not > attempting to change the original list but make a copy. That's perfectly > easy to do in Python as it is. The exampmle is a cautionary one about > changing the list on which you are iterating. > > Jim From tzot at sil-tec.gr Tue Apr 26 04:58:29 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 26 Apr 2005 11:58:29 +0300 Subject: Python, Perl & PDF files References: Message-ID: <2d0s61pt0i1isc2sh42sii894hu2u57gv7@4ax.com> On Mon, 25 Apr 2005 13:00:51 -0400, rumours say that Peter Hansen might have written: >Peter Hansen wrote: >> Dennis Lee Bieber wrote: >>> On Mon, 25 Apr 2005 17:24:36 +0300, Christos "TZOTZIOY" Georgiou: >>>> I don't know any related myth of anglo-saxon origin to quote. >>> The most commonly known phrasing would likely be "God only helps >>> those who help themselves". >> Google suggests that removing the word "only" produces a >> phrase many times more commonly known... >And very interesting reading (to spawn another diversion >typical to c.l.p), such as the third link in Google >titled "Vessel of Honour: ..." (content available only >via the "Cached" link), which points out that this >biblical-sounding phrase was never in the bible, >but actually comes *from Greek mythology*, and specifically >(it claims) from the same story as Christos has >quoted, except that the "god" in question was Hercules >and other details differ somewhat... It seems that I mixed two myths (I should pay more attention probably to mythology lessons at primary school :). The fable with Hercules is the correct one, as far as a cart and mud is concerned. The one about Athena and arm-motion, is that Aesop's fable: http://www.mythfolklore.net/aesopica/oxford/480.htm Now there's another phrase, "the smart bird gets caught by the beak", and I don't know if I'm a smart bird, but my nose is big... -- TZOTZIOY, I speak England very best. "Be strict when sending and tolerant when receiving." (from RFC1958) I really should keep that in mind when talking with people, actually... From prasad413in at gmail.com Wed Apr 20 02:35:06 2005 From: prasad413in at gmail.com (hue) Date: 19 Apr 2005 23:35:06 -0700 Subject: New to Tkinter... In-Reply-To: References: Message-ID: <1113978906.823983.323410@f14g2000cwb.googlegroups.com> Hello From skip at pobox.com Tue Apr 12 23:15:03 2005 From: skip at pobox.com (Skip Montanaro) Date: Tue, 12 Apr 2005 22:15:03 -0500 Subject: permission In-Reply-To: <425c8b44$1@dnews.tpgi.com.au> References: <425c8b44$1@dnews.tpgi.com.au> Message-ID: <16988.36535.646396.892426@montanaro.dyndns.org> James> Is it possible to check if you have permission to access and or James> change a directory or file? Yes, but it's generally much easier to try, then recover from any errors: try: f = open(somefile, "a") except IOError, msg: print "can't open", somefile, "for writing" else: f.write("hi mom!\n") Skip From cam.ac.uk at mh391.invalid Thu Apr 28 14:45:21 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Thu, 28 Apr 2005 19:45:21 +0100 Subject: anonymous functions/expressions without lambda? In-Reply-To: References: Message-ID: Dave Benjamin wrote: > I think you meant to write something like this: > > def attrsetter(obj, name, value): > def _return_func(): > return setattr(obj, name, value) > return _return_func Sure did. Sorry. -- Michael Hoffman From rkern at ucsd.edu Sat Apr 23 22:41:59 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sat, 23 Apr 2005 19:41:59 -0700 Subject: Variables In-Reply-To: <426B0283.40602@cloudthunder.com> References: <426B0283.40602@cloudthunder.com> Message-ID: Richard Blackwood wrote: > To All: > > Folks, I need your help. I have a friend who claims that if I write: > > foo = 5 > > then foo is NOT a variable, necessarily. If you guys can define for me > what a variable is and what qualifications you have to back you, I can > pass this along to, hopefully, convince him that foo is indeed a variable. None of us can do that unless you tell us what he thinks the word "variable" means. The terminology is a bit fluid. I suspect that your friend applying a somewhat restricted notion of "variable" that coincides with the behavior of variables in some other language. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From onurb at xiludom.gro Wed Apr 6 13:19:54 2005 From: onurb at xiludom.gro (bruno modulix) Date: Wed, 06 Apr 2005 19:19:54 +0200 Subject: boring the reader to death (wasRe: Lambda: the Ultimate Design Flaw In-Reply-To: References: Message-ID: <42541a3c$0$12176$626a14ce@news.free.fr> Sunnan wrote: > Aahz wrote: > (snip) >> print "foo is", foo > > > Is the space added automatically? (Like awk does, if you add a comma.) Yes. But you can also format it how you like: print "foo is %s and that's a good news, my friends" % foo -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From tzot at sil-tec.gr Tue Apr 26 05:10:45 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 26 Apr 2005 12:10:45 +0300 Subject: Python, Perl & PDF files References: <2d0s61pt0i1isc2sh42sii894hu2u57gv7@4ax.com> Message-ID: <181s61l6hoatlsre5dpha9no6pieblbhos@4ax.com> On Tue, 26 Apr 2005 11:58:29 +0300, rumours say that Christos "TZOTZIOY" Georgiou might have written: >http://www.mythfolklore.net/aesopica/oxford/480.htm BTW, does anyone see the connection between: > we should make every possible effort on our own behalf > and only then ask for divine assistance and proper netiquette?-) http://www.catb.org/~esr/faqs/smart-questions.html -- TZOTZIOY, I speak England very best. "Be strict when sending and tolerant when receiving." (from RFC1958) I really should keep that in mind when talking with people, actually... From kbk at shore.net Mon Apr 25 23:56:11 2005 From: kbk at shore.net (Kurt B. Kaiser) Date: Mon, 25 Apr 2005 23:56:11 -0400 (EDT) Subject: Weekly Python Patch/Bug Summary Message-ID: <200504260356.j3Q3uBNw020893@bayview.thirdcreek.com> Patch / Bug Summary ___________________ Patches : 316 open ( +2) / 2831 closed ( +7) / 3147 total ( +9) Bugs : 908 open (+10) / 4941 closed (+20) / 5849 total (+30) RFE : 178 open ( +1) / 153 closed ( +2) / 331 total ( +3) New / Reopened Patches ______________________ package_data chops off first char of default package (2005-04-15) http://python.org/sf/1183712 opened by Wummel [ast] fix for 1183468: return/yield in class (2005-04-16) http://python.org/sf/1184418 opened by logistix urllib2 dloads failing through HTTP proxy w/ auth (2005-04-18) http://python.org/sf/1185444 opened by Mike Fleetwood binascii.b2a_qp does not handle binary data correctly (2005-04-18) http://python.org/sf/1185447 opened by Eric Huss Automatically build fpectl module from setup.py (2005-04-18) http://python.org/sf/1185529 opened by Jeff Epler Typo in Curses-Function doc (2005-04-20) http://python.org/sf/1186781 opened by grzankam subprocess: optional auto-reaping fixing os.wait() lossage (2005-04-21) http://python.org/sf/1187312 opened by Mattias Engdeg?rd Add const specifier to PySpam_System prototype (2005-04-21) http://python.org/sf/1187396 opened by Luis Bruno Don't assume all exceptions are SyntaxError's (2005-04-25) http://python.org/sf/1189210 opened by John Ehresman Patches Closed ______________ fix typos in Library Reference (2005-04-10) http://python.org/sf/1180062 closed by doerwalter [AST] Fix for core in test_grammar.py (2005-04-08) http://python.org/sf/1179513 closed by nascheme Implemented new 'class foo():pass' syntax (2005-04-03) http://python.org/sf/1176019 closed by nascheme range() in for loops, again (2005-04-12) http://python.org/sf/1181334 closed by arigo Info Associated with Merge to AST (2005-01-07) http://python.org/sf/1097671 closed by kbk New / Reopened Bugs ___________________ Minor error in tutorial (2005-04-14) CLOSED http://python.org/sf/1183274 opened by Konrads Smelkovs check for return/yield outside function is wrong (2005-04-15) http://python.org/sf/1183468 opened by Neil Schemenauer try to open /dev/null as directory (2005-04-15) http://python.org/sf/1183585 opened by Roberto A. Foglietta PyDict_Copy() can return non-NULL value on error (2005-04-15) CLOSED http://python.org/sf/1183742 opened by Phil Thompson Popen4 wait() fails sporadically with threads (2005-04-15) http://python.org/sf/1183780 opened by Taale Skogan return val in __init__ doesn't raise TypeError in new-style (2005-04-15) CLOSED http://python.org/sf/1183959 opened by Adal Chiriliuc dest parameter in optparse (2005-04-15) http://python.org/sf/1183972 opened by ahmado Missing trailing newline with comment raises SyntaxError (2005-04-15) http://python.org/sf/1184112 opened by Eric Huss example broken in section 1.12 of Extending & Embedding (2005-04-16) http://python.org/sf/1184380 opened by bamoore Read-only property attributes raise wrong exception (2005-04-16) CLOSED http://python.org/sf/1184449 opened by Barry A. Warsaw itertools.imerge: merge sequences (2005-04-18) CLOSED http://python.org/sf/1185121 opened by Jurjen N.E. Bos pydoc doesn't find all module doc strings (2005-04-18) http://python.org/sf/1185124 opened by Kent Johnson PyObject_Realloc bug in obmalloc.c (2005-04-19) http://python.org/sf/1185883 opened by Kristj?n Valur python socketmodule dies on ^c (2005-04-19) CLOSED http://python.org/sf/1185931 opened by nodata tempnam doc doesn't include link to tmpfile (2005-04-19) http://python.org/sf/1186072 opened by Ian Bicking [AST] genexps get scoping wrong (2005-04-19) http://python.org/sf/1186195 opened by Brett Cannon [AST] assert failure on ``eval("u'\Ufffffffe'")`` (2005-04-19) http://python.org/sf/1186345 opened by Brett Cannon [AST] automatic unpacking of arguments broken (2005-04-19) http://python.org/sf/1186353 opened by Brett Cannon Python Programming FAQ should be updated for Python 2.4 (2005-02-09) CLOSED http://python.org/sf/1119439 reopened by montanaro nntplib shouldn't raise generic EOFError (2005-04-20) http://python.org/sf/1186900 opened by Matt Roper TypeError message on bad iteration is misleading (2005-04-21) http://python.org/sf/1187437 opened by Roy Smith Pickle with HIGHEST_PROTOCOL "ord() expected..." (2005-04-22) CLOSED http://python.org/sf/1188175 opened by Heiko Selber Rebuilding from source on RH9 fails (_tkinter.so missing) (2005-04-22) http://python.org/sf/1188231 opened by Marty Heyman Python 2.4 Not Recognized by Any Programs (2005-04-23) http://python.org/sf/1188637 opened by Yoshi Nagasaki zipfile module and 2G boundary (2005-04-24) http://python.org/sf/1189216 opened by Bob Ippolito Seg Fault when compiling small program (2005-04-24) http://python.org/sf/1189248 opened by Reginald B. Charney LINKCC incorrect (2005-04-25) http://python.org/sf/1189330 opened by Christoph Ludwig LINKCC incorrect (2005-04-25) CLOSED http://python.org/sf/1189337 opened by Christoph Ludwig file.write(x) where len(x) > 64*1024**2 is unreliable (2005-04-25) CLOSED http://python.org/sf/1189525 opened by Martin Gfeller pydoc may hide non-private doc strings. (2005-04-25) http://python.org/sf/1189811 opened by J Livingston "Atuple containing default argument values ..." (2005-04-25) http://python.org/sf/1189819 opened by Chad Whitacre Bugs Closed ___________ Minor error in tutorial (2005-04-14) http://python.org/sf/1183274 closed by doerwalter copy.py bug (2005-02-03) http://python.org/sf/1114776 closed by anthonybaxter re.escape(s) prints wrong for chr(0) (2005-04-13) http://python.org/sf/1182603 closed by nascheme PyDict_Copy() can return non-NULL value on error (2005-04-15) http://python.org/sf/1183742 closed by rhettinger return val in __init__ doesn't raise TypeError in new-style (2005-04-15) http://python.org/sf/1183959 closed by rhettinger dir() does not include _ (2005-04-13) http://python.org/sf/1182614 closed by nickjacobson Read-only property attributes raise wrong exception (2005-04-16) http://python.org/sf/1184449 closed by bwarsaw Readline segfault (2005-04-05) http://python.org/sf/1176893 closed by mwh python socketmodule dies on ^c (2005-04-19) http://python.org/sf/1185931 closed by nodata101 Bad sys.executable value for bdist_wininst install script (2005-04-12) http://python.org/sf/1181619 closed by theller StringIO and cStringIO don't provide 'name' attribute (2005-04-03) http://python.org/sf/1175967 closed by mwh Python Interpreter shell is crashed (2005-01-12) http://python.org/sf/1100673 closed by mwh Python Programming FAQ should be updated for Python 2.4 (2005-02-09) http://python.org/sf/1119439 closed by jafo Dictionary Parsing Problem (2005-02-05) http://python.org/sf/1117048 closed by tjreedy 2.4.1 breaks pyTTS (2005-04-07) http://python.org/sf/1178624 closed by doerwalter Pickle with HIGHEST_PROTOCOL "ord() expected..." (2005-04-22) http://python.org/sf/1188175 closed by drhok multiple broken links in profiler docs (2005-03-30) http://python.org/sf/1173773 closed by isandler LINKCC incorrect (2005-04-25) http://python.org/sf/1189337 closed by cludwig file.write(x) where len(x) > 64*1024**2 is unreliable (2005-04-25) http://python.org/sf/1189525 closed by tim_one New / Reopened RFE __________________ "replace" function should accept lists. (2005-04-17) CLOSED http://python.org/sf/1184678 opened by Poromenos Make bisect.* functions accept an optional compare function (2005-04-18) http://python.org/sf/1185383 opened by Marcin Ciura RFE Closed __________ "replace" function should accept lists. (2005-04-17) http://python.org/sf/1184678 closed by rhettinger itertools.imerge: merge sequences (2005-04-18) http://python.org/sf/1185121 closed by jneb From tjreedy at udel.edu Fri Apr 1 18:48:05 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 1 Apr 2005 18:48:05 -0500 Subject: that is it is not it (logic in Python) References: <424d0be1$0$2882$626a14ce@news.free.fr> <424dc4b4$0$18707$636a15ce@news.free.fr> Message-ID: "F. Petitjean" wrote in message news:424dc4b4$0$18707$636a15ce at news.free.fr... Le Fri, 1 Apr 2005 13:39:47 -0500, Terry Reedy a ?crit : >> Reread the ref manual on chained comparison operators. >And see the date of the post :-) Ditto for the reply ;-) TJR From maxm at mxm.dk Fri Apr 8 05:15:38 2005 From: maxm at mxm.dk (Max M) Date: Fri, 08 Apr 2005 11:15:38 +0200 Subject: doubt regarding Conversion of date into timestamp In-Reply-To: References: Message-ID: <42564b6f$0$246$edfadb0f@dread12.news.tele.dk> praba kar wrote: > Dear All, > > I am new to Python I want to know how to > change a time into timestamp Is there any specific reason for not using datetime instead of time ? -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From fredrik at pythonware.com Fri Apr 22 02:21:39 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 22 Apr 2005 08:21:39 +0200 Subject: Manipulating large blobs in Python References: <42686F31.3060101@fourstonesExpressions.com> Message-ID: Tim Stone wrote: > I'm working on a module that will manipulate large blobs. I'm using a C > dll to allocate big blocks of memory, using PyMem_Malloc, which is > working quite well up until I try to manipulate a blob that exhausts > Python's heap. how large is that? > I'm guessing that to increase the heapsize, I'm going to have to recompile > Python... (??) Am I on the right track? no. if PyMem_Malloc fails (i.e. returns NULL), it's the operating system that refuses to give your process more memory. From steven.bethard at gmail.com Sat Apr 2 17:02:28 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 02 Apr 2005 15:02:28 -0700 Subject: Performance issue In-Reply-To: References: Message-ID: Marc 'BlackJack' Rintsch wrote: > def make_anagram_map(words): > anagram_map = dict() > for word in imap(lambda w: w.strip().lower(), words): > sorted_word = ''.join(sorted(list(word))) > anagram_map.setdefault(sorted_word, list()).append(word) > > return dict(ifilter(lambda x: len(x[1]) > 1, anagram_map.iteritems())) Or if you're afraid of map and filter like me, you can try: def make_anagram_map(words): anagram_map = {} for word in (w.strip().lower() for w in words): anagram_map.setdefault(''.join(sorted(word)), []).append(word) return dict(sortedword_wordlist for sortedword_wordlist in anagram_map.iteritems() if len(sortedword_wordlist[1]) > 1) py> make_anagram_map(['owers', 'pest', 'rowse', 'pets', 'sower', 'step']) {'epst': ['pest', 'pets', 'step'], 'eorsw': ['owers', 'rowse', 'sower']} STeVe From peter at engcorp.com Mon Apr 18 10:23:30 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 18 Apr 2005 10:23:30 -0400 Subject: ANN: Python 2.3.2 for PalmOS available In-Reply-To: <1113832747.373571.13220@l41g2000cwc.googlegroups.com> References: <1113608405.558884.235890@f14g2000cwb.googlegroups.com> <1113832747.373571.13220@l41g2000cwc.googlegroups.com> Message-ID: beliavsky at aol.com wrote: > What are the potential applications of Python on PalmOS? Just curious. Python is a general purpose programming language, as you know. Doesn't that suggest that the set of potential applications is pretty much all those which don't require the raw performance of C or perhaps some highly specialized feature available only in another language (if such a thing even exists)? Calendar tools, time tracking tools, games, various kinds of network clients (for the latest Palms), etc. I've just written a very specialized time tracking tool in Plua, which could easily have been done using Python if it had access to the UI elements and the file system as Plua does. Given that you already know what Python is all about, your question sounds to me like that of someone who doesn't even know what a Palm is good for... which I doubt you are, so I find the question rather puzzling. -Peter From ruach at chpc.utah.edu Fri Apr 22 16:46:26 2005 From: ruach at chpc.utah.edu (Matthew Thorley) Date: Fri, 22 Apr 2005 14:46:26 -0600 Subject: handling tar, gz and bz2 with python Message-ID: Is there a module for unpacking tar files in python? how about bzip2 and gzips? I know I can use the gzip module for gzips but is there anything that can detect what format a file is in and decopress and unpack it using the other methods? thanks -Matthew From sunnan at handgranat.org Sun Apr 3 18:38:55 2005 From: sunnan at handgranat.org (Sunnan) Date: Sun, 03 Apr 2005 22:38:55 GMT Subject: Lambda: the Ultimate Design Flaw In-Reply-To: <3b99ncF6fd2apU1@individual.net> References: <87is3663cn.fsf@wilson.rwth-aachen.de> <3b99ncF6fd2apU1@individual.net> Message-ID: <3g_3e.134005$dP1.471451@newsc.telia.net> Artie Gold wrote: > Torsten Bronger wrote: >> The whole text seems to be a variant of >> . >> >> Tsch?, >> Torsten. >> > Ya think? ;-) Heh. I was glad that Torsten pointed it out; I didn't get what was funny about the joke until then. From vze4rx4y at verizon.net Fri Apr 1 11:42:30 2005 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Fri, 01 Apr 2005 16:42:30 GMT Subject: unittest vs py.test? References: <114pqf31isr8k4d@news.supernews.com> Message-ID: [Roy Smith ] > One thing that worries me a little is that all three seem to have > advantages and disadvantages, yet none is so obviously better than the > others that it stands out as the only reasonable way to do it. This means > some groups will adopt one, some will adopt another, and the world will > become fragmented. Worry is a natural thing for someone with "panix" in their email address ;-) FWIW, the evolution of py.test is to also work seemlessly with existing tests from the unittest module. the world diversifies, the world congeals, Raymond Hettinger From timothy at open-networks.net Sun Apr 17 00:02:20 2005 From: timothy at open-networks.net (Timothy Smith) Date: Sun, 17 Apr 2005 14:02:20 +1000 Subject: pysvn install on freebsd Message-ID: <4261DFCC.6010601@open-networks.net> has anyone used or installed this on fbsd the install for it is totally redundant. i get this error for it make -f freebsd.mak clean all test cd ../Source && make -f pysvn_freebsd_py.mak clean make: cannot open pysvn_freebsd_py.mak. *** Error code 2 Stop in /usr/home/timothy/pysvn-1.1.2/Extension/Builder. From cpghost at cordula.ws Wed Apr 13 11:37:34 2005 From: cpghost at cordula.ws (Cordula's Web) Date: 13 Apr 2005 08:37:34 -0700 Subject: for line in file weirdness References: <1113388411.589754.82600@f14g2000cwb.googlegroups.com> <1113393892.784115.79720@o13g2000cwo.googlegroups.com> Message-ID: <1113406654.084550.118410@g14g2000cwa.googlegroups.com> Thanks :) Reading everything into a variable was not an option, due to some very large files. Creating the iterator only once, as Fredrik suggested, solved the problem nicely. Again many thanks for your great support! From carsten at uniqsys.com Mon Apr 4 17:14:21 2005 From: carsten at uniqsys.com (Carsten Haese) Date: Mon, 04 Apr 2005 17:14:21 -0400 Subject: Looking for Stephen Turner, maintainer of informixdb In-Reply-To: <42490c40$0$27184$9b4e6d93@newsread4.arcor-online.net> References: <42490c40$0$27184$9b4e6d93@newsread4.arcor-online.net> Message-ID: <1112649261.15320.13.camel@dot.uniqsys.com> On Tue, 2005-03-29 at 03:05, Michael Husmann wrote: > Carsten Haese wrote: > > > Hello everybody: > > > > I have discovered that the functionality for connecting Python to an > > Informix database is currently in a frustrating state of neglect. The > > link to Kinfxdb is dead, and informixdb doesn't build on Python 2. I > > couldn't find any usable workarounds to the build problem, so I worked > > out successfully how to build informixdb using distutils. > > > > Now I'd like to share the result with the community, but the maintainer > > appears to have gone missing. My emails to sjturner at ix.netcom.com and > > stepturn at mediaone.net have bounced back undeliverable, so now I'm > > posting to the lists trying to locate Stephen. > > > > If anybody has any pointers for locating Stephen Turner, please let me > > know. If Stephen can't be located, I'd be willing to take over the > > project, but I'd prefer the torch be given to me rather than me just > > taking it. > > Carsten, > > haven't heard anything from Stephen either, but there are some extensions to > the informixdb module. I'll send the sources to you next week. So if you > like you can bundle everything in one package. Michael, I'd certainly like to take a look at those extensions. (I tried to respond to you off-list, but my mail bounced back. Is this project cursed or am I? :) I hope you're reading this, Michael.) A week has gone by with no replies as to Stephen's whereabouts, and one reply telling me that I can, in good faith, go ahead and release a fork. Unless somebody tells me I should wait longer, I guess I'll do that. Stay tuned for the announcement on when and where my fork will be available. Best regards, -- Carsten Haese - Software Engineer | Phone: (419) 861-3331 Unique Systems, Inc. | FAX: (419) 861-3340 1446 Reynolds Rd, Suite 313 | Maumee, OH 43537 | mailto:carsten at uniqsys.com From apardon at forel.vub.ac.be Fri Apr 15 03:32:21 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 15 Apr 2005 07:32:21 GMT Subject: A testcase for a Queue like class. Message-ID: I'm writing some sort of replacement for the Queue module. I'm calling the class I'm writing a tube. However I'm stuck in how I should write some testcases. The tube will have an open method, with as argument an access parameter that will determine if the thread wants to put things (write) on the queue or will get (read) things from the queue (or both). Now what I want is that a thread that opens the tube for read access will block until a thread opens the same tube for write access. The problem is how do I put such a requirement in a test case? -- Antoon Pardon From j1k1cki at hotmail.com Mon Apr 11 02:41:31 2005 From: j1k1cki at hotmail.com (j1k1cki at hotmail.com) Date: 10 Apr 2005 23:41:31 -0700 Subject: Cleaning up after C module Message-ID: <1113201691.215996.129930@f14g2000cwb.googlegroups.com> Hello, I have a Python module written in C that spawns and kills processes using OS-specific mechanisms. I want to kill all spawned processes when the interpreter exits. I tried to wrap every spawned process in a Python object like this: import cmodule class Process: __init__(self, execname): self.pid = cmodule.spawn(execname) __del__(self): cmodule.kill(self.pid) p = Process("foo") but this does not work, I am getting and exception inidicating that 'cmodule' is 'None' in '__del__()'. Moreover, the Language Reference states that "It is not guaranteed that __del__() methods are called for objects that still exist when the interpreter exits", so it looks like this approach is wrong anyway. How do I do this right? Thanks very much in advance Grzegorz PS: Python 2.3.3 From deetsNOSPAM at web.de Sun Apr 10 07:57:26 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Sun, 10 Apr 2005 13:57:26 +0200 Subject: workaround for generating gui tools References: <1113061810.530359.172720@g14g2000cwa.googlegroups.com> <3bqgh6F6larilU1@individual.net> Message-ID: > Domain-specific abstractions do that *faster* than GUI designers, not > slower. And better, too, since every iteration tends to be fully > functional and not just a "let's see what this looks like" prototype. Can you show me some working, in-use example for that? I _seriously_ doubt that the process of rearranging and tuning the layout can be done faster in the text-world than with a good designer like qt-designer. But I'm all ears for better solutions. BTW, when I talk of gui designers, I _only_ have them for creating guis - no attaching of event code or stuff like that (except from some trivial signal-slot-connections, that is) As a programmer, the only thing of interest to me are the certain widgets I need my logic to bind to. The structure of the thing itself I don't care about. > > Heck, switch 'em out dynamically based on what day of the week it is and > how the user feels today. Let's see your GUI-designer do that. > > And if you're not used to doing it that way, you'll be *stunned* at how > much stuff tends to factor out and get easily re-used. Well - stun me by example :) > > An approach that has more data to work with (some idea of what things are > doing and what they are for) will beat an approach with less data ("thing > at row 4, col 2" or, worst case, "thing at 233,144") any day. Hm. There certainly are cases where I take smaller building blocks and rearrange them according to my current needs - all in python of course. But that's only a comparably small part - at least to my current apps. It could grow depending on the type of application - e.g. database driven stuff - but so far, I'm pretty well with creating the larger dialogs/widgets in the designer and when the functionality is working, the rearranging of these widgets for better usability is pretty important and certainly easier done in the designer. To me the whole discussion is similar to generating html using python or using templates - templates need only to conform to a certain interface for the app writer to work. Sure, sometimes things get a little bit more tedious compared to just printing out html fragments. But the more control you want over the look of your results, the less powerful the generating approach becomes - because you simply lack the features to control the layout or you take deep steps into parameter hell - but then I see html as a domain specific language and prefer to use that to control the layout. I've seen such development in the java-world using struts, where people introduced their own tags for displaying data objects - over time, some of these grew 10 or more cryptic attributes for fine-controlling the layout. Instead of just providing the necessary data and letting jsp do the layout. -- Regards, Diez B. Roggisch From ksenia.marasanova at gmail.com Mon Apr 11 03:42:22 2005 From: ksenia.marasanova at gmail.com (Ksenia Marasanova) Date: Mon, 11 Apr 2005 09:42:22 +0200 Subject: templating system In-Reply-To: References: <130df19305041008552621549c@mail.gmail.com> Message-ID: <130df19305041100427ea9d54d@mail.gmail.com> > > > http://www.reportlab.org/preppy.html Looks very close to what I was looking for :) Thanks! -- Ksenia From codecraig at gmail.com Fri Apr 15 09:43:15 2005 From: codecraig at gmail.com (codecraig) Date: 15 Apr 2005 06:43:15 -0700 Subject: Get OS name Message-ID: <1113572595.889597.206690@g14g2000cwa.googlegroups.com> How can I get the OS Name, such as "Windows XP Pro". I know I can do sys.getwindowsversion but that doesnt return a nice Windows XP Pro string. and os.name gives "nt" thanks. From gsakkis at rutgers.edu Mon Apr 11 07:08:00 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 11 Apr 2005 04:08:00 -0700 Subject: Puzzling OO design problem References: <1113003772.020556.69550@l41g2000cwc.googlegroups.com> <1113010854.638038.173460@g14g2000cwa.googlegroups.com> <1113018015.535852.53250@z14g2000cwz.googlegroups.com> <1113043759.765568.9920@o13g2000cwo.googlegroups.com> <425919b6.16894062@news.oz.net> Message-ID: <1113217680.850207.93810@z14g2000cwz.googlegroups.com> "Bengt Richter" wrote in message news:425919b6.16894062 at news.oz.net... > > See if this does what you want: > > [snipped] > Yes, that's pretty much what I had in mind. I particularly liked the idea of mirroring automagically the nested class inheritance in each version. So I tried to refine this recipe a little and I pushed down the boilerplate code from 3 lines to one word; laziness is a virtue :-) Below is the test only; I posted the main module to http://rafb.net/paste/results/Hweu3t19.html to avoid messing up the indentation. Cheers, George #================================================= # test.py from namespace import Namespace class Era(object): def __init__(self): self.lumberjack = self.GameUnit() self.warrior = self.CombatUnit() self.shooter = self.RangedUnit() class MedievalAge(Era): __metaclass__ = Namespace() class GameUnit(object): def move(self): return "MedievalAge.GameUnit.move()" class CombatUnit(GameUnit): def fight(self): return "MedievalAge.CombatUnit.fight()" class RangedUnit(CombatUnit): def aim(self): return "MedievalAge.RangedUnit.aim()" class ColonialAge(Era): __metaclass__ = Namespace(MedievalAge) class CombatUnit: def fight(self): return "ColonialAge.CombatUnit.fight()" class IndustrialAge(Era): __metaclass__ = Namespace(ColonialAge) class GameUnit: def move(self): return "IndustrialAge.GameUnit.move()" class RangedUnit: def aim(self): return "IndustrialAge.RangedUnit.aim()" if __name__ == '__main__': for era in MedievalAge(), ColonialAge(), IndustrialAge(): for player in era.lumberjack, era.warrior, era.shooter: for action in "move", "fight", "aim": try: result = getattr(player,action)() except AttributeError: result = "N/A" print "%s:%s.%s:\t%s" % (type(era).__name__, type(player).__name__, action, result) From myata99 at tom.com Wed Apr 13 14:17:15 2005 From: myata99 at tom.com (Tom) Date: Thu, 14 Apr 2005 02:17:15 +0800 Subject: How to call a function in embeded python code in delphi? Message-ID: <425D622B.1020600@tom.com> delphi 7 python 2.3 win98 Python for Delphi V3.25 In Delphi: 1 Create a new Form ; 2 Drop a TMemo(Memo1) to contain python code; 3 Drop a TPythonInputOutput (PythonInputOutput1) ; 4 Drop a TPythonEngine (PythonEngine1) ; 5 Drag a PythonDelphiVar component and name it bx. Set the VarName property to the same as its name; 6 Connect the attribute IO of the TPythonEngine to the TPythonInputOutput; 7 Drop a TButton (Button1) ; 8 Write python code in the Memo1 (set Memo1's property of lines): def ax(m,n): y=10 bx.value=y+m+n ... Now, As click Button1, how to call the funtion ax passing the arguments(such as m=33 and n=25), and get bx.ValueAsString ; Delphi Code: --------------------------- unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, PythonEngine, StdCtrls; type TForm1 = class(TForm) Memo1: TMemo; Button1: TButton; PythonEngine1: TPythonEngine; bx: TPythonDelphiVar; PythonInputOutput1: TPythonInputOutput; procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject); begin ///////////////////////////////////////////////// // // // How to call the funtion ax passing the // // arguments(such as m=33 and n=25), and // // get bx.ValueAsString ?? // // // ///////////////////////////////////////////////// showmessage( bx.ValueAsString ); end; end. ------------------------------- Thank you very much!! From jmeile at hotmail.com Mon Apr 18 11:43:59 2005 From: jmeile at hotmail.com (Josef Meile) Date: Mon, 18 Apr 2005 17:43:59 +0200 Subject: Zope3 and Plone In-Reply-To: <1113835544.983163.202080@z14g2000cwz.googlegroups.com> References: <1113835544.983163.202080@z14g2000cwz.googlegroups.com> Message-ID: <4263D5BF.40407@hotmail.com> Hi Mir, you are asking in the wrong place. This is a python specific list. You can find a suitable list here: http://mail.zope.org/mailman/listinfo Regards, Josef Mir Nazim wrote: > Hi, > > I wanted to know what will happen to plone once Zope3 will be official > version. Is plone being ported to Zope3. I googled it but did not come > accross anything stating the plone's migration to zope3. > > I am thinking to take up a project. plone is a candidate for it. should > i want to take benifit of zope3 features too. > > what should be done. > > Please comment > thanks > From programmer.py at gmail.com Fri Apr 15 22:23:32 2005 From: programmer.py at gmail.com (Jaime Wyant) Date: Fri, 15 Apr 2005 21:23:32 -0500 Subject: Piping data into script under Win32 In-Reply-To: <1113617504.067692.311950@o13g2000cwo.googlegroups.com> References: <1113617504.067692.311950@o13g2000cwo.googlegroups.com> Message-ID: I can't think of any reason that wouldn't work. You've entered the code in exactly like you have it below? Could you paste the traceback from your console? jw On 15 Apr 2005 19:11:44 -0700, runes wrote: > I trying to figure out a way to make a python script accept data output > from another process under Windows XP, but I fail miserably. I have a > vague memory having read this is not possible with Python under > Windows... > > But googling for a clue I came across this from /Learning Python/ (Lutz > & Ascher) [1] > > > > import sys > data = sys.stdin.readlines() > print "Counted", len(data), "lines." > > On Unix, you could test it by doing something like: > > % cat countlines.py | python countlines.py > Counted 3 lines. > > On Windows or DOS, you'd do: > > C:\> type countlines.py | python countlines.py > Counted 3 lines. > > > > So: Is it possible to pipe data under DOS/Win9x but not NT/2k/XP or is > it a bug in /Learning Python/ ? > > I've tried about all kinds of sane and insane approaches involving > sys.stdin, but they all results in IOError: [Errno 9] Bad file > descriptor. > > [1] > > -- > http://mail.python.org/mailman/listinfo/python-list > From steve at holdenweb.com Tue Apr 26 08:34:25 2005 From: steve at holdenweb.com (Steve Holden) Date: Tue, 26 Apr 2005 08:34:25 -0400 Subject: regex over files In-Reply-To: <426E221D.5020005@chamonix.reportlab.co.uk> References: <426D0659.7080307@chamonix.reportlab.co.uk><426D08BC.1040703@klix.ch> <426E021E.8000809@jessikat.fsnet.co.uk> <426E221D.5020005@chamonix.reportlab.co.uk> Message-ID: Robin Becker wrote: > Steve Holden wrote: > ...... > >> >> I seem to remember that the Medusa code contains a fairly good >> overlapped search for a terminator string, if you want to chunk the file. >> >> Take a look at the handle_read() method of class async_chat in the >> standard library's asynchat.py. > > ..... > thanks I'll give it a whirl > Whoops, I don't think it's a regex search :-( You should be able to adapt the logic fairly easily, I hope. regards Steve -- Steve Holden +1 703 861 4237 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ From bogus@does.not.exist.com Fri Apr 15 11:55:02 2005 From: bogus@does.not.exist.com () Date: Fri, 15 Apr 2005 15:55:02 -0000 Subject: (no subject) Message-ID: #! rnews 2153 Newsgroups: comp.lang.python Path: news.xs4all.nl!newsspool.news.xs4all.nl!transit.news.xs4all.nl!195.241.76.212.MISMATCH!transit1.news.tiscali.nl!transit0.news.tiscali.nl!tiscali!newsfeed1.ip.tiscali.net!proxad.net!proxad.net!newshosting.com!nx02.iad01.newshosting.com!novia!feed2.newsreader.com!newsreader.com!newsread.com!news-xfer.newsread.com!nntp.abs.net!attws2!ip.att.net!NetNews1!xyzzy!nntp From: Harry George Subject: Re: Python's use in RAD X-Nntp-Posting-Host: cola2.ca.boeing.com Content-Type: text/plain; charset=us-ascii Message-ID: User-Agent: Gnus/5.09 (Gnus v5.9.0) Emacs/21.3 Lines: 46 Sender: hgg9140 at cola2.ca.boeing.com Organization: The Boeing Company References: Mime-Version: 1.0 Date: Fri, 15 Apr 2005 15:33:58 GMT Xref: news.xs4all.nl comp.lang.python:372620 "Ross Cowie" writes: > Hi, > > I am currenly a second year university student and was wondering if > you could help me ut. As part of a project i have decided to write > about python, i am not having very much luck with regards to finding > infrmation on pythons use in Rapid Application Development, and was > wondering of you could highlight some of the features that make it > suitable for RAD. Like the use of dinamic binding. > > Your healp would be appreciated. > > Hope to hear from you soon. > > Ross > > Generally we don't do homework here. But we can give you pointers. 1. Searching google for "python RAD" shows 148,000 hits, and at least the first few pages look relevant. Did you check? 2. "RAD" means different things to different people. Do you mean: a) Agile/Extreme Programming (2 or more people working together) b) Test-driven c) GUI builder d) Rapid edit-run cycle e) Lots of libraries so your work is just hooking together existing tools f) Dynamic, code-generated-on-the-fly, or other meta programming g) Project management experience in life cycle flow times and labor costs You need to understand your assignment in these terms, then you can investigate Python. 3. As a practical matter, Python does "a"-"g" quite well. Originally this was because of the rich-yet-clean syntax and batteries-included libraries. These days those factors still count, but they are enhanced by large numbers of "other" libraries and tools which have Python bindings. -- harry.g.george at boeing.com 6-6M21 BCA CompArch Design Engineering Phone: (425) 294-4718 From rkern at ucsd.edu Sat Apr 23 23:50:53 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sat, 23 Apr 2005 20:50:53 -0700 Subject: Variables In-Reply-To: <426B1300.6090802@cloudthunder.com> References: <426B0283.40602@cloudthunder.com> <426b0d03_3@newspeer2.tds.net> <426B1300.6090802@cloudthunder.com> Message-ID: Richard Blackwood wrote: > Kent Johnson wrote: > >> Richard Blackwood wrote: >> >>>>> To All: >>>>> >>>>> Folks, I need your help. I have a friend who claims that if I >>>>> write: >>>>> >>>>> foo = 5 >>>>> >>>>> then foo is NOT a variable, necessarily. >>>> >>>> >>>> >>> Indeed, this language is math. My friend says that foo is a constant >>> and necessarily not a variable. >> >> >> >> Well, we mostly talk Python here, not math. In Python, if you say >> foo = 5 >> foo is a name bound to an immutable value. >> >> If I had written foo = raw_input(), he would >> >>> say that foo is a variable. >> >> >> >> That's funny. foo is still a name bound to an immutable (string) >> value. foo is no more or less variable than it was with foo = 5. >> >> Which is perfectly fine except that he >> >>> insists that since programming came from math, the concept of >>> variable is necessarily the identical. This can not be true. For >>> example, I may define foo as being a dictionary, but I can not do >>> this within math because there is no concept of dictionaries within >>> mathematics; yet foo is a variable, a name bound to a value which can >>> change. >> >> >> >> Sounds like you are having a stupid and meaningless argument with your >> friend. What you call foo won't change what it is. He should learn >> Python, then he would understand the true zen of foo. > > > That is exactly how I feel about it. Foo is what it is. Variable, name > bound to immutable value, etc., what we call it doesn't really change > how I program, only how I communicate with other programmers (and > mathematicians). Is the notion of variable not a fundamental concept in > programming? Surely there must be an unambiguous definition I can relay > to him. Why should there be? Different programming languages have different models. In C, a variable corresponds to a memory slot. In Python, it's a just a name that can be bound to an object. If you must, http://en.wikipedia.org/wiki/Variable -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From nemesis at nowhere.invalid Tue Apr 12 16:11:45 2005 From: nemesis at nowhere.invalid (Nemesis) Date: Tue, 12 Apr 2005 20:11:45 GMT Subject: Python 2.4 killing commercial Windows Python development ? References: <425a9869$0$38039$bed64819@news.gradwell.net><20050411194907.1769.17472.XPN@orion.homeinvalid> <425AF2FD.2080006@v.loewis.de> Message-ID: <20050412192200.1706.92325.XPN@orion.homeinvalid> Mentre io pensavo ad una intro simpatica "Fredrik Lundh" scriveva: >> It will just work. Python installs the DLL if it is missing, and leaves >> it alone (just incrementing the refcount) if it is present on the target >> system. > installs it where? the MS docs seem to indicate that they want you to install > it in the program directory, rather than in a "shared" location: As far I remember the Python installer copies this dll in the system32 folder if you install Python as Administrator, instead it leaves the dll inside the Python folder if you install Python as User. -- As a computer, I find your faith in technology amusing. |\ | |HomePage : http://nem01.altervista.org | \|emesis |XPN (my nr): http://xpn.altervista.org From peter at engcorp.com Mon Apr 4 10:06:46 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 04 Apr 2005 10:06:46 -0400 Subject: redundant importr In-Reply-To: References: <3avnh3F6cekgkU1@individual.net> <1MudnZ0j7M-bIdDfRVn-sA@powergate.ca> Message-ID: max(01)* wrote: > Peter Hansen wrote: >> No it doesn't. I thought I was clear, but I can reword >> it for you: the files are compiled *in-memory* and the >> results are never written to disk. >> >> > *if* they are compiled, where are they put, if the >>> corresponding *.py files are on a non-writeable directory? >> >> They are not put anywhere. > > ok, maybe it is an implementation-dependent issue after all. Not really. > consider this: [snip] > -rw-r--r-- 1 max2 max2 307 2005-04-02 17:45 imported.pyc > > see? Yes, but you don't, yet. :-) Obviously the .pyc file is being written, so my comments above, out of context, is wrong. Now please go put them back in context. You asked what would happen if the directory was not writable. That's the context in which to interpret my claims that the bytecode (the *result* of the compilation) is not written to disk. I'll try one last time, before giving up in abject failure and letting someone else take a stab at this: the compilation will occur every time if a .pyc file does not exist. The interpreter will attempt to write the results of the compilation process to disk in a .pyc file to cache it for the next time, to avoid having to recompile. *If* this is not possible, then no caching takes place, no .pyc file is written, and the next time you run the code, the compilation step will occur all over again (note: with the results being held in memory only while the program runs, then discarded). Please tell me it's clear now. :-) -Peter From nick at craig-wood.com Mon Apr 4 07:30:02 2005 From: nick at craig-wood.com (Nick Craig-Wood) Date: 04 Apr 2005 11:30:02 GMT Subject: Queue.Queue-like class without the busy-wait References: <1111707620.556818.289300@g14g2000cwa.googlegroups.com> <7xmzsshzxr.fsf@ruckus.brouhaha.com> <7x8y4cyr70.fsf@ruckus.brouhaha.com> <7xoed86lnd.fsf@ruckus.brouhaha.com> <7xfyyjcu5w.fsf@ruckus.brouhaha.com> <1112278104.651390.305160@f14g2000cwb.googlegroups.com> <1112278604.081328.60970@f14g2000cwb.googlegroups.com> Message-ID: pyguy2 at gmail.com wrote: > Thinking about cross-platform issues. I found this, from the venerable > Tim Peters to be enlightening for python's choice of design: > > "It's possible to build a better Queue implementation that runs only on > POSIX systems, or only on Windows systems, or only on one of a dozen > other less-popular target platforms. The current implementation works > fine on all of them, although is suboptimal compared to what could be > done in platform-specific Queue implementations. " > > Here is a link: > http://groups-beta.google.com/group/comp.lang.python/messages/011f680b2dac320c,a03b161980b81d89,1162a30e96ae330a,0db1e52548493843,6b8d593c84ad4fd4,b6293a53f98252ce,82cddc89805b4b56,81c7289cc4cb4441,0906b24cc1534844,3ff6629391074ed4?thread_id=55b80d05e9d54705&mode=thread&noheader=1&q=queue+timeout+python#doc_011f680b2dac320c Interesting thread. How about leaving the current threading alone, but adding a pthreads module for those OSes which can use or emulate posix threads? Which is windows and most unixes? -- Nick Craig-Wood -- http://www.craig-wood.com/nick From benmarkwell at gmail.com Fri Apr 1 22:52:42 2005 From: benmarkwell at gmail.com (Ben) Date: 1 Apr 2005 19:52:42 -0800 Subject: New to programming question In-Reply-To: References: <1112325275.120122.100800@o13g2000cwo.googlegroups.com> Message-ID: <1112413962.901616.37300@o13g2000cwo.googlegroups.com> Thanks for your reply. From bgs248 at hotmail.com Wed Apr 27 20:34:49 2005 From: bgs248 at hotmail.com (bgs) Date: 27 Apr 2005 17:34:49 -0700 Subject: suggestions on how to do this References: Message-ID: <1114648489.758666.224590@o13g2000cwo.googlegroups.com> You could probably use scipy.base.polynomial, but it's easy enough to implement a polynomial yourself. Just use a dict-- each key represents the power and each value the coefficient of the polynomial. You didn't say exactly how efficient you need this. It takes only a couple seconds to sum 100 of the b(k)'s using the implementation below. This gets you roots out to about A=500. Perhaps there are bugs in the below implementation. Either way, you can compare your results and its results and if they're not the same, well then there's a problem. ------------------------------------------ from rational import rational #get from bitconjurer.org/rational.py def add(a, b, s=1): c = {} for k, v in b.items(): if not a.has_key(k): c[k] = s*v for k, v in a.items(): vb = b.get(k, 0) c[k] = a[k] + s*vb return c def raise1(a): b = {} for k, v in a.items(): b[k+1] = v return b def scale(a, s): b = {} for k, v in a.items(): b[k] = v*s return b def eval(x, p): s = 0.0 for k, v in p.items(): s = s + float(v.num)/float(v.den)*x**k return s b = {-3 : {}, -2 : {}, -1 : {}, 0 : {0:rational(1,1)}, 1 : {}} N = 100 for k in range(2,N): b[k] = scale(raise1(add(b[k-5],b[k-2],-1)),rational(1,k**2)) o = [b[0]] for k in range(1, N): o.append(add(o[-1], b[k])) for x in range(0,800): print x, eval(x, o[-3]), eval(x, o[-2]), eval(x, o[-1]) # o[-1],o[-2], and o[-3] start to split around x = 500 From steve at holdenweb.com Mon Apr 25 12:45:18 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 25 Apr 2005 12:45:18 -0400 Subject: Injecting code into a function In-Reply-To: <1114425158.092697.99030@o13g2000cwo.googlegroups.com> References: <1114425158.092697.99030@o13g2000cwo.googlegroups.com> Message-ID: George Sakkis wrote: > Is there a general way of injecting code into a function, typically > before and/or after the existing code ? I know that for most purposes, > an OO solution, such as the template pattern, is a cleaner way to get > the same effect, but it's not always applicable (e.g. if you have no > control over the design and you are given a function to start with). In > particular, I want to get access to the function's locals() just before > it exits, i.e. something like: > > def analyzeLocals(func): > func_locals = {} > def probeFunc(): > # insert func's code here > sys._getframe(1).f_locals["func_locals"].update(locals()) > probeFunc() > # func_locals now contains func's locals > > So, how can I add func's code in probeFunc so that the injected code > (the update line here) is always called before the function exits ? > That is, don't just inject it lexically in the end of the function if > there are more than one exit points. I guess a solution will involve a > good deal bytecode hacking, on which i know very little; if there's a > link to a (relatively) simple HOWTO, it would be very useful. > > Thanks, > George > A decorator would seem to be the sensible way to do this, assuming you are using Python 2.4. def decorated(func): def wrapper(arg1, arg2, arg3): print "Arg2:", arg2 func(arg1) print "Arg3:", arg3 return wrapper @decorated def f1(x): print "F1:", x f1('ARG1', 'ARG2', 'ARG3') Arg2: ARG2 F1: ARG1 Arg3: ARG3 All the decorator really does is compute one function from another. There's been enough discussion on the list recently that I won't repeat the theory. regards Steve -- Steve Holden +1 703 861 4237 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ From ville at spammers.com Fri Apr 29 15:58:01 2005 From: ville at spammers.com (Ville Vainio) Date: 29 Apr 2005 22:58:01 +0300 Subject: Which IDE is recommended? References: <426f90ac$1_2@rain.i-cable.com> Message-ID: >>>>> "John" == John J Lee writes: John> Dave Cook writes: John> What are those compelling features of Pydev, for an emacs John> user? http://pydev.sourceforge.net/features.html Code completion and debugger are the most obvious ones. Eclipse itself is also quite a "feature". -- Ville Vainio http://tinyurl.com/2prnb From theoryboy at my-deja.com Fri Apr 29 07:31:08 2005 From: theoryboy at my-deja.com (Peter Saffrey) Date: 29 Apr 2005 04:31:08 -0700 Subject: Python site-packages and import Message-ID: (apologies for starting a new thread - Google can't retrieve the other message for some reason) Yes, /usr/lib/python/site-packages is in sys.path. This series of commands should explain what I mean: I've put the Python ID3 module in a sub-directory of site-packages as an illustration. pzs at bonnie:~$ ls /usr/lib/python2.3/site-packages/ ID3.py ID3.pyc ID3.pyo README apt_inst.so apt_pkg.so apt_proxy bsddb3 debconf.py debconf.pyc debconf.pyo id3 pj twisted pzs at bonnie:~$ ls /usr/lib/python2.3/site-packages/apt_proxy/ __init__.py __init__.pyo apt_proxy.pyc apt_proxy_conf.py apt_proxy_conf.pyo apt_proxytap.pyc memleak.py memleak.pyo misc.pyc packages.py packages.pyo __init__.pyc apt_proxy.py apt_proxy.pyo apt_proxy_conf.pyc apt_proxytap.py apt_proxytap.pyo memleak.pyc misc.py misc.pyo packages.pyc twisted_compat pzs at bonnie:~$ ls /usr/lib/python2.3/site-packages/id3 ID3.py ID3.pyc ID3.pyo pzs at bonnie:~$ python Python 2.3.5 (#2, Feb 9 2005, 00:38:15) [GCC 3.3.5 (Debian 1:3.3.5-8)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.path ['', '/usr/lib/python23.zip', '/usr/lib/python2.3', '/usr/lib/python2.3/plat-linux2', '/usr/lib/python2.3/lib-tk', '/usr/lib/python2.3/lib-dynload', '/usr/local/lib/python2.3/site-packages', '/usr/lib/python2.3/site-packages'] >>> import apt_proxy.memleak >>> import id3.ID3 Traceback (most recent call last): File "", line 1, in ? ImportError: No module named id3.ID3 >>> Peter From ville at spammers.com Wed Apr 6 02:53:15 2005 From: ville at spammers.com (Ville Vainio) Date: 06 Apr 2005 09:53:15 +0300 Subject: Case-insensitive dict, non-destructive, fast, anyone? References: <424dc33c.55623752@news.oz.net> Message-ID: >>>>> "Bengt" == Bengt Richter writes: Bengt> I wonder if a dict with a general override hook for hashing Bengt> all keys would be useful. E.g., a dict.__keyhash__ that Bengt> would take key as arg and default as now returning Bengt> key.__hash__() but that you could override. Seems like this There would need to be an override hook for key comparison as well (I suppose it always uses == operation now?). But yes, I think it would be *much* more useful than any 'keytransform' feature - is there any use for 'keytransform' feature apart from the uses that would be better covered by hash/comparison hooks? It would be lovely to have something like this in the stdlib (or anywhere, for that matter). Think about the use cases for hashing via by os.path.normcase, str.lower... -- Ville Vainio http://tinyurl.com/2prnb From bokr at oz.net Wed Apr 6 04:10:22 2005 From: bokr at oz.net (Bengt Richter) Date: Wed, 06 Apr 2005 08:10:22 GMT Subject: Decorator Base Class: Needs improvement. References: <0v4351l5v1f3i9h3fssvcfklifkdlhjv7o@4ax.com> <43d351pq3qmlr8vlealdj818p8mt61p1ps@4ax.com> Message-ID: <425394bd.436936831@news.oz.net> On Wed, 06 Apr 2005 02:31:05 GMT, Ron_Adam wrote: >On Tue, 05 Apr 2005 19:38:38 -0400, Steve Holden >wrote: > > >>> >>So what you are saying is that you would like to be able to use >>arbitrarily complex expressions after the :at" sign, as long as they >>return a decorator? If so, you've been "pronounced" :-) >> >>regards >> Steve > >No not at all, I never said that. But.. ;-) > > >If we get into what I would like, as in my personal wish list, that's >a whole other topic. > > >I would have preferred the @ symbol to be used as an inline assert >introducer. Which would have allowed us to put debug code anywhere we >need. Such as @print total @. Then I can switch on and off >debugging statements by setting __debug__ to True or False where ever >I need it. > >And as far as decorators go. I would of preferred a keyword, possibly >wrap, with a colon after it. Something like this. I don't understand your seeming fixation with wrappers and wrapping. That's not the only use for decorators. See Raymond Hettinger's optimizing decorators in the cookbook for instance. Decorators are something like metaclasses for functions, with much more general possibilities than wrapping, IMO. > >def function_name(x): > return x > >wrap function_name: > wrapper1() > wrapper2() > wrapper3() > >A wrap command could more directly accomplish the wrapping, so that >def statements within def statements aren't needed. (Unless you >want'ed too for some reason.) I think you'll have to show some convincing use cases showing a clear advantage over current decoration coding if you want converts ;-) > >And as far as arbitrary complex expressions go.. Actually I think that >it's quite possible to do as it is. ;-) Yes and no. You can always write @deco and refer to an arbitrarily complex callable deco ..., but the actual @-line expression has to abide by the language grammar, and that does not allow arbitrary expressions. But it does provide enough rope. E.g. see my most recent reply to El Pitonero. > >But this is just a few of my current thoughts which may very well >change. It's an ever changing list. > I can see that ;-) Regards, Bengt Richter From jepler at unpythonic.net Sun Apr 3 16:45:29 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Sun, 3 Apr 2005 15:45:29 -0500 Subject: Corectly convert from %PATH%=c:\\X; "c:\\a; b" TO ['c:\\X', 'c:\\a; b'] In-Reply-To: <200504032012.j33KCqU17294@unpythonic.net> References: <20050403150134.GA3398@unpythonic.net> <200504032012.j33KCqU17294@unpythonic.net> Message-ID: <20050403204529.GC3398@unpythonic.net> The C code that Python uses to find the initial value of sys.path based on PYTHONPATH seems to be simple splitting on the equivalent of os.pathsep. See the source file Python/sysmodule.c, function makepathobject(). for (i = 0; ; i++) { p = strchr(path, delim); // ";" on windows, ":" on unix if (p == NULL) ... w = PyString_FromStringAndSize(path, (int) (p - path)); if (w == NULL) ... PyList_SetItem(v, i, w); if (*p == '\0') break; path = p+1; } No special handling of quote characters happens here. > I think I will stick to a simple splitting at the ;. Luckily all the > directories I am dealing with have nice names. If you do this, you'll match the behavior of python itself, and you'll match the behavior of wine. > I have not even tried to see what quirks there exist with unix. None. There's no way to quote anything in paths, so while you can't place a directory with a colon in its name on your path, nobody loses any sleep over it either. Here's what the Open Group has to say about PATH: PATH This variable shall represent the sequence of path prefixes that certain functions and utilities apply in searching for an executable file known only by a filename. The prefixes shall be separated by a colon ( ':' ). When a non-zero-length prefix is applied to this filename, a slash shall be inserted between the prefix and the filename. A zero-length prefix is a legacy feature that indicates the current working directory. It appears as two adjacent colons ( "::" ), as an initial colon preceding the rest of the list, or as a trailing colon following the rest of the list. A strictly conforming application shall use an actual pathname (such as .) to represent the current working directory in PATH . The list shall be searched from beginning to end, applying the filename to each prefix, until an executable file with the specified name and appropriate execution permissions is found. If the pathname being sought contains a slash, the search through the path prefixes shall not be performed. If the pathname begins with a slash, the specified path is resolved (see Pathname Resolution). If PATH is unset or is set to null, the path search is implementation-defined. ah, if only windows was so well-defined! Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From michael.kearns at REMOVEsaaconsultants.com Tue Apr 12 04:48:35 2005 From: michael.kearns at REMOVEsaaconsultants.com (Michael Kearns) Date: Tue, 12 Apr 2005 09:48:35 +0100 Subject: Python 2.4 killing commercial Windows Python development ? In-Reply-To: <425ad806$0$3146$8fcfb975@news.wanadoo.fr> References: <425a9869$0$38039$bed64819@news.gradwell.net> <425ad806$0$3146$8fcfb975@news.wanadoo.fr> Message-ID: <425b8b32$0$38040$bed64819@news.gradwell.net> Do Re Mi chel La Si Do wrote: > Hi ! > > This DLL come also with MS-JVM engine, who is free. Therefore... > This is very true (and the .NET suggestion as well). However, why should I require an end-user to install MS-JVM or the .NET framework, purely for a simple little launcher application ? The main application it launches is Java, but there's no way it would run on the MS-JVM, and .NET just gives a load more technology that we don't really need (and is a bigger install than the entire application). Michael. From glauco.silva at cenpra.gov.br Fri Apr 15 09:21:31 2005 From: glauco.silva at cenpra.gov.br (Glauco Silva) Date: Fri, 15 Apr 2005 10:21:31 -0300 Subject: problem with py2exe ! Message-ID: <022901c541be$0a13d230$e87290c8@piau> Hi, I?m with problem to create a executable program in python. I?m using py2exe but i don?t know if it?s right. My setup.py: from distutils.core import setup import py2exe from glob import glob setup( # The first three parameters are not required, if at least a # 'version' is given, then a versioninfo resource is built from # them and added to the executables. version = "2.0", description = "programa InVesalius", name = "InVesalius", # targets to build console = ["C:\\promed2.0\\python\\MyMainModule.py"], data_files=[("icons", glob("C:\\promed2.0\\icons\\*.*")), ("docs",glob("C:\\promed2.0\\docs\\*.*")), ("config", ["C:\\promed2.0\\setup.cfg"]) ], packages = ['vtk-windows', 'vtk-windows.vtk', 'vtk-windows.vtk.gtk', 'vtk-windows.vtk.qt', 'vtk-windows.vtk.tk', 'vtk-windows.vtk.util', 'vtk-windows.vtk.wx', 'vtk-windows.vtk.test'], ) When i run in prompt "python setup.py py2exe", appear in the end this: ########### The following modules appear to be missing [ '_imaging_gif','libVTKCommonPython', 'libVTKContribPython', 'libVTKGraphicsPython', 'libVTKImagingPython', 'libVTKPatentedPython', libvtkCommonPython', 'libvtkFilteringPython', 'libvtkGraphicsPython', 'libvtkHybridPython', 'libvtkIOPython', 'libvtkImagingPython', 'libvtkParallelPython', 'libvtkPatentedPython', 'libvtkRenderingPython', 'numarray.array', 'numarray.dot', 'numarray.fromfile', 'numarray.size', 'numarray.zeros', 'vtk.vtkActor2D', 'vtk.vtkDCMParser', 'vtk.vtkImageClip', 'vtk.vtkImageFlip', 'vtk.vtkImageImport', 'vtk.vtkImageMagnify', 'vtk.vtkImageMapper', 'vtk.vtkImagePermute', 'vtk.vtkImageReader', 'vtk.vtkImageResample', 'vtk.vtkImageReslice', 'vtk.vtkImageShiftScale', 'vtk.vtkImageThreshold', 'vtk.vtkImageViewer', 'vtk.vtkImageWriter', 'vtk.vtkRenderWindow', 'vtk.vtkRenderer', 'vtk.vtkTextMapper', 'vtk.vtkTextProperty', 'vtk.vtkTransform'] ########### My PYTHONPATH = C:\Python23;C:\promed2.0\vtk-windows;C:\promed2.0\python My dir: ########## promed2.0/ setup.cfg setup.py icons/ docs/ python/ MyMainModule.py vtk-window/ vtkpython.py vtkpythontk.py vtk.pth vtkCommon.dll vtkCommonPython.dll vtkCommonTCL.dll ... vtk/ ########### OS: win 2K Python ver: 2.3.5 py2exe ver: 0.5.4 How can i solve this problem? Thanks Glauco -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- No virus found in this outgoing message. Checked by AVG Anti-Virus. Version: 7.0.308 / Virus Database: 266.9.11 - Release Date: 14/4/2005 From grante at visi.com Tue Apr 5 09:40:15 2005 From: grante at visi.com (Grant Edwards) Date: Tue, 05 Apr 2005 13:40:15 -0000 Subject: How to merge two binary files into one? References: <1153pu8pvom6b02@corp.supernews.com> <1153vfhid1vfif1@corp.supernews.com> Message-ID: <115559v197r5e5c@corp.supernews.com> On 2005-04-05, Andrew Dalke wrote: > Grant Edwards wrote: >> For large files, something like this is probably a better idea: > > Or with the little-used shutil module, and keeping your > nomenclature and block size of 65536 I knew I should have looked through shutil to see if there was already something like that. -- Grant Edwards grante Yow! MMM-MM!! So THIS is at BIO-NEBULATION! visi.com From jelleferinga at gmail.com Tue Apr 26 11:52:37 2005 From: jelleferinga at gmail.com (jelle) Date: 26 Apr 2005 08:52:37 -0700 Subject: how to pass an array to a VB array via COM In-Reply-To: References: <1114515084.138728.26180@g14g2000cwa.googlegroups.com> Message-ID: <1114530757.278144.193980@o13g2000cwo.googlegroups.com> No I haven't, it might be an idea. Would it be an effective method though? I have little experience working with COM, but i suppose writing an (VB!) array wouldnt be the most challenging problem, though browsing through this list it looks like no good solution arrived yet. Cheers, Jelle From jarrod.roberson at gmail.com Fri Apr 15 12:52:12 2005 From: jarrod.roberson at gmail.com (fuzzylollipop) Date: 15 Apr 2005 09:52:12 -0700 Subject: How to fix this error in the example in 6.1.4 Files and Directories Message-ID: <1113583932.703797.118610@o13g2000cwo.googlegroups.com> the following code is from the Python 2.3.5 docs ( http://www.python.org/doc/2.3.5/lib/os-file-dir.html ) import os from os.path import join, getsize for root, dirs, files in os.walk('python/Lib/email'): print root, "consumes", print sum([getsize(join(root, name)) for name in files]), print "bytes in", len(files), "non-directory files" if 'CVS' in dirs: dirs.remove('CVS') # don't visit CVS directories every time I try and run it I get the following error print sum([getsize(join(root,name)) from name in files]), ^ the only change I made was the path supplied to os.walk() I think this has to do something with the list comprehension syntax and I am trying to learn that part, using this example which seems to be broken. From irmen.NOSPAM at xs4all.nl Mon Apr 4 14:41:43 2005 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Mon, 04 Apr 2005 20:41:43 +0200 Subject: setup distributed computing for two computer only In-Reply-To: <1112634286.899245.107530@l41g2000cwc.googlegroups.com> References: <1112634286.899245.107530@l41g2000cwc.googlegroups.com> Message-ID: <42518a67$0$136$e4fe514c@news.xs4all.nl> ajikoe at gmail.com wrote: > Is there any one who has experiance about how to setup distributed > computing for 2 computer only. I really want to know from the start. > Any suggestion appreciated. Please be more specific about "distributed computing"... --Irmen From could.net at gmail.com Thu Apr 7 21:32:17 2005 From: could.net at gmail.com (could ildg) Date: Fri, 8 Apr 2005 09:32:17 +0800 Subject: how can I extract all urls in a string by using re.findall() ? In-Reply-To: <1112911984.035191.238350@f14g2000cwb.googlegroups.com> References: <311b5ce105040619052e00e10c@mail.gmail.com> <1112911984.035191.238350@f14g2000cwb.googlegroups.com> Message-ID: <311b5ce10504071832413fc32@mail.gmail.com> I agree with Cappy2112. I got more puzzled after I read the docs On 7 Apr 2005 15:13:04 -0700, Cappy2112 wrote: > >>Reading the documentation on re might be helpfull here :-P > Many times, the python docs can make the problem more complicated, > espcecially with regexes. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- ???????????????????? ???????????????? ???????? From whocaresrmb at yahoo.com Thu Apr 21 14:14:16 2005 From: whocaresrmb at yahoo.com (Johnny Gentile) Date: 21 Apr 2005 11:14:16 -0700 Subject: =?iso-8859-1?q?Re=3A_Good_morning_or_good_evening_depending_upon?= =?iso-8859-1?q?_your_location=2E_I_want_to_ask_you_the_most_import?= =?iso-8859-1?q?ant_question_of_your_life=2E_Your_joy_or_sorrow_for?= =?iso-8859-1?q?_all_eternity_depends_upon_your_answer=2E_The_quest?= =?iso-8859-1?q?ion_is=3A_Are_you_saved=3F_It_is_not_a_question_of_?= =?iso-8859-1?q?how_good_you_are=2C_nor_if_you_are_a_church_member?= =?iso-8859-1?q?=2C_but_are_you_saved=3F_Are_you_sure_you_will_go_t?= =?iso-8859-1?q?o_Heaven_when_you_die=3F_GOOGLE=B7NEWSGROUP=B7POST?= =?iso-8859-1?q?=B7146?= In-Reply-To: <80jf61d89lccsd5j8otesssamm93ecni5i@4ax.com> References: <1114098221.580669.86300@g14g2000cwa.googlegroups.com> <80jf61d89lccsd5j8otesssamm93ecni5i@4ax.com> Message-ID: <1114107256.963720.222660@o13g2000cwo.googlegroups.com> You seem to have a lot of questions for someone who talks to God every three minutes. What do you guys do, discuss the Yankees or something? From steven.bethard at gmail.com Wed Apr 6 02:06:51 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 06 Apr 2005 00:06:51 -0600 Subject: "specialdict" module In-Reply-To: <3bha55F6dj9omU2@individual.net> References: <3bamhhF6j009lU1@individual.net> <3bha55F6dj9omU2@individual.net> Message-ID: Georg Brandl wrote: > Georg Brandl wrote: > >>Hello, >> >>in follow-up to the recent "dictionary accumulator" thread, I wrote a >>little module with several subclassed dicts. >> >>Comments (e.g. makes it sense to use super), corrections, etc.? Is this >>PEP material? >> >>Docstrings, Documentation and test cases are to be provided later. > > So, no further interest in this? Or should I write a PEP before? I'd personally like to see a PEP. It'd give people a chance to come up with some use cases that really justify adding such specialized dicts to the standard library. The only use cases I can come up with would be better served by functions that take a sequence and produce a dict (e.g. by counting items or by grouping items into lists). Once the dict is built, I usually have no more need for the default-specialized methods. I'm sure there are some good use cases out there for such dicts, but before I get behind this, I wouldn't mind seeing a few of them. =) STeVe From radam2_ at _tampabay.rr.com Sat Apr 9 05:29:25 2005 From: radam2_ at _tampabay.rr.com (Ron_Adam) Date: Sat, 09 Apr 2005 09:29:25 GMT Subject: Thoughts on some stdlib modules References: Message-ID: <851f51tlm6nl24mbnt6s7246akgk6ng6ro@4ax.com> On Sat, 09 Apr 2005 02:22:45 -0400, Steve Holden wrote: >Ron_Adam wrote: >> On Fri, 08 Apr 2005 05:15:23 -0400, vegetax >> wrote: >> >> >>>Are those issues being considered right now? i cant find any PEP addressing >>>the issue especifically, at least cooking it for python 3000. >>> >>>specific topics could be: >>> >>>grouping related modules. >>>removing useless legacy modules. >>>refactoring duplicated functionality. >>>removing/redesigning poorly written modules. >>>adding a module versioning system. >> >> >> I've been thinking that the lib directory could be better named and >> rearranged a bit. I sometimes mistakenly open the libs directory >> instead of lib because of the name similarity. >> >> An alternative might be to use the name "packs" or "packages" in place >> of "lib", which would emphasize the use of packages as the primary >> method of extending python. The standard library could then be a >> package called "stdlib" within this directory. Third party packages >> would then be along side "stdlib" and not within a directory that is >> within the standard library. >> >> It would be mostly a cosmetic change, but I believe it would be worth >> doing if it could be done without breaking programs that may have hard >> coded path references to the library. :-/ >> >> Ron >> >Ron: > >You do a lot of thinking, don't you? :-) Just the way my mind works. ;-) >This is a *very large* change, not a cosmetic one, requiring changes to >many installation routines (including, probably, distutils) and causing >problems for software that attempts to operate with multiple versions of >Python - and those projects have problems enough as it is despite >Python's quite fine record of careful development. I thought it might be more involved than it seemed. >This seems a rather high price to pay just to avoid having you >mistakenly avoid opening "libs" instead of "lib" - a distinction that is >only meaningful on Windows platforms anyway, I believe. That's not surprising on windows. >You are correct in suggesting that the library could be better organized >than it is, but I felt we would be better off deferring such change >until the emergence of Python 3.0, which is allowed to break backwards >compatibility. So, start working on your scheme now - PEP 3000 needs >contributions. My own current favorite idea is to have the current >standard library become the "stdlib" package, but I'm sure a lot of >people would find that suggestion at least as half-baked as yours. Yes, I agree, the "stdlib" should be a package. So I don't find it half-baked at all. Packages are part of python, so python should take advantage of them. As far as a organizing scheme, I've come to the conclusion, files should be organized by who's responsible for them, as in who to contact if something doesn't work correctly. And not allowing files to be intermixed from different sources is definitely worth doing if possible. Something Windows does very very badly. For Python, that would mean packages should be fully self contained and don't move any files to other directories if possible. Which simplifies installs, uninstalls, and upgrades. But it would require much more than a cosmetic change, and more than the simple, or not so simple, directory changes I suggested. One of the tools I wrote in C (early 90's), was a make file maker. I still have the source code here somewhere. Starting with the main source file and a template with the compile options in it, it searched all included files recursively for references and built the make file using the template. It really made large projects easy. I don't think that's anything new now. Dist tools should do something like that to find needed files. It shouldn't matter what directories they are in as long as it has read access rights to them, or they are in the search path, or there's a direct or indirect reference to them in the source code someplace. >{If an idea is more-half-baked than something exactly half-baked is it >0.4-baked or 0.6-baked? Does "more half-baked" actually mean "less baked"?) > >regards > Steve All new ideas are un-baked, they aren't fully baked until they are old ideas which have been implemented. So 0.6 baked is more than half baked, and 0.4 baked is ... pudding. ;-) I'll consider working on that PEP. It sounds like it might be a good project for me. Cheers, Ron From mrovner at propel.com Sat Apr 30 03:36:40 2005 From: mrovner at propel.com (Mike Rovner) Date: Sat, 30 Apr 2005 00:36:40 -0700 Subject: Python Challenge ahead [NEW] for riddle lovers In-Reply-To: <1f7befae05043000165448b8d@mail.gmail.com> References: <3dg5isF6qe1nhU1@news.dfncis.de> <1f7befae05043000165448b8d@mail.gmail.com> Message-ID: Tim Peters wrote: > [Mike Rovner] > >>3 IS wrong because if you use any not BIG letter after bodyguard on both >>sides, you get extra 'eCQQmSXK\n' which slow me down for 5 minutes. > > > Get rid of the newlines first. > > On level 7, I'm not sure whether there's something more to do, or > whether I'm looking at a bug in how IE displays .png files. Using > Windows is good practice in solving maddening riddles every day > . There is! That black and white line contains the message. Mike From cam.ac.uk at mh391.invalid Tue Apr 5 18:29:45 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Tue, 05 Apr 2005 23:29:45 +0100 Subject: Best editor? In-Reply-To: <1112725379.514651.66540@l41g2000cwc.googlegroups.com> References: <1112725379.514651.66540@l41g2000cwc.googlegroups.com> Message-ID: ChinStrap wrote: > > Opinions on what the best is? The best editor? Ed is the standard text editor. Accept no substitutes. -- Michael Hoffman From tjreedy at udel.edu Thu Apr 21 17:52:27 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 21 Apr 2005 17:52:27 -0400 Subject: __del__ and reference count problem References: <97O9e.70365$mL3.4834342@phobos.telenet-ops.be><1114107504.036833.109360@z14g2000cwz.googlegroups.com><4267f1e0$0$8871$636a15ce@news.free.fr> <1114116099.446355.13610@z14g2000cwz.googlegroups.com> Message-ID: wrote in message news:1114116099.446355.13610 at z14g2000cwz.googlegroups.com... > it looks like we have to use other way, hold the data we want to > preseve in an object, because it is possible the class is removed > before the instance cleaned, What is removed first is the binding between name A and the class object. But the class object still exists (its refcount is > 0) and can be accessed via the instance which has a reference to that class object. Terry J. Reedy From lbates at syscononline.com Thu Apr 14 14:57:02 2005 From: lbates at syscononline.com (Larry Bates) Date: Thu, 14 Apr 2005 13:57:02 -0500 Subject: distribute python script In-Reply-To: <1113501385.376681.148340@o13g2000cwo.googlegroups.com> References: <1113501385.376681.148340@o13g2000cwo.googlegroups.com> Message-ID: py2exe works just fine, but you didn't give enough information for us to help you. Thomas Heller (maintainer of py2exe) monitors this list. So post some more information of what "...caused a problem in my script..." means and we will all try to help. Larry Bates codecraig wrote: > i want to distribute my python script as an executable. I have tried > py2exe but it caused a problem in my script when I ran it. I know > about Gordon McMillans Installer (which is no longer hosted)..but i > tried that and when i run the .exe it generated, it just crashes (i.e. > Windows wants to send an error report). Pyco is gone as well. > > anyone? > From littlejohn.75 at news.free.fr Sun Apr 17 11:03:46 2005 From: littlejohn.75 at news.free.fr (F. Petitjean) Date: 17 Apr 2005 15:03:46 GMT Subject: module to parse "pseudo natural" language? References: Message-ID: <42627ad1$0$3573$626a14ce@news.free.fr> Le Sun, 17 Apr 2005 13:38:09 +0200, Andrew E a ?crit : > Hi all > > I've written a python program that adds orders into our order routing > simulation system. It works well, and has a syntax along these lines: > > ./neworder --instrument NOKIA --size 23 --price MARKET --repeats 20 > > etc > > However, I'd like to add a mode that will handle, say: > > ./neworder buy 23 NOKIA at MKT x 20 > > I could enter several orders either by running multiple times, or use a > comma-separated approach, like: > > ./neworder buy 23 NOKIA at MKT on helsinki, sell 20 NOKIA at market on > helsinki It would be simpler to have the rule : one line == one order, action, command wahtever. > > The thing about this is that its a "tolerant" parser, so all of these > should also work: > > # omit words like "at", "on" > ./neworder buy 23 NOKIA mkt helsinki > > # take any symbol for helsinki > ./neworder buy 23 mkt helsinki > > # figure out that market=helsinki > ./neworder buy 23 NOKIA at market price You have some variation of the same ? buy ? order. If you want to detail the semantics : you arrive to determine the different parameter of a BuyCommand : what, where, how (many) ... This semantic is expressed differently in english, US-english, french ... If you base your parser on regex you see that the same BuyOrder is represented by a number of variant : Please, buy 23 NOKIA at market Helsinki Acheter 40 actions Bouygues ? la Bouse de Paris So you have for a given environment (orders management module) a number of commands expressed in pseudo-natural languages. Each command has a certain number of attributes name, module_name, parameters, variants(list of regexps for instance), description, short description, sample sentence (to be presented to the user in an interactive session if requested). An important attribute is naturally the action taken when the parser/interpreter matches the current line. So you group the description of the Commands in an easy to parse file and write an interpreter which on startup read such a file for the Commands it understands : command to load a module, to list the commands in the currently loaded module or in the interpreter, command to display the sample, short or long description (help about cmd or how to spell cmd)., command to stop the interpreter (and the program) ... command to read/include a file containings commands to parse and execute. Python is dynamic, with setattr() you can easily construct a Command object from its description. Here is what could be the description of a command to compute the equilibrium position in a stability module (using a ?here? shell like syntax ): command equilibre << eoc description << eod La commande ? equilibre ? permet de lancer le calcul de la position d'?quilibre du flotteur couramment d?crit. position equilibre en partant de pqr 0.0/0.0/1.0 et h=8.500 les mots-cl?s sont equilibre pqr et h[=] eod sample < # The regexpes variants << eov # the following regexp is with re.I (ignore case flag) : variant I << eovi equilibrer?\spqr\s+(?P\d*\.\d*/\d*\.\d*/\d*\.\d*)\s+(?P\d*\.\d*) eovvi # syntax of regexp untested :-) variant << eovi equilibrium\spqr\s+(?P\d*\.\d*/\d*\.\d*/\d*\.\d*)\s+(?P\d*\.\d*) eovvi eov eoc > Thanks for any suggestions :) > > Andrew From sjmachin at lexicon.net Thu Apr 14 18:30:56 2005 From: sjmachin at lexicon.net (John Machin) Date: Fri, 15 Apr 2005 08:30:56 +1000 Subject: Get the entire file in a variable - error References: <1113489431.686307.31840@f14g2000cwb.googlegroups.com> Message-ID: On 14 Apr 2005 07:37:11 -0700, martijn at gamecreators.nl wrote: >H! > >I'm using a database and now I want to compress a file and put it into >the database. > >So I'm using gzip because php can open the gzip file's. >The only problem is saving the file into the database. > >The function below does this: >- gzip the file [oke] >- get all the bytes with tst.getvalue() [error] >I only get the first line. > >I have the same problem when I try it with file.open(), .read(). > >"how to get all the binary data in a variable to put that in a database >LONG field?" > >Thank's > >def compressFILE(sid,filedata): > tst = StringIO.StringIO() > > #tmp > zip = gzip.GzipFile(str(sid)+'.gz','w',5,tst) According to the docs, it will convert your 'w' into 'wb'. That shouldn't be your problem. However just because I'm paranoid doesn't mean someone isn't out to get you, so change it to 'wb' anyway. It's an extremely good habit to put the 'b' on whenever you are reading or writing binary data. > zip.write(filedata) > > #put every byte in a database > print tst.getvalue() Here's your problem, being over-eager. Compressors that allow you to feed them their input a spoonful at a time will maintain a large amount of "state" and won't finish the job until you call their close() method. Just like if you have a process writing a file to disk, a second process trying to read the file before the first process closes it is not in general guaranteed to see *any* of the file's content, let alone all of it. > > zip.close() > tst.close() OK, now you can inspect the contents of "tst", write it to your database, and then (and only then) worry about BLOBs and embedded nulls and other nasties. HTH, John From tzot at sil-tec.gr Fri Apr 15 05:24:15 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Fri, 15 Apr 2005 12:24:15 +0300 Subject: curses for different terminals References: <219t51pr0he28bke65jl2c1t0k5528qa7m@4ax.com> Message-ID: On Thu, 14 Apr 2005 19:38:26 +0200, rumours say that harold fellermann might have written: >> 1. Are you doing an single process application that produces output on >> many terminals? ie the program is kind of like a service? >gotcha. I want to write a TCP server that handles incoming requests in >threads (one thread per request using SocketServer.ThreadingTCPServer). >Now, I want the server to use curses for client-server communication >(client will be telnet). Thus, my programm runs in a single process >(although several threads) and provides several curses screens (one for >each client.) I see. At first, here is some relevant source from Modules/_cursesmodule.c : """ A number of SysV or ncurses functions don't have wrappers yet; if you need a given function, add it and send a patch. Here's a list of currently unsupported functions: addchnstr addchstr chgat color_set define_key del_curterm delscreen dupwin inchnstr inchstr innstr keyok mcprint mvaddchnstr mvaddchstr mvchgat mvcur mvinchnstr mvinchstr mvinnstr mmvwaddchnstr mvwaddchstr mvwchgat mvwgetnstr mvwinchnstr mvwinchstr mvwinnstr newterm resizeterm restartterm ripoffline scr_dump scr_init scr_restore scr_set scrl set_curterm set_term setterm tgetent tgetflag tgetnum tgetstr tgoto timeout tputs vidattr vidputs waddchnstr waddchstr wchgat wcolor_set winchnstr winchstr winnstr wmouse_trafo wscrl """ So the answer is that, no, you can't use newterm currently. But even if you did, it's not certain that you could use multiterminal ncurses in a multithreaded environment; AFAIK in ncurses you just change the "current" term and then go on with normal curses calls; is there a "current" term per thread, or is there one per process? I couldn't find an answer in the short search I did. I am afraid you will have to make it into a 3-tier arch; that is, your server has the data model and absolutely no curses knowledge, and the clients run a middle application, interfacing ncurses I/O and server protocol. -- TZOTZIOY, I speak England very best. "Be strict when sending and tolerant when receiving." (from RFC1958) I really should keep that in mind when talking with people, actually... From saint.infidel at gmail.com Thu Apr 28 14:35:10 2005 From: saint.infidel at gmail.com (infidel) Date: 28 Apr 2005 11:35:10 -0700 Subject: Getting the sender widget's name in function (Tkinter) In-Reply-To: References: <1114545565.116766.157000@f14g2000cwb.googlegroups.com> <1114547849.644971.191270@f14g2000cwb.googlegroups.com> Message-ID: <1114713310.899563.285880@f14g2000cwb.googlegroups.com> Here's a slight variation of tiissa's solution that gives the callable a reference to the actual widget instead of just it's name: from Tkinter import Tk, Button class say_hello: def __init__(self, widget): self.widget = widget def __call__(self): print 'Hello,', self.widget['text'] def run(): root = Tk() b1 = Button(root, text='Button 1') b1.configure(command=say_hello(b1)) b1.pack() b2 = Button(root, text='Button 2') b2.configure(command=say_hello(b2)) b2.pack() root.mainloop() run() From greg at cosc.canterbury.ac.nz Wed Apr 20 01:47:45 2005 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Wed, 20 Apr 2005 17:47:45 +1200 Subject: packages In-Reply-To: <42640829$0$4565$626a14ce@news.free.fr> References: <4263FC93.5090104@mage.hu> <42640829$0$4565$626a14ce@news.free.fr> Message-ID: <3cm8ofF6o3tkaU1@individual.net> tiissa wrote: > There is: see PEP 8. > http://www.python.org/peps/pep-0008.html > > However, I understood there was no definitive convention hence various > common styles. I think this is a relatively recent development. At the time the tutorial was written, and the older parts of the standard library, there wasn't any established convention. Hopefully the stdlib naming will gradually get ironed out as the oldest bits get deprecated. The tutorial could probably do with being updated, too. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From radam2 at tampabay.rr.com Tue Apr 26 17:32:02 2005 From: radam2 at tampabay.rr.com (Ron) Date: Tue, 26 Apr 2005 21:32:02 GMT Subject: Fast plotting? In-Reply-To: References: Message-ID: Russell E. Owen wrote: > Can anyone recommend a fast cross-platform plotting package for 2-D > plots? > > Our situation: > We are driving an instrument that outputs data at 20Hz. Control is via > an existing Tkinter application (which is being extended for this new > instrument) that runs on unix, mac and windows. We wish to update 5-10 > summary plots at approximately 2 Hz and will be offering controls to > control the instrument and the plots, preferably (but not necessarily) > mixed in with the plots. > > Ideally the package would create plots in the Tkinter application. But > we realize we're unlikely to get the speed we need that way. So we are > willing to have the Tkinter app send data to the plotting package (e.g. > via a socket) and have it display the plots in a separate process. > > We started out with matplotlib, which is a wonderful package (and well > integrated with most or all GUI toolkits). Unfortunately it is just too > slow -- at least when driving plots integrated with the Tkinter app. (It > is getting faster and so are computers, so at some point this will be a > great way to go. But for now...) > > Any suggestions? > > -- Russell Have you looked at BLT? http://sourceforge.net/projects/blt/ http://heim.ifi.uio.no/~hpl/Pmw.Blt/doc/ From cappy2112 at gmail.com Mon Apr 4 01:38:03 2005 From: cappy2112 at gmail.com (Cappy2112) Date: 3 Apr 2005 22:38:03 -0700 Subject: (win32) speedfan api control In-Reply-To: References: Message-ID: <1112593083.067017.31810@l41g2000cwc.googlegroups.com> Nice idea- getting the handle to a control. But how do you know what to pass for wparam , lparam , flags ? BTW- I don't see anything unique to Active Python here. You can do all of this with the Python windows extensions, which can be installed without Active Python. From mwm at mired.org Wed Apr 20 23:00:26 2005 From: mwm at mired.org (Mike Meyer) Date: Wed, 20 Apr 2005 22:00:26 -0500 Subject: Why Python does *SLICING* the way it does?? References: <1113976729.450677.261130@o13g2000cwo.googlegroups.com> <87r7h5lk5a.fsf@wilson.rwth-aachen.de> Message-ID: <86k6mwu94l.fsf@guru.mired.org> Antoon Pardon writes: > Op 2005-04-20, Torsten Bronger schreef : >> Hall?chen! >> >> nde at no.spam.org (Nick Efford) writes: >> >>> seberino at spawar.navy.mil wrote: >>>> Many people I know ask why Python does slicing the way it does..... >>> >>>> Can anyone /please/ give me a good defense/justification??? >>> >>>> I'm referring to why mystring[:4] gives me elements 0, 1, 2 and 3 >>>> but *NOT* mystring[4] (5th element). >>> >>> mystring[:4] can be read as "the first four characters of >>> mystring". If it included mystring[4], you'd have to read it as >>> "the first five characters of mystring", which wouldn't match the >>> appearance of '4' in the slice. >>> >>> [...] >>> >>> It all makes perfect sense when you look at it this way! >> >> Well, also in my experience every variant has its warts. You'll >> never avoid the "i+1" or "i-1" expressions in your indices or loops >> (or your mind ;). >> >> It's interesting to muse about a language that starts at "1" for all >> arrays and strings, as some more or less obsolete languages do. I >> think this is more intuitive, since most people (including >> mathematicians) start counting at "1". The reason for starting at >> "0" is easier memory address calculation, so nothing for really high >> level languages. > > Personnaly I would like to have the choice. Sometimes I prefer to > start at 0, sometimes at 1 and other times at -13 or +7. Some HLLs have had arrays that let you declare the first index as well as the size for decades now. Algol-68, for instance. Modern language still offer such features, but none seem to have been very popular. Of course, in any reasonable OO language, you can roll your own. So the question comes down to whether or not these get into the standard library. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From kasimov at i.com.ua Thu Apr 28 05:10:29 2005 From: kasimov at i.com.ua (Maksim Kasimov) Date: Thu, 28 Apr 2005 12:10:29 +0300 Subject: interactive web graphics References: Message-ID: java are also wide-spread browser plugin with interactive and multimedia capabilities, and java-applets can be written with python (jython) "Diez B. Roggisch" wrote: news:d4p0dh$4lk$05$1 at news.t-online.com... > you are after _might_ be done using macromedia flash - as that is a > wide-spread browser plugin with interactive and multimedia capabilities. > But how to do it in flash I've no idea - after all I'm a pythoneer. > > Alternatively, SVG might be an option - but I'm not sure if its mature and > powerful enough. > > -- > Regards, > > Diez B. Roggisch -- Best regards, Maksim Kasimov mailto: kasimov at i.com.ua From mauriceling at acm.org Wed Apr 27 00:36:15 2005 From: mauriceling at acm.org (Maurice LING) Date: Wed, 27 Apr 2005 14:36:15 +1000 Subject: bytecode non-backcompatibility References: <1114418065.581779.52480@l41g2000cwc.googlegroups.com> <86wtqqm27r.fsf@guru.mired.org> <86is29n9cg.fsf@guru.mired.org> <86ekcxkk15.fsf@guru.mired.org> Message-ID: Mike Meyer wrote: > Maurice LING writes: > > >>The idea of having to release the program or library as source files >>does ring alarms in many executives in corporate world. Less freezing >>the modules (which renders it platform dependent) or using Jython >>(which is not possible when C extensions are involved), there is no >>middle grounds in CPython for distribution without source codes. > > > You're right - and byte codes *as they exist now* aren't an acceptable > middle ground, either. The problem isn't that the interpreter might > change (that can be defeated by distributing the interpreter with the > bytecode files), but that the byte code can be decompiled to get your > Python source back. See http://www.crazy-compilers.com/decompyle/ > for an example. I know that bytecodes can be decompiled back to python source. Similarly Java class files can be decompiled back to Java source files quite easily. IANAL, however, I do think that reverse engineering can be seen as a purposeful act in the eyes of law. I remembered that EU Council Directive 9/250/ECC does explicits the allowable scope of decompilation (for interoperability, preserving expression of ideas, achieving performance of objectives). For companies, I think it is touchy to ask permission to release the source codes even though they may be alright with releasing the same Java JAR file into the community. We do know that regardless of whatever methods of compilation there may be, if some genius is willing to spend sufficient time to crack a program. Even if he has to read the binary codes, it will still break. But that is a wilfull act rather than just looking at the source codes when it is distributed with it. It's just like picking up your money from the ground if you had dropped it as compared to pickpocketing you as compared to hold you at knife point and robbing you...... Same end result but it is viewed differently in the eyes of law and morals. > > Selling byte codes to someone who's worried about shipping source is > selling them snake oil. I think it's unprofessional, at best. > > Message-ID: Charles Krug wrote: > Do I *coughs* simply *coughs* trap the exception created by: > > for v in x: > >when v is a scaler quantity? Sure. Why not? If you're coming from a type-bondage language like C++ or Java, it probabliy feels strange, but it's the Python way. It looks like what you want to catch is TypeError. From steve at holdenweb.com Sat Apr 30 23:00:17 2005 From: steve at holdenweb.com (Steve Holden) Date: Sat, 30 Apr 2005 23:00:17 -0400 Subject: Trying to write CGI script with python... In-Reply-To: <1114907876.724509.122910@z14g2000cwz.googlegroups.com> References: <1114803082.851505.149730@o13g2000cwo.googlegroups.com> <1114806476.477679.150290@f14g2000cwb.googlegroups.com> <1114907876.724509.122910@z14g2000cwz.googlegroups.com> Message-ID: Jason Mobarak wrote: > M.E.Farmer wrote: > >>I found an excellent example that was posted by the F-bot. > > [...] > >>try: >> import myscript >> myscript.main() >>except: >> print "Content-Type:", "text/html" >> print >> file = StringIO.StringIO() > > > Note: it's usually a very bad idea to name -anything- "file" unless you > intentionally want to clobber the name of the built-in file object. > [...] In fairness to the effbot I feel duty bound to suggest that the example may have been produced before file() was a built-in function. The effbot is usually reiable on programming matters. regards Steve -- Steve Holden +1 703 861 4237 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ From franz.steinhaeusler at utanet.at Mon Apr 4 14:53:39 2005 From: franz.steinhaeusler at utanet.at (Franz Steinhäusler) Date: Mon, 04 Apr 2005 20:53:39 +0200 Subject: Eric3 under WinXP Message-ID: Hello NG, (Win XP) I have successfully installed pyqt, but not qtext, which I need to run Eric3. The PyQT demo files run fine. I've downloaded QScintilla, compiled via MS-VC, but (I suppose I need the SIG), to translate or provide the Python interface with pyd Files. Eric complains, that qtext is not found. Has anyone success with getting this to work and how? Many thanks in advance for possible answers, -- Franz Steinh?usler DrPython (Project Developer) http://mitglied.lycos.de/drpython/ From michele.simionato at gmail.com Sat Apr 9 01:18:40 2005 From: michele.simionato at gmail.com (Michele Simionato) Date: 8 Apr 2005 22:18:40 -0700 Subject: Python Equivalent to Java Interfaces? In-Reply-To: References: Message-ID: <1113023920.372623.137890@o13g2000cwo.googlegroups.com> Google for "Hettinger interface checking": the first hit is the cookbook recipe you are looking for. Michele Simionato From hancock at anansispaceworks.com Mon Apr 11 17:02:11 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Mon, 11 Apr 2005 16:02:11 -0500 Subject: Parent module idea dropped? [Python import parent package] In-Reply-To: <42568C37.7090201@geochemsource.com> References: <425628FE.9080901@geochemsource.com> <42568C37.7090201@geochemsource.com> Message-ID: <200504111602.11095.hancock@anansispaceworks.com> On Friday 08 April 2005 08:50 am, Laszlo Zsolt Nagy wrote: > > > So finally I got the answer: there was a "parent package" feature in > > the ni module but it was dropped of its awkwardness. This is not a big > > loss but this is exatly the feature that I need. Is there a person on > > this list who was against the "parent package" idea? He must know the > > answer or a workaround :-) > > I just created a new module that can handle the 'from __.__.SomeModule > import SomeClass' notation. > Keywords: Python import parent package > What is the right place to make it available for others? Well, generally speaking, it seems that most people would stick it on their website and post a link here. Or you could just post the text here as an example (I imagine it's pretty short?). I'd find it useful myself. Cheers, Terry -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From ken at perfect-image.com Sun Apr 10 16:02:27 2005 From: ken at perfect-image.com (Ken Godee) Date: Sun, 10 Apr 2005 13:02:27 -0700 Subject: workaround for generating gui tools In-Reply-To: References: <1113061810.530359.172720@g14g2000cwa.googlegroups.com> <3bqgh6F6larilU1@individual.net> Message-ID: <42598653.4040306@perfect-image.com> Jeremy Bowers wrote: > On Sun, 10 Apr 2005 13:57:26 +0200, Diez B. Roggisch wrote: > > >>>Domain-specific abstractions do that *faster* than GUI designers, not >>>slower. And better, too, since every iteration tends to be fully >>>functional and not just a "let's see what this looks like" prototype. >> >>Can you show me some working, in-use example for that? I _seriously_ doubt >>that the process of rearranging and tuning the layout can be done faster in >>the text-world than with a good designer like qt-designer. But I'm all ears >>for better solutions. > > > Regrettably, no. I have them but they are all unsharable, either because > the real owner would consider them proprietary, or because they are an > unreleased and at the moment unfinished product I can't give the code out > for. > > But I can help some. > This guys gotta be a politician or english major or something! :) 155 lines, 1706 words, 9493 character reply, but his method is so simple he still can't show us an example! The original poster was just asking for an example of how to sub class his code generated form into his program for easy future updates, a "VERY STANDARD" way of doing it. I tried at first to follow this "Great Way" of doing it, but I guess I'm to simple minded, or just got to damed borded. Hey, that's just me. I guess I'll just be stuck zapping out forms with qt designer, the old fashion way. From eldiener_no_spam_here at earthlink.net Fri Apr 8 12:42:17 2005 From: eldiener_no_spam_here at earthlink.net (Edward Diener) Date: Fri, 08 Apr 2005 16:42:17 GMT Subject: Installing Python 2.4 on Linux In-Reply-To: References: Message-ID: John Ridley wrote: > --- Edward Diener wrote: > [snip] > >>I do not know whether this is a Python problem or a Fedora 3 problem >>but >>I thought I would ask here first and see if anybody else had the same >> >>problem. I imagine the problem might exist on other Linux systems. > > > On my Mandrake 10.1 system I have the default python 2.3 installation > plus a separate python 2.4 installation which I compiled from source. > There are two executables (python2.3 and python2.4) in /usr/bin, plus a > hard-link (from python2.4) named python. If necessary, I could switch > back to the default setup by replacing the hard-link with one from > python2.3 - so the system would then have its preferred python version > and I could selectively run python2.4 whenever appropriate. So far, > Mandrake has not complained about using python 2.4 exclusively, so I > might try removing the old installation eventually. (Then again, it's > always handy to keep it for compatibility testing). I need python to be python2.3 else many utilities no longer work. The problem is then using IDLE and pydoc for Python2.4 since neither are .py scripts and need python to be a link to python2.4 and not python2.3. I guess the solution is to write a script a shell script which links python to python2.4, run IDLE let's say, then link back to python2.3. However while I am doing this, other system facilities which depend on python to be python2.3 will be dead. From __peter__ at web.de Sat Apr 30 03:23:45 2005 From: __peter__ at web.de (Peter Otten) Date: Sat, 30 Apr 2005 09:23:45 +0200 Subject: Micro-PEP: str.translate(None) to mean identity translation References: <4272e00c.260731842@news.oz.net> <1114835238.762478.236940@o13g2000cwo.googlegroups.com> Message-ID: M.E.Farmer wrote: > Bengt Richter wrote: >> Just thought None as the first argument would be both handy and > mnemonic, >> signifying no translation, but allowing easy expression of deleting > characters, >> e.g., >> >> s = s.translate(None, 'badcharshere') >> >> Regards, >> Bengt Richter > > What's wrong with : > > s = s.replace('badchars', "") > > It seems obvious to replace a char ( to me anyway ) with a blank > string, rather than to 'translate' it to None. > I am sure you have a reason what am I missing ? > M.E.Farmer >>> s = "NHoBwA RyAoSuB AsAeHeH AiBtH,A CnRoAwD HyBoAuC HdRoCnH'AtB" >>> s.translate(None, "BADCHARS") "Now you see it, now you don't" >>> s.replace("BADCHARS", "") "NHoBwA RyAoSuB AsAeHeH AiBtH,A CnRoAwD HyBoAuC HdRoCnH'AtB" i. e. you have to replace() for every char in "BADCHARS": >>> reduce(lambda x, y: x.replace(y, ""), "BADCHARS", s) "Now you see it, now you don't" +1, btw. Peter From tzot at sil-tec.gr Thu Apr 14 13:17:44 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Thu, 14 Apr 2005 20:17:44 +0300 Subject: curses for different terminals References: Message-ID: <219t51pr0he28bke65jl2c1t0k5528qa7m@4ax.com> On Thu, 14 Apr 2005 18:39:14 +0200, rumours say that harold fellermann might have written: >Hi all, >I want to use curses in a server application that provides a GUI for >telnet clients. Therefore, I need the functionality to open and handle >several >screens. Just to make sure we understand what you want to do: 1. Are you doing an single process application that produces output on many terminals? ie the program is kind of like a service? 2. Are you doing an application with one session per terminal? ie a user starts your app in every terminal, no multi-term output from a single process. 3. Are you doing an application that runs on one terminal but with many "virtual" sessions (or screens), kind of like the `screen(1)` program or the behaviour of the linux or Novell console? >Concerning >http://dickey.his.com/ncurses/ncurses-intro.html#init >this can be done using the function newterm(type,ofp,ifp). However, this >function seems not to be defined in the python library. Does anyone know >how this can be done in python? Select one of the above, or describe more the desired situation if I didn't cover your case, and we will try to help you more. -- TZOTZIOY, I speak England very best. "Be strict when sending and tolerant when receiving." (from RFC1958) I really should keep that in mind when talking with people, actually... From danb_83 at yahoo.com Fri Apr 8 04:38:35 2005 From: danb_83 at yahoo.com (Dan Bishop) Date: 8 Apr 2005 01:38:35 -0700 Subject: curious problem with large numbers References: Message-ID: <1112949515.151213.274340@o13g2000cwo.googlegroups.com> Chris Fonnesbeck wrote: > I have been developing a python module for Markov chain Monte Carlo > estimation, in which I frequently compare variable values with a very > large number, that I arbitrarily define as: > > inf = 1e10000 Don't forget that you can write your own Infinity. (Warning: Buggy code, especially for unsigned Infinity) class Infinity(object): def __init__(self, sign=1): self._sign = cmp(sign, 0) def __repr__(self): return "Infinity(%d)" % self._sign def __str__(self): if self._sign == 0: return "UInf" elif self._sign < 0: return "-Inf" else: return "+Inf" def __eq__(self, other): return isinstance(other, Infinity) and self._sign == other._sign def __ne__(self, other): return not (self == other) def __le__(self, other): if self._sign == 0: raise ValueError("Unsigned Infinity is incomparable") elif self._sign < 0: return True else: return False def __ge__(self, other): if self._sign == 0: raise ValueError("Unsigned Infinity is incomparable") elif self._sign < 0: return False else: return True def __lt__(self, other): return not (self >= other) def __gt__(self, other): return not (self <= other) def __add__(self, other): if isinstance(other, Infinity): if self._sign == other._sign: return self else: raise ValueError("%s + %s is undefined" % (self, other)) else: return self __radd__ = __add__ def __neg__(self): return Infinity(-self._sign) def __sub__(self, other): return self + (-other) def __rsub__(self, other): return -self def __mul__(self, other): return Infinity(self._sign * other) __rmul__ = __mul__ def __div__(self, other): if instance(other, Infinity): raise ValueError("Inf/Inf is undefined") else: return Infinity(self._sign * other) __truediv__ = __div__ __floordiv__ = __div__ def __rtruediv__(self, other): return 0 __rdiv__ = __rtruediv__ def __rfloordiv__(self, other): if self._sign * cmp(other, 0) < 0: return -1 else: return 0 POSITIVE_INFINITY = Infinity(1) NEGATIVE_INFINITY = Infinity(-1) UNSIGNED_INFINITY = Infinity(0) From fuzzyman at gmail.com Tue Apr 5 11:51:54 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 5 Apr 2005 08:51:54 -0700 Subject: Python Google Server In-Reply-To: <1112696434.623557.97000@g14g2000cwa.googlegroups.com> References: <1112696434.623557.97000@g14g2000cwa.googlegroups.com> Message-ID: <1112716314.193243.151820@f14g2000cwb.googlegroups.com> Note - there are a couple of *minor* chanegs to this. See the online python cookbok, the thread on comp.lang.python or http://www.voidspace.org.uk/python/weblog/index.shtml From jcribbs at twmi.rr.com Tue Apr 26 20:36:41 2005 From: jcribbs at twmi.rr.com (Jamey Cribbs) Date: Tue, 26 Apr 2005 20:36:41 -0400 Subject: ANN: KirbyBase 1.8.1 Message-ID: <426EDE99.5090402@twmi.rr.com> KirbyBase is a simple, plain-text, database management system written in Python. It can be used either embedded in a python script or in a client/server, multi-user mode. You use python code to express your queries instead of having to use another language such as SQL. KirbyBase is disk-based, not memory-based. Database changes are immediately written to disk. You can find more information on KirbyBase at: http://www.netpromi.com/kirbybase.html You can download KirbyBase for Python at: http://www.netpromi.com/files/KirbyBase_Python_1.8.1.zip The credit for this release goes entirely to Pierre Quentel, the author of Karrigell (http://karrigell.sourceforge.net). Pierre contributed every code change that made it into this version. Thanks! Changes in Version 1.8.1: -Added the ability to select, update, delete multiple records by specifying a list of record numbers. -Cleaned up the internals of _getMatchesByRecno by not splitting the record line into fields if user is selecting all records, and by using a generator to return matches instead of building a list of matches and returning the whole list. Jamey Cribbs jcribbs at twmi.rr.com From phil at riverbankcomputing.co.uk Thu Apr 28 02:29:27 2005 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Thu, 28 Apr 2005 07:29:27 +0100 Subject: pyqt and Eric 3 In-Reply-To: References: Message-ID: <200504280729.27459.phil@riverbankcomputing.co.uk> On Thursday 28 April 2005 3:46 am, ChrisH wrote: > In article , > secun at yahoo.com says... > > > Are there any Eric 3 users out there? > > > > I've been thinking about trying it. > > > > Also, if I write scripts for internal use only at my company, do I have > > to purchase a Qt or pyqt license? > > > > Thanks for the info! > > Chris > > Oops.. I forgot to say I'm writing code for Windows. Until the GPL versions of Qt4 and PyQt4 are available for Windows (and eric has been ported to it) you will need Qt and PyQt licenses. Phil From jepler at unpythonic.net Wed Apr 6 11:03:48 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 6 Apr 2005 10:03:48 -0500 Subject: Resticted mode still active (error?) In-Reply-To: References: Message-ID: <20050406150348.GF12835@unpythonic.net> Is there a script that causes this problem, without using mod_python or jepp? If so, please attach it to the sourceforge bug. http://sourceforge.net/tracker/index.php?func=detail&aid=1163563&group_id=5470&atid=105470 -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From kretino at net.hr Thu Apr 21 04:01:54 2005 From: kretino at net.hr (jozo) Date: Thu, 21 Apr 2005 10:01:54 +0200 Subject: python LEX Message-ID: I have to work on python lexical definition in Lex. I spent lots of my time to find regular expresions written for Lex of Python language but nothing. Can somebody help me? I nEED hELP From strombrg at dcs.nac.uci.edu Mon Apr 4 17:53:01 2005 From: strombrg at dcs.nac.uci.edu (Dan Stromberg) Date: Mon, 04 Apr 2005 21:53:01 GMT Subject: sparse sets of integers? Message-ID: Does anyone have a python implementation (or python C/C+ extension) that would allow me to perform set operations (union, intersection, difference, number of elements, &c) over very large collections of integers? Some of the sets may have over 10**11 (probably less than 10**13 though) integers in them, but there will tend to be runs of integers being included or not included, so there might be 10**5 consecutive integers included, then 10**4 that are not included, and then another 10**6 that are. Is there such code already available? I wrote something like this in C ages ago, but: 1) I no longer have the code 2) Who wants to work in C if you can do it fast enough in python anyway? :) Thanks! From bj_666 at gmx.net Sat Apr 2 11:33:47 2005 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sat, 02 Apr 2005 18:33:47 +0200 Subject: Performance issue References: <424ec521$0$149$e4fe514c@news.xs4all.nl> Message-ID: In <424ec521$0$149$e4fe514c at news.xs4all.nl>, Irmen de Jong wrote: >> words = file.splitlines() > > You can obtain this list without reading the file in its entirety, > by using the readlines method of file objects: > > words=open("words.txt").readlines() This leaves the newline characters at the end of each line while `str.splitlines()` removes them. Ciao, Marc 'BlackJack' Rintsch From paul at fxtech.com Thu Apr 28 11:14:45 2005 From: paul at fxtech.com (Paul Miller) Date: Thu, 28 Apr 2005 10:14:45 -0500 Subject: anonymous functions/expressions without lambda? Message-ID: I see lambda is "going away", so I want to use something that will be around for awhile. All I want to do is provide an "inline function" as an argument to another function. For example, let's say I have a function which binds a key to a function call. I want to do something "simple" in this function call, and I have a lot of bindings, so I don't want to have a ton of tiny little functions scattered around: def setVarTo1(): foo.var = 1 def setVarTo2(): foo.var = 2 bind('a', setVarTo1) bind('b', setVarTo2) Instead, I'd like to do something like this: bind('a', foo.var = 1) bind('b', foo.var = 2) What's the recommended way to do something like this? Note that the bind function is implemented in "C", and I am embedding the interpreter. From ahmedt at gmail.com Wed Apr 20 15:40:08 2005 From: ahmedt at gmail.com (ahmedt at gmail.com) Date: 20 Apr 2005 12:40:08 -0700 Subject: What's the difference between these 2 statements? In-Reply-To: <4266ad9f$0$14218$636a15ce@news.free.fr> References: <70c4ec00.0504201052.30227e93@posting.google.com> <3cnmpbF6gnlkhU1@individual.net> <4266ad9f$0$14218$636a15ce@news.free.fr> Message-ID: <1114026007.999930.12850@f14g2000cwb.googlegroups.com> I'm sorry, I'm not really following your logic. Can you supply the statement with the three parameters ? so if I want to reverse it fully using s[len(s)-1:x:-1] what would x be or is it impossible to express it in this way ? Thanks, AT From sjmachin at lexicon.net Fri Apr 29 18:10:33 2005 From: sjmachin at lexicon.net (John Machin) Date: Sat, 30 Apr 2005 08:10:33 +1000 Subject: Best way to parse file into db-type layout? References: <32r471h0nnq5aieeip6p83bpo54fcv9ooq@4ax.com> Message-ID: On Fri, 29 Apr 2005 18:54:54 GMT, Peter A. Schott wrote: >That looks promising. > The field numbers are pre-defined at the mainframe level. Of course. Have you managed to acquire a copy of the documentation, or do you have to reverse-engineer it? >This may help me get to my ultimate goal which is to pump these into a DB on a >row-by-row basis ( :-P ) That's your *ultimate* goal? Are you running a retro-computing museum or something? Don't you want to *USE* the data? > I'll have to do some playing around with this. I >knew that it looked like a dictionary, but wasn't sure how best to handle this. > >One follow-up question: I'll end up getting multiple records for each "type". What does that mean?? If it means that more than one customer will get the "please settle your account" letter, and more than one customer will get the "please buy a spangled fritzolator, only $9.99" letter, you are stating the obvious -- otherwise, please explain. >Would I be referencing these by row[#][field#]? Not too sure what you mean by that -- whether you can get away with a (read a row, write a row) way of handling the data depends on its structure (like what are the relationships if any between different rows) and what you want to do with it -- both murky concepts at the moment. > >Minor revision to the format is that starts like: >###,1,1,val_1,.... How often do these "minor revisions" happen? How flexible do you have to be? And the extra "1" means what? Is it ever any other number? > > >I think right now the plan is to parse through the file and insert the pairs >directly into a DB table. Something like RowID, LetterType, date, Field#, >Value. Again, I'd recommend you lose the "Field#" in favour of a better representation, ASAP. > I can get RowID and LetterType overall, date is a constant, the rest >would involve reading each pair and inserting both values into the table. Time >to hit the books a little more to get up to speed on all of this. What you need is (a) a clear appreciation of what you are trying to do with the data at a high level (b) then develop an understanding of what is the underlying data model (c) then and only then worry about technical details. Good luck, John From __peter__ at web.de Wed Apr 27 03:27:09 2005 From: __peter__ at web.de (Peter Otten) Date: Wed, 27 Apr 2005 09:27:09 +0200 Subject: python equivalent of php implode References: <8664y8lyb2.fsf@guru.mired.org> Message-ID: Maxim Kasimov wrote: > i'm tying to run example, and then get a traceback. am i something missed? > > mysql> create table tmp_tmp (id int not null auto_increment primary key, > sd varchar(255) not null default '', si int not null default 1); > >>>> import MySQLdb >>>> db = MySQLdb.connect("localhost", "login", "password", "dbname") >>>> c = db.cursor() >>>> query_param = { > ... 'sd' : 'somedata', > ... 'si' : 2, > ... } >>>> table = 'tmp_tmp' >>>> keys = query_param.keys() >>>> values = query_param.values() >>>> sql = "INSERT INTO %s (%s) values (%s)" % (table, ", ".join(keys), ", > ".join(["?"] * len(keys)) ) >>>> c.execute(sql, values) > Traceback (most recent call last): > File "", line 1, in ? > File "/usr/local/lib/python2.2/site-packages/MySQLdb/cursors.py", line > 95, > in execute > return self._execute(query, args) > File "/usr/local/lib/python2.2/site-packages/MySQLdb/cursors.py", line > 108, in _execute > self.errorhandler(self, ProgrammingError, m.args[0]) > File "/usr/local/lib/python2.2/site-packages/MySQLdb/connections.py", > line > 33, in defaulterrorhandler > raise errorclass, errorvalue > _mysql_exceptions.ProgrammingError: not all arguments converted Try another paramstyle (see http://python.org/peps/pep-0249.html), e. g. ... ",".join(["%s"] * len(keys)) ... instead of ... ",".join(["?"] * len(keys)) ... Peter From vincent at visualtrans.de Mon Apr 11 01:08:17 2005 From: vincent at visualtrans.de (vincent wehren) Date: Mon, 11 Apr 2005 07:08:17 +0200 Subject: help with wxPython and wxGrid References: Message-ID: "Sam the Cat" schrieb im Newsbeitrag news:LNWdnelNabejW8TfRVn-tg at comcast.com... | using "from wxPython.wx import *" under python2.3 I cannot seem to find the | wxGrid class -- it says its undefined -- am I missing something obvious ? I | know the globalspace import is not the best, but that how I got started | ;) -- any help owuld be appreciated | | Try: from wxPython.wx import * from wxPython.grid import * or import wx import wx.grid -- Vincent Wehren From rune.strand at gmail.com Tue Apr 12 18:06:30 2005 From: rune.strand at gmail.com (runes) Date: 12 Apr 2005 15:06:30 -0700 Subject: Python documentation moronicities (continued) In-Reply-To: <1113301533.054410.203710@z14g2000cwz.googlegroups.com> References: <1113301533.054410.203710@z14g2000cwz.googlegroups.com> Message-ID: <1113340181.174797.132250@f14g2000cwb.googlegroups.com> > why cannot this piece of shit writing give a single example of usage? Actually, I can understand your frustration even if you should enhance your vocabulary slightly. I often struggle with the Python documnetation myself and I can't understand why a couple of examples are so hard to give. When I laernt PHP I used the resources at php.net exclusively, and that's because of the plenty of examples and the newbie friendlyness. Recently I struggled with the regex module and found the the documentation being close to worthless. I'm not a CS guy, I may have a harder fight grasping concepts. The re documentation, like much Python documentation seems to be written with other people than my kind in mind. Luckily I found this regex howto: http://www.amk.ca/python/howto/regex/ and that helped a lot. In addition, Mr. Magnus Lie Hetland coincidentally posted a question on this list that got answers that helped me out. (http://groups-beta.google.com/group/comp.lang.python/browse_frm/thread/734cdb90078d5298/fc4c56ca66231d7f?q=Hetland&rnum=2#fc4c56ca66231d7f) From steve at holdenweb.com Tue Apr 5 03:32:47 2005 From: steve at holdenweb.com (Steve Holden) Date: Tue, 05 Apr 2005 03:32:47 -0400 Subject: Insert database rows from CSV file In-Reply-To: References: Message-ID: Dennis Lee Bieber wrote: > On Mon, 4 Apr 2005 15:54:37 -0700, "3c273" declaimed > the following in comp.lang.python: > > >>Thanks for the link, but this is the step I am trying to save (for someone >>else). Every time he goes to run a report, he must stop and import any new >>csv files. Since the files are generated by a Python script, I thought I > > > That information wasn't supplied in the original message. Your > original post implied that the data source /was/ the CSV file... > > Show us the code segment that is writing the CSV file, and we > can probably show you the DB-API equivalent for "writing" a new record > to the table. > > For short however: > > aCustomer = "Customer1" > theWidget = "Widget1" > aQuantity = 1000 > > # I'm presuming the table only has the three columns, since you didn't > list fields > cursor.execute(""" INSERT INTO "Table1" Values (%s, %s, %s) """, > (aCustomer, theWidget, aQuantity)) Beware, however, that the parameter markers ("%s" in the example above) will depend on which database module you use - some modules will expect "?", for example. This depends on the module's "paramstyle". Also, don't forget to commit the changes! regards Steve -- Steve Holden +1 703 861 4237 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ From bokr at oz.net Sun Apr 24 01:01:32 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 24 Apr 2005 05:01:32 GMT Subject: Variables References: <426B0283.40602@cloudthunder.com> Message-ID: <426b255d.375304108@news.oz.net> On Sat, 23 Apr 2005 22:45:14 -0400, Richard Blackwood wrote: >Robert Kern wrote: > >> Richard Blackwood wrote: >> >>> To All: >>> >>> Folks, I need your help. I have a friend who claims that if I write: >>> >>> foo = 5 >>> >>> then foo is NOT a variable, necessarily. If you guys can define for >>> me what a variable is and what qualifications you have to back you, I >>> can pass this along to, hopefully, convince him that foo is indeed a >>> variable. >> >> >> None of us can do that unless you tell us what he thinks the word >> "variable" means. The terminology is a bit fluid. I suspect that your >> friend applying a somewhat restricted notion of "variable" that >> coincides with the behavior of variables in some other language. >> >Indeed, this language is math. My friend says that foo is a constant and >necessarily not a variable. If I had written foo = raw_input(), he would >say that foo is a variable. Which is perfectly fine except that he >insists that since programming came from math, the concept of variable >is necessarily the identical. This can not be true. For example, I may >define foo as being a dictionary, but I can not do this within math >because there is no concept of dictionaries within mathematics; yet foo >is a variable, a name bound to a value which can change. Maybe he doesn't know that foo = 5 in Python is not an equation as in math, but a Python source language statement to be translated to a step in some processing sequence. Tell him in Python foo is a member of one set and 5 is a member of another, and foo = 5 expresses the step of putting them into correspondence to define a mapping, not declaring them equal. Even in math notation, ISTM important to distinguish between a finger and what it may for the moment be pointing at. Regards, Bengt Richter From storchaka at ksf.kiev.ua Mon Apr 18 11:30:50 2005 From: storchaka at ksf.kiev.ua (Serhiy Storchaka) Date: Mon, 18 Apr 2005 18:30:50 +0300 Subject: pre-PEP: Simple Thunks In-Reply-To: References: <3jl2615c5pckknicc32ccv2cktue3nh603@4ax.com> Message-ID: Brian Sabbey wrote: > do f in with_file('file.txt'): > print f.read() def with_file(filename): f = open(filename) yield f f.close() for f in with_file('file.txt'): print f.read() > t = "no file read yet" > do f in with_file('file.txt'): > t = f.read() t = "no file read yet" for f in with_file('file.txt'): t = f.read() -- Serhiy Storchaka From steve at holdenweb.com Mon Apr 4 11:20:34 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 04 Apr 2005 11:20:34 -0400 Subject: Newsgroup Programming In-Reply-To: References: Message-ID: Chuck wrote: > I've found and used the nntplib module for newgroup programming. Can anyone > suggest a library, technique or reference on how to combine mutliple > messages with attachments such as mp3's, .wmv, *.avi, etc.? > > Are you talking about reconstructing a long post like a .avi that has been split up into separate messages? If so then you'll need to concatenate all the message bodies and use uudecode on the result, I suspect. regards Steve -- Steve Holden +1 703 861 4237 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ From harold.fellermann at upf.edu Thu Apr 7 07:22:04 2005 From: harold.fellermann at upf.edu (harold fellermann) Date: Thu, 7 Apr 2005 13:22:04 +0200 Subject: richcmpfunc semantics In-Reply-To: <3bkgpnF6d50ppU1@individual.net> References: <3bkgpnF6d50ppU1@individual.net> Message-ID: Thank you Greg, I figured most of it out in the meantime, myself. I only differ from you in one point. >> What has to be done, if the function is invoked for an operator >> I don't want to define? > > Return Py_NotImplemented. (Note that's return, *not* raise.) I used PyErr_BadArgument(); return NULL; instead. What is the difference between the two and which one is to prefer. Also, do you need to increment the reference count of Py_NotImeplemented before returning it? Thanks, - harold - -- I like pigs. Dogs look up to us. Cats look down to us. Pigs treat us as equal. -- Winston Churchill From rkoida at yahoo.com Tue Apr 19 23:49:31 2005 From: rkoida at yahoo.com (rkoida at yahoo.com) Date: 19 Apr 2005 20:49:31 -0700 Subject: How to Convert a makefile to Python Script Message-ID: <1113968971.081613.140640@l41g2000cwc.googlegroups.com> Hello All I am working on a Problem to convert makefile in to a python script. Are there any Modules? Please try to comment. Thanks rkoida From sjmachin at lexicon.net Fri Apr 29 18:59:11 2005 From: sjmachin at lexicon.net (John Machin) Date: Sat, 30 Apr 2005 08:59:11 +1000 Subject: Best way to parse file into db-type layout? References: <7v1371pn9gvsh52m7nld6ddjm9b9k3elgf@4ax.com> Message-ID: On Fri, 29 Apr 2005 23:21:43 +0100, Michael Hoffman wrote: >John Machin wrote: >> [Michael Hoffman]: >> >>>for row in csv.reader(fileinput.input()): >> >> csv.reader requires that if the first arg is a file that it be opened >> in binary mode. > >fileinput.input() is not a file. Hair-splitter. fileinput opens its files in text mode. It's an awk simulation and shouldn't be used for real-world data. > >I have tested this code and it works fine for the provided example. Well I've got news for you: real-world data has embedded CRs, LFs and (worst of all) ^Zs often enough, and you won't find them mentioned in any documentation, nor find them in examples. From sjmachin at lexicon.net Wed Apr 27 08:15:56 2005 From: sjmachin at lexicon.net (John Machin) Date: Wed, 27 Apr 2005 22:15:56 +1000 Subject: kdialog and unicode References: <8d7dabda.0504261239.37952804@posting.google.com> <8aft611878hr6d3an0n55rbk23mm71hpht@4ax.com> <1114568185.015176.238000@g14g2000cwa.googlegroups.com> Message-ID: On 26 Apr 2005 19:16:25 -0700, dmbkiwi at gmail.com wrote: > >John Machin wrote: >> On 26 Apr 2005 13:39:26 -0700, dmbkiwi at gmail.com (dumbkiwi) wrote: >> >> >Peter Otten <__peter__ at web.de> wrote in message >news:... >> >> Dumbkiwi wrote: >> >> >> >> >> Just encode the data in the target encoding before passing it >to >> >> >> os.popen(): >> >> > >> >Anyway, from your post, I've done some more digging, and found the >> >command: >> > >> >sys.setappdefaultencoding() >> > >> >which I've used, and it's fixed the problem (I think). >> > >> >> Dumb Kiwi, eh? Maybe not so dumb -- where'd you find >> sys.setappdefaultencoding()? I'm just a dumb Aussie [1]; I looked in >> the 2.4.1 docs and also did import sys; dir(sys) and I can't spot it. > >Hmmm. See post above, seems to be something generated by eric3. So >this may not be the fix I'm looking for. > >> >> In any case, how could the magical sys.setappdefaultencoding() fix >> your problem? From your description, your problem appeared to be that >> you didn't know what encoding to use. > >I knew what encoding to use, Would you mind telling us (a) what that encoding is (b) how you came to that knowledge (c) why you just didn't do test = os.popen('kdialog --inputbox %s' %(data.encode('that_encoding'))) instead of test = os.popen('kdialog --inputbox %s' %(data.encode('utf-8'))) > the problem was that the text was being >passed to kdialog as ascii. It wasn't being passed to kdialog; there was an attempt which failed. > The .encode('utf-8') at least allows >kdialog to run, but the text still looks like crap. Using >sys.setappdefaultencoding() seemed to help. The text looked a bit >better - although not entirely perfect - but I think that's because the >font I was using didn't have the correct characters (they came up as >square boxes). And the font you *were* using is what? And the font you are now using is what? What facilities do you have to use different fonts? >> >> What is the essential difference between >> >> send(u_data.encode('polish')) >> >> and >> >> sys.setappdefaultencoding('polish') >> ... >> send(u_data) > >Not sure - I'm new to character encoding, and most of this seems like >black magic to me. The essential difference is that setting a default encoding is a daft idea. > >> >> [1]: Now that's *TWO* contenders for TautologyOTW :-) >> Before I retract that back to one contender, I'll give it one more shot: 1. Your data: you say it is Polish text, and is utf-8. This implies that it is in Unicode, encoded as utf-8. What evidence do you have? Have you been able to display it anywhere so that it "looks good"? If it's not confidential, can you show us a dump of the first say 100 bytes of text, in an unambiguous form, like this: print repr(open('polish.text', 'rb').read(100)) 2. Your script: You say "I then manipulate the data to break it down into text snippets" - uh-huh ... *what* manipulations? Care to tell us? Care to show us the code? 3. kdialog: I know nothing of KDE and its toolkit. I would expect either (a) it should take utf-8 and be able to display *any* of the first 64K (nominal) Unicode characters, given a Unicode font or (b) you can encode your data in a legacy charset, *AND* tell it what that charset is, and have a corresponding font or (c) you have both options. Which is correct, and what are the details of how you can tell kdialog what to do -- configuration? command-line arguments? HTHYTHYS, John From jacob at cd.chalmers.se Sun Apr 3 18:57:33 2005 From: jacob at cd.chalmers.se (Jacob Hallen) Date: 3 Apr 2005 22:57:33 GMT Subject: Europython 2005 is now accepting talk submissions Message-ID: Europython 2005 is now accepting talk submissions! Find out more at http://www.europython.org Just as last year, we have a Refereed Paper Track. Last day for proposing a refereed paper is 22 April 2005. For regular talks, we have the following tracks: Business Education Python Frameworks Python Language Science Social skills and General Topics Zope/Plone We also have a special track for "Misfits" this year. It is for any topic that is Python related but doesn't fit in any of the above categories. Last day for submitting talks to the regular tracks is 1 May 2005. On top of this, we will have two tracks of Lightning Talks; one for Zope/plone and one for other topics. You can register talks for these all the time until the Lightning Talk sessions end, or the schedule is filled, whichever comes first. Europython 2005 will be held 27-29 June at the Chalmers University of Techchnology, G?teborg, Sweden. Registration will open in mid-April. We hope this will become the best Europython Conference ever! With your help it can. We are still seeking volunteers to help us with a number of things. We have a recent vacancy as track chair for Python Frameworks, and it is not too late to revive the Applications Track. We also need people to help out in the reception during the conference. Send an email to europython at python.org. Jacob Hall?n Head organiser -- From finite.automaton at gmail.com Tue Apr 26 16:58:23 2005 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: 26 Apr 2005 13:58:23 -0700 Subject: Pythonic way to do static local variables? References: <_xgbe.128633$cg1.54987@bgtnsc04-news.ops.worldnet.att.net> Message-ID: <1114549103.844774.178070@o13g2000cwo.googlegroups.com> A quick, hackish way to keep a static variable is to declare it as a parameter and give it a default value. The parameter list is evaluated when the function is compiled, not when it is called. The underscores are added as per convention to indicate that the variable is special/private. Example- def cumulative_sum(arg, __static__ = []): __static__.append(arg) return reduce(lambda a,b: a + b, __static__) #------------------- >>> cumulative_sum(1) 1 >>> cumulative_sum(1) 2 >>> cumulative_sum(1) 3 From fred.dixon at gmail.com Tue Apr 12 21:08:51 2005 From: fred.dixon at gmail.com (fred.dixon) Date: 12 Apr 2005 18:08:51 -0700 Subject: sort of a beginner question about globals Message-ID: <1113354531.380490.81190@z14g2000cwz.googlegroups.com> i have read the book and searched the group too ---------------------------------------------- im not gettin it. i want to read a global (OPTIONS) from file1 from a class method (func1) in file2 i want to understand how this works. ---------------------------------------------- #file1.py import file2 import sys OPTION = sys.argv[1:] pass a=global2.class1() a.func1() #file2.py import __main__ pass class class1: . def func1(self): . pass ------------------------------------------- From hoel at gl-group.com Mon Apr 18 08:00:33 2005 From: hoel at gl-group.com (=?iso-8859-15?q?Berthold_H=F6llmann?=) Date: Mon, 18 Apr 2005 14:00:33 +0200 Subject: compiling python 2.4.1 on Linux_X86_64 using PGI compiler fails Message-ID: I am trying to compile Python on an Opteron machine using the PGI C compiler under Linux. I use: CC=pgcc ./configure --prefix=/usr/local/gltools/python/Python-2.2.1 \ --exec-prefix=/usr/local/gltools/python/Python-2.2.1/$GL_ARCH \ --with-cxx=pgCC but make fails with: pgCC -Xlinker -export-dynamic -o python \ Modules/ccpython.o \ libpython2.4.a -lpthread -ldl -lpthread -lutil -lm libpython2.4.a(posixmodule.o)(.text+0x38d6): In function `posix_tmpnam': : warning: the use of `tmpnam_r' is dangerous, better use `mkstemp' libpython2.4.a(posixmodule.o)(.text+0x3841): In function `posix_tempnam': : warning: the use of `tempnam' is dangerous, better use `mkstemp' case $MAKEFLAGS in \ *-s*) CC='pgcc' LDSHARED='pgcc -shared' OPT='-DNDEBUG -O' ./python -E ./setup.py -q build;; \ *) CC='pgcc' LDSHARED='pgcc -shared' OPT='-DNDEBUG -O' ./python -E ./setup.py build;; \ esac make: *** [sharedmods] Error 139 and issuing the last command from the command line gives: > CC='pgcc' LDSHARED='pgcc -shared' OPT='-DNDEBUG -O' ./python -E ./setup.py build Segmentation fault (core dumped) This is with PGI 5.2 and 6.0. Has anyone compiled python successfully using PGI compilers under 64 bit Linux. If yes, what are the neccesarry switches? Thanks Berthold -- hoel at GL-Group.com __ Address: G / \ L Germanischer Lloyd phone: +49-40-36149-7374 -+----+- Vorsetzen 35 P.O.Box 111606 fax : +49-40-36149-7320 \__/ D-20459 Hamburg D-20416 Hamburg From philippe at philippecmartin.com Sun Apr 24 12:54:20 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Sun, 24 Apr 2005 16:54:20 GMT Subject: Using Ming on Windows References: Message-ID: <0bQae.51$461.1@newssvr11.news.prodigy.com> I never managed to link my python extensions (mingw .a) with python and broke down and bought Visual/C++ as it is the compiler used by Python. Yet some people seem to have managed: http://uucode.com/texts/python-mingw/python-mingw.html Regards, Philippe Jack Diederich wrote: > On Sat, Apr 23, 2005 at 05:13:29PM -0300, Andr? Roberge wrote: >> I tried to install Ming >> (http://sourceforge.net/projects/ming/) >> on Windows to use with Python *but* >> I can't [/don't know how to] use "make" to install it. >> >> Does anyone know where I could find a ready-made compiled >> version for Windows to just "put in" my site-packages directory. >> >> Any help would be appreciated. >> > Ming seems to be abandoded/unsupported. Use groups.google.com to > find some hints on how to install it. I've done it on linux, but > never tried on windows (why would I?) and replied with some > suggestions last time it came up on c.l.py > > -jackdied From sizer at nospam.com Tue Apr 19 16:42:03 2005 From: sizer at nospam.com (Sizer) Date: 19 Apr 2005 15:42:03 -0500 Subject: Extending base class methods References: <1113919270.802463.54310@l41g2000cwc.googlegroups.com> Message-ID: henrikpierrou at hotmail.com wrote in news:1113919270.802463.54310 at l41g2000cwc.googlegroups.com: > Any ideas why this does not work? I get the error "TypeError: unbound > method printer() must be called with Field_Collection instance as > first argument (got MSD instance instead)"): > > > #====================================================================== > =============== class Field_Collection: > fieldList = [] > > def add(self, name, size, compression, responseValue, value, > description): > self.fieldList.append( Field(name, size, compression, > responseValue, value, description) ) > > def update(self): > print "updating field" > > def get(self): > print "getting field" > > def printer(self): > for x in self.fieldList: > x.printer() > > > #====================================================================== > =============== > > > class MSD(Field_Collection): > standard = "" > decField = "" > > def printer(self): > print "Standard: " + self.standard > print "decField: " + self.decField > Field_Collection.printer(self) > > #====================================================================== > =============== > > w2k, python 2.3 > I added these lines to your code: foo = MSD() foo.printer() And it worked perfectly (python 2.3.3). You would get that error if you accidentally did something like: foo = MSD() MSD.printer() # oops, should be foo.printer() From mwm at mired.org Tue Apr 26 22:55:13 2005 From: mwm at mired.org (Mike Meyer) Date: Tue, 26 Apr 2005 21:55:13 -0500 Subject: what is the best way to determine system OS? References: <1114436211.942212.203790@f14g2000cwb.googlegroups.com> <868y37osc7.fsf@guru.mired.org> <86y8b6o8pw.fsf@guru.mired.org> <1114487173.272526.13670@o13g2000cwo.googlegroups.com> <86acnln8wi.fsf@guru.mired.org> Message-ID: <86acnlkjxq.fsf@guru.mired.org> Roel Schroeven writes: > Mike Meyer wrote: >>>In that case, it seems to be a better idea to check the version of >>>vmstat that's on the system. At least, I presume that such differences >>>in behaviour can be deduced from the vmstat version string. >> Hmm. That doesn't seem to work here: >> guru% vmstat --version >> vmstat: illegal option -- - >> usage: vmstat [-aimsz] [-c count] [-M core [-N system]] [-w wait] >> [-n devs] [disks] > > The version on Debian Woody uses -V: > > $ vmstat -V > procps version 2.0.7 > > Apparently it is quite a different program than yours; the -V option > is cleary labeled in the man page, and it supports much less options: -V doesn't work here: guru% vmstat -V vmstat: illegal option -- V usage: vmstat [-aimsz] [-c count] [-M core [-N system]] [-w wait] [-n devs] [disks] Of course, you could use the fact that various things *don't* work as a hint to what version of vmstat you have. I'd be interested in what other BSD's did - especially with "what $(which vmstat)". http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From tpherndon at gmail.com Sun Apr 17 19:18:54 2005 From: tpherndon at gmail.com (Peter Herndon) Date: 17 Apr 2005 16:18:54 -0700 Subject: MS SQL Server/ODBC package for Python In-Reply-To: <7tj2619vr3b49iealucjcqacic9d067ndr@4ax.com> References: <425faff2$0$298$ed9e5944@reading.news.pipex.net> <1113579774.353462.30960@l41g2000cwc.googlegroups.com> <42603197.9090002@egenix.com> <7tj2619vr3b49iealucjcqacic9d067ndr@4ax.com> Message-ID: <1113779934.308133.27690@z14g2000cwz.googlegroups.com> I switched around the order, both in the actual application and in my tests as replied to Francois Lepoutre above. Results were consistent, after the first run of any given test, which unsurprisingly took a bit longer. From nospam at here.com Wed Apr 20 13:40:56 2005 From: nospam at here.com (Matt Feinstein) Date: Wed, 20 Apr 2005 13:40:56 -0400 Subject: goto statement References: Message-ID: On Wed, 20 Apr 2005 10:23:58 +0100 (BST), praba kar wrote: >Dear All, > > In Python what is equivalent to goto statement I'd like to that implemented in an interpreted language. Requires some time travel. Matt Feinstein -- There is no virtue in believing something that can be proved to be true. From mage at mage.hu Thu Apr 21 10:19:27 2005 From: mage at mage.hu (Mage) Date: Thu, 21 Apr 2005 16:19:27 +0200 Subject: goto statement In-Reply-To: References: <20050420092359.81900.qmail@web8409.mail.in.yahoo.com> <42664190.6010507@i.com.ua> <87vf6hlkix.fsf@wilson.rwth-aachen.de> Message-ID: <4267B66F.5040504@mage.hu> Michael Soulier wrote: >On 4/20/05, Maxim Kasimov wrote: > > >>but what if i just can't to do this becouse i'm working thrue ssh, and have to use >>only installed editors (such as vi) >> >> > >Then learn to use vi. > >:.,+10s/^/# >" comment the next 10 lines > > Or if you don't like that you can use sftpfs with gui editor. Mage From noemail at noemail.com Tue Apr 12 18:47:57 2005 From: noemail at noemail.com (Jim) Date: Tue, 12 Apr 2005 18:47:57 -0400 Subject: How to debug SOAP using TCpMon and Python? Message-ID: Hello, I am trying to debug a Python SOAP application using tcpmon. I am wondering what listen port, target port number and host address should I use. What about optional parameters: Http Proxy support, host and port? My PC is behind a firewall. Thanks for your help. Jim From gene.tani at gmail.com Sat Apr 9 00:55:01 2005 From: gene.tani at gmail.com (gene.tani at gmail.com) Date: 8 Apr 2005 21:55:01 -0700 Subject: Python Equivalent to Java Interfaces? In-Reply-To: References: Message-ID: <1113022501.240371.97120@g14g2000cwa.googlegroups.com> There's 4 places to look: zope, twisted, PEAK and pyProtocols: this link describes pyprotocols pretty well http://peak.telecommunity.com/protocol_ref/module-protocols.html http://peak.telecommunity.com/PyProtocols.html From hancock at anansispaceworks.com Wed Apr 20 18:04:40 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Wed, 20 Apr 2005 17:04:40 -0500 Subject: Why Python does *SLICING* the way it does?? In-Reply-To: References: <1113976729.450677.261130@o13g2000cwo.googlegroups.com> Message-ID: <200504201704.40894.hancock@anansispaceworks.com> On Wednesday 20 April 2005 12:28 pm, Roy Smith wrote: > Terry Hancock wrote: > >> I used to make "off by one" errors all the time in both C and Fortran, > >> whereas I hardly ever make them in Python. > > Part of the reason may be that most loops over lists involve > iterators, > both endpoints are mentioned explicitly. C++/STL also uses iterators, > but the syntax is repulsive. That's true of course. It's more likely to show up in manipulating lists or strings. And Python provides a much richer environment for processing strings, so one has to deal with explicit indexing much less. But I still think that I make fewer error per instance of dealing with intervals. It's rare that I even have to think about it much when writing such a thing. Negative indexing also helps a lot. Terry -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From ivoras at _-_fer.hr Fri Apr 29 14:12:17 2005 From: ivoras at _-_fer.hr (Ivan Voras) Date: Fri, 29 Apr 2005 20:12:17 +0200 Subject: Reusing object methods? In-Reply-To: References: Message-ID: Jp Calderone wrote: >> I want to 'reuse' the same method from class A in class B, and without >> introducing a common ancestor for both of them - is this possible in >> an elegant, straightforward way? > > > This is what sub-classing is for. If it makes you feel better, call it > "mixing in" instead. You can share this method between two classes > without inheritance (by defining a free function and then ...), but > using a common base class really is just the right way to do it. Ok. From ramon.aragues at gmail.com Thu Apr 21 14:15:02 2005 From: ramon.aragues at gmail.com (ramon.aragues at gmail.com) Date: 21 Apr 2005 11:15:02 -0700 Subject: Persistent python object and the Web Message-ID: <1114107302.827987.230560@l41g2000cwc.googlegroups.com> Hi, I'd like to know if I am trying to do something impossible or I am just being unable to find how to do it. In the latter case, please... help me... I?ve implemented a python class Graph, which handles graphs (with its nodes, edges, finding paths, etc). In my text-menu interface, I can add nodes, delete nodes, add edges, find shortest routes, etc. I simply create a graph_object before presenting the text menu and then, when a user choses a command (eg. add-node) I call the method of this object with the appropiate parameters. Now... I need to "translate" this text-menu interface to a web interface. The same as the text-menu interface, but letting the user do it through the web. I have created an HTML that lets the user enter the parameters and chose which command to execute by pushing different buttons. But... My problem is that I don't know how to create a graph_object that remains persistent through time (it has to be the same graph_object for the first command as for the last one "pushed" by the user). I want to be able to create the object when the user enters the web page (by calling graph_object = Graph(id="graph1")) and then make calls to graph_object methods when the user pushes a button. I'm using python2.3, mod_python and Apache. Any help will be greatly appreaciated. Ramon From axel at straschil.com Mon Apr 11 04:14:47 2005 From: axel at straschil.com (Axel Straschil) Date: 11 Apr 2005 08:14:47 GMT Subject: Multiple inheritance: Interface problem workaround, please comment this References: <1112963912.909325.186760@f14g2000cwb.googlegroups.com> <1113062849.105547.229830@z14g2000cwz.googlegroups.com> Message-ID: Hallo! > Look at the comment in the code! I have posted the "decorate" module in Uuups, sorry, I'll RTFM myselfe *g* Lg, AXEL. -- "Aber naja, ich bin eher der Forentyp." Wolfibolfi's outing in http://www.informatik-forum.at/showpost.php?p=206342&postcount=10 From draghuram at gmail.com Thu Apr 28 10:18:28 2005 From: draghuram at gmail.com (draghuram at gmail.com) Date: 28 Apr 2005 07:18:28 -0700 Subject: Question about python code distribution... In-Reply-To: References: <1114658428.295091.78500@f14g2000cwb.googlegroups.com> Message-ID: <1114697908.282178.266840@f14g2000cwb.googlegroups.com> Hi, I would like for all platforms, not just for windows. In any case, the above two replies about "zipfile" support and "eggs" answer my question. That's exactly what I was looking for. Thanks for prompt and useful responses. Raghu. From alex at quad.com.ar Wed Apr 27 12:39:30 2005 From: alex at quad.com.ar (alex) Date: Wed, 27 Apr 2005 13:39:30 -0300 Subject: Which IDE is recommended? In-Reply-To: <200504271110.24334.jeffelkins@earthlink.net> References: <426f90ac$1_2@rain.i-cable.com> <200504271110.24334.jeffelkins@earthlink.net> Message-ID: <426FC042.1080805@quad.com.ar> jeff elkins wrote: > >Is Boa actively used? There doesn't seem to be much activity its mailing list. >The tutorial fails for me using python 2.3.5, wxpython 2.5.3.2 and Boa 0.4.0 >under debian sid. > >Jeff > > > Boa is not a dead project if that's your concern, maybe it's not getting a lot of attention, but the cvs is getting some decent activity, 0.4.x was recently released, and I've seen some bug reports being fixed in cvs quite fast too. It's really a great product if you can live with its poor documentation and its constraint-oriented design (as opposed to sizer oriented) yes I know it supports sizers, but it wasn't designed for it, and you'll probably end up manually coding the sizers because the built-in support is really weird. anyway, I consider boa the best rad tool for wxpython, it could be better.. but it's still the best of its kind imho. regards, Alex Verstraeten. From michele.simionato at gmail.com Wed Apr 13 03:28:06 2005 From: michele.simionato at gmail.com (Michele Simionato) Date: 13 Apr 2005 00:28:06 -0700 Subject: win32 readline maintenance (was Re: IPython - problem with... In-Reply-To: References: <3bv5mgF6jbil9U1@individual.net> <1113323786.737140.184800@o13g2000cwo.googlegroups.com> Message-ID: <1113377286.541980.68610@l41g2000cwc.googlegroups.com> Switching to the US keyboard did not help for me. From py.adriano at gmail.com Sat Apr 9 13:36:59 2005 From: py.adriano at gmail.com (Adriano Monteiro) Date: Sat, 9 Apr 2005 14:36:59 -0300 Subject: Help with modem terminal Message-ID: <29ec2154050409103674b72340@mail.gmail.com> Hey folks, I need to talk to my modem through a terminal, so I can send commands and get the answers. Does anybody here know what can I do? I've tried to use pty.py, but I'm lost... Regards, []'s! -- Adriano Monteiro Marques www.gopython.com.br py.adriano at gmail.com I'm FREE... Are you? (PYTHON powered) From tiissa at nonfree.fr Wed Apr 20 15:35:51 2005 From: tiissa at nonfree.fr (tiissa) Date: Wed, 20 Apr 2005 21:35:51 +0200 Subject: pyGTK on Mouse over event ? In-Reply-To: <1114022408.677746.287630@f14g2000cwb.googlegroups.com> References: <1114022408.677746.287630@f14g2000cwb.googlegroups.com> Message-ID: <4266af16$0$31058$626a14ce@news.free.fr> Domenique.Tilleuil at gmail.com wrote: > hello, > > Is there an event simular to the java event onMouseOver ? > I want to get the coordinates of the mouse pointer when it is over an > image ( GTKImage widget) > > I've tried using the EventBox with the motion_notify but that only > seems to work when the mouse is pressed ? > Why do you use an event box? Image derives from Widget hence can be connected to the motion-notify-event just like EventBox. Did you try directly? From kartic.krishnamurthy at gmail.com Tue Apr 5 19:37:04 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 5 Apr 2005 16:37:04 -0700 Subject: Is it possible to distinguish between system environment variables and the user ones? In-Reply-To: References: Message-ID: <1112744224.598681.89770@z14g2000cwz.googlegroups.com> There is nothing that plainly differentiates whether an environment variable is the system's or the current user's. What you could do is: 1. Get the list of environment variables for the user the script is executing as. 2. Use the pywin32 extensions to access the registry key HKCU\Environment 3. Lookup the environment variables present in the list (Item 1) that appear as string values under HKCU\Environment. 4. The intersecting list belongs to the user, the rest can be surmised as belonging to the system environment. Thanks, --Kartic From msoulier at gmail.com Tue Apr 19 22:57:23 2005 From: msoulier at gmail.com (Michael Soulier) Date: Tue, 19 Apr 2005 22:57:23 -0400 Subject: Importing some functions from a py file In-Reply-To: <20050420025217.46333.qmail@web54501.mail.yahoo.com> References: <20050420025217.46333.qmail@web54501.mail.yahoo.com> Message-ID: On 4/19/05, Anthony Liu wrote: > > You are certainly right, because I don't know how to > protect the main functions. Where do I put > > if __name__ == '__main__': main() I just glanced in the modules section of the python documentation and surprisingly this is not mentioned at all that I could see. I think that's an oversight. See this example: http://diveintopython.org/getting_to_know_python/index.html Mike -- Michael P. Soulier http://www.digitaltorque.ca http://opag.ca python -c 'import this' Jabber: msoulier at digitaltorque.ca From kay.schluehr at gmx.net Sun Apr 24 02:11:38 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 23 Apr 2005 23:11:38 -0700 Subject: Variables In-Reply-To: References: <426B0283.40602@cloudthunder.com> <426b255d.375304108@news.oz.net> Message-ID: <1114323098.854687.27750@g14g2000cwa.googlegroups.com> Richard Blackwood wrote: > Could I honestly argue this to him? From what basis do I argue that it > is not an equation? In any event, he would likely (passionately) > disagree considering his notion that programming is an off-shoot of math > and thus at the fundamental level has identical concepts and rules. What is special on *equations* in mathematics is that both sides of an equation are ususually not equal! Identifying an equational expression "x=1" with the solutionset {1} of the equation is for convenience. For more complex equational expressions, say "x**5+4x-1 = 0" You never confuse the equation with the solution set. The solution set is nothing but a set of values that if inserted into the equation would really create equal terms on both sides i.e. "0=0" in our example. To make a difference between an assignment and an equation it would be better to use a different operator for an equation, say "==". Usually "==" is interpreted in programming languages as a binary operator that returns a boolean value. This is a usefull but narrow perspective that is broken by many computer algebra systems like Mathematica that adapts "==" to the the more general equational interpretation. The interpretation of "x = 5" as defining a "constant" may stem from languages ( Visual Basic ? ) that introduce a "var" keyword to make variable creation explicit. var x = 7; or var int x = 8; In C You refuse "var" and restrict "immutable variables" i.e. constants by means of the keyword "const". In Python You can't define a "constant" by simply assign a value to name. You can interpret assignment as creation of a variable of domain object. Since each expression is an object You can drop "object" from C-like definitions object x = 8 and reduce it to x = 8 To become more precise You have to do workarounds. Ciao, Kay From donmcdaniel2005 at yahoo.com Thu Apr 28 03:04:49 2005 From: donmcdaniel2005 at yahoo.com (Donald L McDaniel) Date: Thu, 28 Apr 2005 00:04:49 -0700 Subject: Ron Grossi: God is not a man References: <1114098221.580669.86300@g14g2000cwa.googlegroups.com> <1114127633.859113.292290@l41g2000cwc.googlegroups.com> <#2tJ0r3RFHA.3664@TK2MSFTNGP15.phx.gbl> <1114328806.147822.64660@z14g2000cwz.googlegroups.com> <1114329202.229148.82550@o13g2000cwo.googlegroups.com> <1114654290.690332.155200@f14g2000cwb.googlegroups.com> Message-ID: Matt Hayden wrote: > Johnny Gentile wrote: >> C'mon. Everyone knows God plays a Martin. > > I dunno. I think God has a honkin' big collection so he won't offend > ANY luthiers when they come to visit. SOMEONE has to set up his > guitars... > > mh 1) God is a Being Who lives in Eternity and Infinity. 2) God is not a man. However, His Son, Christ Jesus, left the loftiness of Eternity and became a Man without losing His God-Substance which He receives from His Father. This means He is not just a man, but the God-Man. 3)He lived a pure, sinless life, and died on the Cross in our place, as the Sacrifice for our sins. However, He did not remain in the Tomb HE was placed in after He was taken down from the cross by those who loved Him. Within three days, HE was raised from the dead by His Father, still the God-Man. After 40 days on the earth, He was returned to the Father in His Body of flesh, tho now It was glorified (made eternal by the Father). There He is to this very day, interceeding for those who have received Him as the Anointed One of God. 4) One day, hopefully, soon, He will return in Power and Glory to judge the thoughts of all men, and transfer His servants from their bodies of flesh to glorified bodies, like His. Do not try to reason this out, since the Incarnation of Christ is not a thing of logic and reason, but a Holy Mystery, only comprehended by faith in those who have put their hope and trust in Him and His Sacrifice on the Cross. Faith can easily be understood by a man with an open mind: Let us say that there is a Sargent in the Army; his commanding officer, a General, whose desk is a thousand miles away, and whom he has never seen, gives him a letter containing an order. The Sargent's act of obedience to the order can be explained as "faith", since he never saw the General, and obeys him simply because he is his commanding officer. While we have never seen the Father, we obey Him, because He sent a Man with orders from Him for His servants. Not only that, but this simple faith is testified to by the Holy Spirit after we obey, and our steps of faith are rewarded with experiential knowledge of God, as we learn to recognise His Hand in our lives. We obey God simply because His Son and servants tell us to. Through time and experience, we have learned to trust His Words, because they come to pass, in His Time, and in His Way. 4) I doubt seriously whether God plays a guitar, since guitars are made by men, for men. His Son could theoretically play a guitar. Perhaps He does. Perhaps He doesn't. Only the Father and His Holy Angels know. -- Donald L McDaniel Please reply to the original thread, so that the thread may be kept intact. ============================== From steve at holdenweb.com Tue Apr 5 19:23:52 2005 From: steve at holdenweb.com (Steve Holden) Date: Tue, 05 Apr 2005 19:23:52 -0400 Subject: IronPython 0.7 released! In-Reply-To: <1f7befae05040512422ef693d4@mail.gmail.com> References: <1111603770.909447.18070@z14g2000cwz.googlegroups.com> <1f7befae05040512422ef693d4@mail.gmail.com> Message-ID: <42531E08.8060706@holdenweb.com> Tim Peters wrote: > [Thomas Gagne] > >>Does the Python community think Microsoft's embrace is a good or bad thing? > > > All things in this world unfold exactly according to Guido's secret > Master Plan. So it depends on whether you think Guido is good or bad. > Members of the Python community are required to think Guido is good. > Therefore all things that happen in this world are good. > > I know, it takes a bit of practice to truly believe that . > > not-mentioning-that-i-don't-feel-particularly-embraced-yet-ly y'rs - tim Presumably when we get past the embracing and on to the extending Barry can finally retrain Spambayes to reject penis enlargement emails? regards Steve -- Steve Holden +1 703 861 4237 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ From steve at holdenweb.com Tue Apr 12 20:01:41 2005 From: steve at holdenweb.com (Steve Holden) Date: Tue, 12 Apr 2005 20:01:41 -0400 Subject: Cannot import mod_python modules In-Reply-To: <6c9897c2.0504121428.4c7238a9@posting.google.com> References: <6c9897c2.0504120255.1f274@posting.google.com> <6c9897c2.0504121428.4c7238a9@posting.google.com> Message-ID: Mark wrote: > Thanks for the reply Steve, > > I have re-installed mod_python and re-configured Apache and it works > now. I'm not exactly sure what I done differently, but oh well at > least it works now :) > > Regards, > > Mark. Right, no point wasting much sleep when mod_python awaits! regards Steve -- Steve Holden +1 703 861 4237 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ From littlejohn at DeleteMe.knology.net Sun Apr 10 10:33:41 2005 From: littlejohn at DeleteMe.knology.net (LittleJohn) Date: Sun, 10 Apr 2005 09:33:41 -0500 Subject: Best editor? References: <1112725379.514651.66540@l41g2000cwc.googlegroups.com> <86k6nbww6z.fsf@guru.mired.org> Message-ID: Mike Meyer wrote: > For quick edits (as either root or me) I use ex. I can't get past ed > not having a prompt. For a Linux gui editor, try NEdit. It's almost identical to the old PFE editor for Windoze and it 'knows' Python. LittleJohn Madison, AL From jstroud at mbi.ucla.edu Thu Apr 21 17:46:05 2005 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 21 Apr 2005 14:46:05 -0700 Subject: Regular Expressions - Python vs Perl In-Reply-To: References: <1114092105.964664.211430@l41g2000cwc.googlegroups.com> Message-ID: <200504211446.05189.jstroud@mbi.ucla.edu> Is it relevant that Python can produce compiled expressions? I don't think that there is such a thing with Perl. Also, to all of the dozen or so people in the world less wise than me about programming: don't choose your language on how fast the regex engine is. This would then become a case of premature optimization. James On Thursday 21 April 2005 10:23 am, Thomas Bartkus wrote: > "djw" wrote in message > news:d48ktk$4ov$1 at news.vcd.hp.com... > > > While I agree with (most of) your points, one should not overlook the > > fact that there are cases when performance does matter (huge datasets > > maybe?). Since the OP didn't indicate why performance was important to > > him/her, one cannot assume that its not a valid concern. > > Yes, yes, but then - the converse would be true. One cannot assume it *is* > a valid concern. > > I could have gone further and pointed out that that RegEx module (now re !) > is probably just C code hooked to Python syntax. IOW - the execution speed > of his RegEx module has *nothing at all* to do with the Python language, > only the efficiency of the particular code library he was using. > > All in all, execution speed for any one particular task is a sucky way to > evaluate a general purpose programming language. If gonzo RegEx query > performance was of utmost importance, would anyone put either of Perl or > Python at the top of his list? > > Thomas Bartkus -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From abkhd at earth.co.jp Tue Apr 19 10:30:56 2005 From: abkhd at earth.co.jp (A.B., Khalid) Date: 19 Apr 2005 07:30:56 -0700 Subject: (Python newbie) Using XP-SP2/MSVC6: No Python24_d.lib, winzip barfs on Python-2.4.1.tar, cannot download bzip2 References: Message-ID: <1113921056.163970.216730@g14g2000cwa.googlegroups.com> Okay, let me have another stap at this. As you have probably noticed MSVC6 is no longer actively supported as far as Python 2.4 goes. The official distribution of Python 2.4 for Windows is built using MSVC7.1 (or whatever you wish to call it). We are told that building C extensions with MSVC6 for use in the official Python 2.4 (which uses the MSVCR71) is not safe, and mixing the different runtime libraries that your extension (or my extension) with that which official Python 2.4 uses will/might cause crashes. Google around for details on this. So, what to do? You seem to have four options. 1. Get and use the MSVC7.1 compiler. 2. Get and use the freely distributed MS compiler. 3. Download the Python source[1] and compile it yourself in MSVC6 (there are project files in the source to enable you to do that). Then use your MSVC6 to create the extension. 4. Get and use MinGW and pyMinGW[2] Regards, Khalid [1] Check to see if your archiever tool is working, or get the source from CVS. [2] pyMinGW: http://jove.prohosting.com/iwave/ipython/pyMinGW.html From lbates at syscononline.com Mon Apr 11 09:47:31 2005 From: lbates at syscononline.com (Larry Bates) Date: Mon, 11 Apr 2005 08:47:31 -0500 Subject: Document exchange! In-Reply-To: <1113155501.394204.92470@o13g2000cwo.googlegroups.com> References: <1113155501.394204.92470@o13g2000cwo.googlegroups.com> Message-ID: <8vSdnXignqBt4sffRVn-pA@comcast.com> You may want to take a look at www.websafe.com. If I can be so bold (since I'm one of the developers), we belive it is both simple and secure. We provide web, WebDAV, and HTTPS interfaces (I can provide you with sample Python code). At-rest encryption is AES. It is a hosted ASP-type application with annual subscriptions. Larry Bates James wrote: > This is not so much as a Python question though I will implement it in > it. > > I am looking to securely aggregate documents based on a metadata from > multiple providers. I am getting the feeling that I am reinventing the > wheel. If anyone knows similar work elsewhere, please point me to it. > > Security and simplicity (is it possible to use the two in the same > sentence? :-) ) of the protocol is king. I have the luxury of > implementing any protocol I choose on each reposity. > > Thanks, > James > From gfyho at yahoo.com Wed Apr 27 15:19:01 2005 From: gfyho at yahoo.com (Gary) Date: 27 Apr 2005 12:19:01 -0700 Subject: Design advice for unit test asserters In-Reply-To: <874qdzpdrr.fsf@titan.staselog.com> References: <1114085180.425079.302580@z14g2000cwz.googlegroups.com> <874qdzpdrr.fsf@titan.staselog.com> Message-ID: <1114629540.972450.121850@g14g2000cwa.googlegroups.com> First, thanks to both Kent and Edvard for useful comments. I certainly need to consider whether it make sense to switch to py.test at this time; its simplicity is attractive. In response to Edvards question: Edvard Majakari wrote: > "Gary" writes: ... > > self.AssertAllFilesExist(fileList) ... > > > > def test_SomeTest(...): > > ... > > [ self.AssertFileExists(f) for f in fileList ] > > I prefer the latter, because then you'd get error for the missing file - > otherwise you'd just know a file didn't exist (but not which, unless you > explicitly coded that in, no?) Yes, my intent is that AssertAllFilesExist(fileList) would be something like the following, more or less: def AssertAllFilesExist(fileList): for f in fileList: self.assert_(os.path.isfile(f) and not os.path.islink(f), "File %s is missing" % f) It's the smarts in these that caused me to instantly see applicability of the Template Pattern - which became quite a distraction to me, because after doing it, I think it was obviously unnecessary overkill. Gary From Serge.Orlov at gmail.com Sun Apr 3 05:38:18 2005 From: Serge.Orlov at gmail.com (Serge Orlov) Date: Sun, 3 Apr 2005 09:38:18 +0000 (UTC) Subject: redundant imports References: <86zmwgx0he.fsf@guru.mired.org> Message-ID: Mike Meyer wrote: > The semantic behavior of "include" in C is the same as "from module > import *" in python. Both cases add all the names in the included > namespace directly to the including namespace. This usage is > depreciated in Python ... Did you mean discouraged? Or it's really slated for deprecation? Serge. From gradius at fmf.nl Fri Apr 15 10:02:31 2005 From: gradius at fmf.nl (Anton Jansen) Date: Fri, 15 Apr 2005 16:02:31 +0200 Subject: IOError 11 CGI module Message-ID: Hi list, I have troubles with some python scripts I use as cgi scripts with thttpd. At irregular intervals when a post is made an IOError is raised by the CGI module. My question is how and why does this happen? The exception looks like this: --- Traceback (most recent call last): File "teamadmin.cgi", line 11, in ? iudex_cgi.makeform() File "/wing6/home/jury/iudex/nederlands/lib/iudex_cgi.py", line 24, in makeform form = _extractflat( cgi.FieldStorage() ) File "/usr/lib/python2.3/cgi.py", line 517, in __init__ self.read_urlencoded() File "/usr/lib/python2.3/cgi.py", line 622, in read_urlencoded qs = self.fp.read(self.length) IOError: [Errno 11] Resource temporarily unavailable --- The code: File:iudex_cgi.py --- import sys import time import traceback import cgi import MySQLdb from iudex_tags import * form = None def _extractflat( fields ): form = {} for i in fields.value: if not form.has_key( i.name ): form[i.name] = [] if i.filename: form[i.name].append( ( i.filename, i.value ) ) else: form[i.name].append( i.value ) return form def makeform(): global form form = _extractflat( cgi.FieldStorage() ) --- With kind regards, Anton Jansen From m at m.com Thu Apr 28 17:50:05 2005 From: m at m.com (monkey) Date: Fri, 29 Apr 2005 05:50:05 +0800 Subject: why "import wx" doesn't work? References: <427126ca$1_3@rain.i-cable.com> Message-ID: <42715a8b$1_1@rain.i-cable.com> > Which version of wxPython are you running? What do you mean by "does not > work"...does the import fail or is your code giving errors? It is the current new version 2.6. The error message said that the class wxApp is not defined... But when using the default "from wxPython.wx import *", it works. From martin at v.loewis.de Mon Apr 11 17:58:21 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 11 Apr 2005 23:58:21 +0200 Subject: Python 2.4 killing commercial Windows Python development ? In-Reply-To: <20050411194907.1769.17472.XPN@orion.homeinvalid> References: <425a9869$0$38039$bed64819@news.gradwell.net> <20050411194907.1769.17472.XPN@orion.homeinvalid> Message-ID: <425AF2FD.2080006@v.loewis.de> Nemesis wrote: > I have the same problem. But I have a doubt, does Python installer ship > this dll? It sure does. > What happens if I try to install Python2.4 on a system wich doesn't have > the dll? It will just work. Python installs the DLL if it is missing, and leaves it alone (just incrementing the refcount) if it is present on the target system. Regards, Martin From steve at holdenweb.com Thu Apr 21 07:29:14 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 21 Apr 2005 07:29:14 -0400 Subject: deprecation of has_key? In-Reply-To: <20050421121306.00006637@LAB2-13.esi> References: <1114069715.945176.73750@l41g2000cwc.googlegroups.com> <426775C8.3000303@holdenweb.com> <20050421121306.00006637@LAB2-13.esi> Message-ID: <42678E8A.4020808@holdenweb.com> Luis Bruno wrote: > Hello, > > Steve Holden wrote: > >>Two words: backward compatibility. To lose that method now would break >>thousands of existing programs. The 2.4 library would probably >>experience breakage too ... let's see: >> >>$ find /lib/python2.4/ -name "*.py" -exec grep has_key {} \; | wc -l >>587 > > > Is there any interest in changing that to the "key in dict" sintax? > The general principles on which maintenance is based for Python decree that such changes not be made gratuitously: the code as it is works now, so it is only worth changing when has_key is removed. If a module were being edited for other reasons there would be no objection to removal of the has_key usage then, but the chance of breakage due to careless modification is high enough to want to avoid it unless really *necessary*. regards Steve -- Steve Holden +1 703 861 4237 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ From osv at javad.ru Thu Apr 21 10:53:19 2005 From: osv at javad.ru (Sergei Organov) Date: 21 Apr 2005 18:53:19 +0400 Subject: goto statement References: <20050420092359.81900.qmail@web8409.mail.in.yahoo.com> <3cmtgvF6q13cvU1@individual.net> <116fbo3pma1lsdb@corp.supernews.com> Message-ID: Grant Edwards writes: > On 2005-04-21, Sergei Organov wrote: > > > Well, I'm writing for embedded realtime systems in C/C++ and > > have never encountered a single need to use goto. > > I have encountered situations in C programs where the best > thing to use was a goto. Those situations have always been > handled beutifully by a "raise" in Python. setjmp/longjump? -- Sergei. From bgs248 at hotmail.com Fri Apr 29 22:40:56 2005 From: bgs248 at hotmail.com (bgs) Date: 29 Apr 2005 19:40:56 -0700 Subject: Python Challenge ahead [NEW] for riddle lovers References: Message-ID: <1114828856.889984.171750@g14g2000cwa.googlegroups.com> pythonchallenge wrote: > For the riddles' lovers among you, you are most invited to take part > in the Python Challenge, the first python programming riddle on the net. > > You are invited to take part in it at: > http://www.pythonchallenge.com That was fun. The very first step in 6 was the most frustrating I thought. From mage at mage.hu Tue Apr 19 09:07:08 2005 From: mage at mage.hu (Mage) Date: Tue, 19 Apr 2005 15:07:08 +0200 Subject: modules and namespaces Message-ID: <4265027C.2090104@mage.hu> Hello, I thought that this will work: #m1.py def f1(): return string.join('a','a') #m2.py def f2(): return string.join('b','b') #main.py import string import m1 import m2 print f1() print f2() --------- However it doesn't work until I import the string module into m1 and m2 modules. I found in the manual that imported modules will be searched in the container module first. Is it more efficient to import the string module into main and m1 and m2 than importing only into m1 and m2? Mage From gry at ll.mit.edu Fri Apr 29 16:54:36 2005 From: gry at ll.mit.edu (gry at ll.mit.edu) Date: 29 Apr 2005 13:54:36 -0700 Subject: module exports a property instead of a class -- Evil? In-Reply-To: <1114802337.216856.219870@l41g2000cwc.googlegroups.com> References: <1114797779.371054.189950@g14g2000cwa.googlegroups.com> <1114802337.216856.219870@l41g2000cwc.googlegroups.com> Message-ID: <1114808076.408181.130480@z14g2000cwz.googlegroups.com> Hmm, I had no idea that "property" was a class. It's listed in the library reference manual under builtin-functions. That will certainly make things neater. Thanks! -- George From pgmoscatt at optushome.com.au Fri Apr 15 05:29:09 2005 From: pgmoscatt at optushome.com.au (Peter Moscatt) Date: Fri, 15 Apr 2005 19:29:09 +1000 Subject: Tk Listbox - Selected Item ? References: <425f722b$0$5849$9a6e19ea@news.newshosting.com> Message-ID: <425f8882$0$5861$9a6e19ea@news.newshosting.com> Martin Franklin wrote: > Peter Moscatt wrote: >> Martin Franklin wrote: >> >> >>>Peter Moscatt wrote: >>> >>>>I am having trouble understanding the methods for the Listbox from Tk. >>>> >>>>If I was to select at item in the list using a mouse click (have already >>>>created the bind event) - what method returns the text of the selected >>>>item ? >>>> >>>>Pete >>>> >>> >>> >>>Pete, >>> >>>pydoc Tkinter.Listbox >>> >>> >>> >>> | curselection(self) >>> | Return list of indices of currently selected item. >>> | >>> | delete(self, first, last=None) >>> | Delete items from FIRST to LAST (not included). >>> | >>> | get(self, first, last=None) >>> | Get list of items from FIRST to LAST (not included). >>> >>>So to get the value of the selected item: >>> >>>lb.get(lb.curselection()[0]) >>> >>> >>>provided the listbox is in single selection mode or only one item is >>>selected >>> >>>Martin >> >> >> Thanks Martin, >> >> I used the: >> lb.get(lb.curselection()[0]) >> >> ant this works to a point. When I select the item in the listbox the >> system generates an error: >> >> Exception in Tkinter callback >> Traceback (most recent call last): >> File "/usr/lib/python2.3/lib-tk/Tkinter.py", line 1345, in __call__ >> return self.func(*args) >> File "/home/linux/programming/dxcluster/servers.py", line 37, in sel >> items = self.listbox.get(self.listbox.curselection()[0]) >> IndexError: tuple index out of range >> >> >> Then if I select a second time directly after the error message I get my >> desired result. >> > > Pete, > > Sounds like you are using the wrong kind of bind event. That is the > first time you select an item the callback for the bind command is > called *before* the selection is made. Can you post the code you have > showing the bind method and callback? > > This code shows three different bind methods, the first produces the > same exception that you got... > > > from Tkinter import * > > > root = Tk() > lb = Listbox(root) > lb.insert(0, "one") > lb.insert(0, "two") > lb.insert(0, "three") > lb.pack() > > def callback(*event): > print lb.get(lb.curselection()[0]) > > ## BAD > #~ lb.bind("<1>", callback) > > ## OK > #~ lb.bind("", callback) > > ## Best > lb.bind("<>", callback) > > root.mainloop() > > > The <> is a virtual event I think quick google would tell > you more and the Tk man pages (online) have a complete explanation... > > http://www.tcl.tk/man/tcl8.4/TkCmd/listbox.htm > http://www.tcl.tk/man/tcl8.4/TkCmd/listbox.htm#M60 > > > Cheers, > Martin. Thanks Martin, You're a legend !!!!! I fixed the bind and used lb.bind("<>", callback) and away it went. Thanks heaps for the help. Pete From simon.brunning at gmail.com Mon Apr 4 07:31:49 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Mon, 4 Apr 2005 12:31:49 +0100 Subject: Testing for EOF ? In-Reply-To: <4251226a$0$5805$9a6e19ea@news.newshosting.com> References: <4251226a$0$5805$9a6e19ea@news.newshosting.com> Message-ID: <8c7f10c605040404315c1854de@mail.gmail.com> On Apr 4, 2005 12:21 PM, Pete Moscatt wrote: > I am reasonably new to python and am trying to read several lines of text > from an open file. my_file = open('whatever.txt', 'r') for line in my_file: print line # Or whatever -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From roy at panix.com Thu Apr 21 22:17:25 2005 From: roy at panix.com (Roy Smith) Date: Thu, 21 Apr 2005 22:17:25 -0400 Subject: Why Python does *SLICING* the way it does?? References: <1113976729.450677.261130@o13g2000cwo.googlegroups.com> <87r7h5lk5a.fsf@wilson.rwth-aachen.de> <3cr2caF6locm6U1@individual.net> Message-ID: Greg Ewing wrote: > Also, everyone, please keep in mind that you always have > the option of using a *dictionary*, in which case your > indices can start wherever you want. > > You can't slice them, true, but you can't have everything. :-) Of course you can slice them, you just have to subclass dict! The following was about 15 minutes work: --------------- import types class slicableDict (dict): def __getitem__ (self, index): if type (index) == types.SliceType: d2 = slicableDict() for key in self.keys(): if key >= index.start and key < index.stop: d2[key] = self[key] return d2 else: return dict.__getitem__ (self, index) d = slicableDict() d['hen'] = 1 d['ducks'] = 2 d['geese'] = 3 d['oysters'] = 4 d['porpoises'] = 5 print d print d['a':'m'] --------------- Roy-Smiths-Computer:play$ ./slice.py {'oysters': 4, 'hen': 1, 'porpoises': 5, 'geese': 3, 'ducks': 2} {'hen': 1, 'geese': 3, 'ducks': 2} I defined d[x:y] as returning a new dictionary which contains those items from the original whose keys are in the range x <= key < y. I'm not sure this is terribly useful but it's a neat demonstration of just how simple Python makes it to do stuff like this. I can't imagine how much work it would be to add a similar functionality to something like C++ multimap. I'm sure the code above could be improved, and I know I've ignored all sorts of things like steps, and error checking. Frankly, I'm amazed this worked at all; I expected to get a syntax error when I tried to create a slice with non-numeric values. PS: Extra credit if you can identify the set of keys I used without resorting to google :-) From max2 at fisso.casa Sat Apr 9 17:57:48 2005 From: max2 at fisso.casa (max(01)*) Date: Sat, 09 Apr 2005 21:57:48 GMT Subject: serialize a tkinter thing Message-ID: hi. i tried to serialize a list of StringVar's, but i got a pickle error. this got me to thinking that tkinter objects are not picklable (in general). would somebody confirm and/or give examples? thanks macs From chromeclouds at yahoo.co.uk Tue Apr 12 18:28:01 2005 From: chromeclouds at yahoo.co.uk (Mark) Date: 12 Apr 2005 15:28:01 -0700 Subject: Cannot import mod_python modules References: <6c9897c2.0504120255.1f274@posting.google.com> Message-ID: <6c9897c2.0504121428.4c7238a9@posting.google.com> Thanks for the reply Steve, I have re-installed mod_python and re-configured Apache and it works now. I'm not exactly sure what I done differently, but oh well at least it works now :) Regards, Mark. From robin at alldunn.com Sat Apr 9 00:03:30 2005 From: robin at alldunn.com (Robin Dunn) Date: Fri, 08 Apr 2005 21:03:30 -0700 Subject: ANNOUNCE: wxPython 2.5.5.1 Message-ID: <42575412.1000502@alldunn.com> Announcing ---------- I'm pleased to announce the 2.5.5.1 release of wxPython, now available for download at http://wxpython.org/download.php. This is mostly a bug-fix release, but there are a few new features as well. See the changes list below for details. What is wxPython? ----------------- wxPython is a GUI toolkit for the Python programming language. It allows Python programmers to create programs with a robust, highly functional graphical user interface, simply and easily. It is implemented as a Python extension module that wraps the GUI components of the popular wxWidgets cross platform library, which is written in C++. wxPython is a cross-platform toolkit. This means that the same program will usually run on multiple platforms without modifications. Currently supported platforms are 32-bit Microsoft Windows, most Linux or other Unix-like systems using GTK or GTK2, and Apple Macintosh OS X. Changes in 2.5.5.1 ------------------ wxMSW: Fixed bug #1022383, 'several ComboBoxes appear selected' wx.grid.Grid: Fixed bug #1163384. Moved the code that handles activating the cell editors to a EVT_CHAR event handler. This is done so the character inserted into the editor will be the "cooked" char value (including accented or composed keys) rather than the raw code provided by the EVT_KEY_DOWN event. Added orient parameter to wx.MDIParentFrame.Tile() wxMSW: wxTextCtrl with wx.TE_RICH2 style now uses RichEdit 4.1 if available. Added GetCount, GetCountRGB, and GetCountColour methods to wx.ImageHistogram. wxMSW: wx.Window.Refresh changed to explicitly refresh all children as well as the parent. Previously it was implicitly done because parents did not clip their children by default. Now that they always clip children then Refresh needed to be fixed to do a recursive refresh. This also fixes the Freeze/Thaw problems that some people had with 2.5.4.1. wx.SplitterWindow: Send EVT_SPLITTER_SASH_POS_CHANGED only once after end of dragging and not after each CHANGING event (modified patch #1076226) wx.glcanvas.GLCanvas: applied patch fixing problems with X server crash when using nVidia cards (patch 1155132) wx.lib.mixins.listctrl: Patches from Toni Brkic: * Bugfix for TextEditMixin when the view can't be scrolled * Enhancement for ListCtrlAutoWidthMixin, allowing it to manage the width of any column. wxMac: removal and reusing toolbar tools like the other platforms is now possible. wxMac: Correct radio tool selection after calling Realize a 2nd time. wxMSW: Applied patch #1166587, removes all flicker from wx.StaticBox Added wx.lib.foldpanelbar, Andrea Gavana's port of Jorgen Bodde's C++ wxFoldPanelBar classes to Python. wxGTK: Applied patch #1173802, reimplementation of GtkFileChooser wxFileDialog by Mart Raudsepp. Note that this new file dialog is only used on GTK2 >= 2.4. For earlier GTK2 versions and GTK1 then the older generic file dialog is used. wxMSW: fixes to static box borders calculations (finalizes patch #1166587) wx.Image: Use Python's buffer interface API for all image data and alpha Set/Get methods and the ImageFromData* constructors. They all still copy the buffer except for SetDataBuffer and SetAlphaBuffer, but this gives more flexibility on where the data can come from. Added MDI support to XRC Added wx.animate module and a demo. The wx.animate module provides a control that is able to display an animated GIF file. wx.lib.plot.py: Applied patch from Werner F. Bruhin that allows either vertical and/or horizontal gridlines. wxMSW: Extra space given for top border of wx.StaticBoxSizer so the upper line is not cliped when there is no label. wxMSW: Restored old behaviour of wx.StaticBox.SetBackgroundColour only affecting the label. wxMSW: Fixed missing EVT_RIGHT_DOWN and EVT_TREE_ITEM_RIGHT_CLICK events in a wx.TreeCtrl. Added wx.GetTopLevelWindows() function which returns a copy of the list of top-level windows that currently exist in the application. Updated docview library modules and sample apps from the ActiveGrid folks. Added the ActiveGrid IDE as a sample application. -- Robin Dunn Software Craftsman http://wxPython.org Java give you jitters? Relax with wxPython! From codecraig at gmail.com Mon Apr 18 17:04:33 2005 From: codecraig at gmail.com (codecraig) Date: 18 Apr 2005 14:04:33 -0700 Subject: Tkinter & Tkconstants In-Reply-To: <1113854966.648882.235040@l41g2000cwc.googlegroups.com> References: <1113854966.648882.235040@l41g2000cwc.googlegroups.com> Message-ID: <1113855590.105946.16330@l41g2000cwc.googlegroups.com> nevermind, i should access it by HORIZONTAL not Tkinter.HORIZONTAL since I imported everything from Tkinter already. Thanks anyway From brad at it.alliedpress.co.nz Mon Apr 25 19:50:07 2005 From: brad at it.alliedpress.co.nz (Brad Murdoch) Date: Tue, 26 Apr 2005 11:50:07 +1200 Subject: select() on pipe Message-ID: <426D822F.7010402@mailhost> im trying to run the select.selct() on a unix pipe, my expectation is that it will block untill there is something there to read, then continue. It seems to do this untill the pipe is written to once, then i get a busy while loop. shouldnt this stop each time, to wait for something to be written to the pipe. obviously im a novice when it comes to python programming, what am i missing here. cheers.. #!/usr/bin/python import os import sys import select try: fifo = open('test.fifo','r') except Exception, blah: report = "ERROR 001: " + str(blah) print report sys.exit(2) while 1: line = False r,w,x = select.select([fifo],[],[]) if r: line=fifo.read() print line From simon.brunning at gmail.com Mon Apr 4 07:48:00 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Mon, 4 Apr 2005 12:48:00 +0100 Subject: Testing for EOF ? In-Reply-To: <1112614568.5293.4.camel@localhost> References: <4251226a$0$5805$9a6e19ea@news.newshosting.com> <8c7f10c605040404315c1854de@mail.gmail.com> <1112614568.5293.4.camel@localhost> Message-ID: <8c7f10c605040404484d8a837b@mail.gmail.com> On Apr 4, 2005 12:36 PM, Peter Moscatt wrote: > Thanks Simon, > > So the code should look like: > > f=open(myfile,"r") > > for some_var in f: > text=f.readline() > print text > > Do I have this correct ? Nearly - you don't need the text=f.readline() bit. A file object (as returned to you by open()) is an iterator, and iterating over it gives you the lines directly. Why not give it a go? The nice thing about Python is how easy it is to try stuff like this out at the interactive prompt. Err, *one* of the nice things, that is. ;-) BTW, newbies are more than welcome here, but there is a python-tutor list[1] which might be more your speed if you are quite new to Python. There are also a number of tutorials available[2] . I'd recommend either the standard tutorial[3] or Dive Into Python[4] for someone like you who already knows how to program but doesn't know Python. Welcome to Python, and have fun. -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ [1] http://mail.python.org/mailman/listinfo/tutor [2] http://www.python.org/moin/BeginnersGuide/Programmers [3] http://www.python.org/doc/current/tut/ [4] http://diveintopython.org/ From could.net at gmail.com Tue Apr 5 03:33:29 2005 From: could.net at gmail.com (could ildg) Date: Tue, 5 Apr 2005 15:33:29 +0800 Subject: How to merge two binary files into one? In-Reply-To: References: <1153pu8pvom6b02@corp.supernews.com> <1153vfhid1vfif1@corp.supernews.com> Message-ID: <311b5ce1050405003353935bd@mail.gmail.com> I'm so glad that this this problem has so many recipes. On Apr 5, 2005 1:57 PM, Andrew Dalke wrote: > Grant Edwards wrote: > > For large files, something like this is probably a better idea: > > Or with the little-used shutil module, and keeping your > nomenclature and block size of 65536 > > import shutil > fout = file('C', 'wb') > for n in ['A', 'B']: > fin = file(n, 'rb') > shutil.copyfileobj(fin, fout, 65536) > fin.close() > fout.close() > > Andrew > dalke at dalkescientific.com > > -- > http://mail.python.org/mailman/listinfo/python-list > -- ???????????????????? ???????????????? ???????? From Scott.Daniels at Acm.Org Sat Apr 2 13:28:04 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sat, 02 Apr 2005 10:28:04 -0800 Subject: boring the reader to death (wasRe: Lambda: the Ultimate DesignFlaw In-Reply-To: <1112456559.835048@yasure> References: <424e8d1d$1@nntp0.pdx.net> <1112456559.835048@yasure> Message-ID: <424edf02@nntp0.pdx.net> Donn Cave wrote: > Quoth Scott David Daniels : > | Sunnan wrote: > | > ...Because what is "boring"? The opposite of dense, tense, intense. Utterly > | > predictable; it's like the combination of all my prejudices. Even before > | > I knew, I thought "Bet Python separates statements from expressions". > | > | Python is for terse, pithy prose; Python is not for poetry. > > That's an odd thing to say. Poetry is verbose, florid? No, poetry is to be read slowly and carefully, appreciating the nuance at every point. You should be able to read "past" python, while poetry is at least as much about the form of the expression as it is about what is being expressed. > Python is Dutch. > > Donn From claird at lairds.us Wed Apr 20 14:08:03 2005 From: claird at lairds.us (Cameron Laird) Date: Wed, 20 Apr 2005 18:08:03 GMT Subject: goto statement References: <20050420092359.81900.qmail@web8409.mail.in.yahoo.com> Message-ID: In article , Maxim Kasimov wrote: >Simon Brunning wrote: >> On 4/20/05, Maxim Kasimov wrote: >> >>>it would be quite useful for debuging porposes >> >> >> How does goto help you to remove bugs? >> >> I can certainly see how it helps you put them in in the first place... >> > >if you need to comment a couple of code (and then uncomment ), what are >you doing then? . . . I might understand the question. I often have if 0: # This is code we never should need; I # leave it here for expository purposes. print some_key_debugging_information() Does that help? From beliavsky at aol.com Fri Apr 22 11:12:56 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 22 Apr 2005 08:12:56 -0700 Subject: In defense of Visual Basic (was Re: Why Python does *SLICING* the way it does??) References: <1113976729.450677.261130@o13g2000cwo.googlegroups.com> <_Lm9e.23143$Xm3.17864@trndny01> <1114003997.778676.144950@z14g2000cwz.googlegroups.com> Message-ID: <1114182776.534932.264940@f14g2000cwb.googlegroups.com> Peter Hansen wrote: > > But I agree, having "the easiest thing for newbies" as your sole > > criterion for language design is a road to madness, for no other reason > > than that newbies don't stay newbies forever. > > If Visual BASIC is the example of "easiest thing for newbies", > then it disproves your theory already. I think VB newbies > *do* stay newbies forever (or as long as they are using just VB). Much snobbery is directed at Visual Basic and other dialects of Basic (they even have "basic" in their name), but I think VBA is better designed than the prestigious C in some important ways. Suppose you want to allocate a 2-D array at run-time and pass it to a procedure. The VBA code is just Option Explicit Option Base 1 Sub make_matrix() Dim x() As Double Dim n1 As Integer, n2 As Integer n1 = 2 n2 = 3 ReDim x(n1, n2) Call print_matrix(x) End Sub Sub print_matrix(xmat() As Double) Debug.Print UBound(xmat, 1), UBound(xmat, 2) 'do stuff with xmat End Sub It is trivial to allocate and pass multidimensional arrays in VBA, but C requires expertise with pointers. The subroutine print_matrix can query the dimensions of xmat, so they don't need to be passed as separate arguments, as in C. The fact that is tricky to do simple things is a sign of the poor design of C and similar languages, at least for non-systems programming. People bash VB as a language the corrupts a programmer and prevents him from ever becoming a "real" programmer. Maybe VB programmers quickly get so productive with it that they don't need to fuss with trickier languages. From mage at mage.hu Wed Apr 20 08:33:56 2005 From: mage at mage.hu (Mage) Date: Wed, 20 Apr 2005 14:33:56 +0200 Subject: exception handling Message-ID: <42664C34.9090802@mage.hu> Hello, def error_msg(msg): sys.exit(msg) try: do_something() if value != my_wish: error_msg('Invalid input') except: print "Fatal IO or Network error" This doesn't work because sys.exit raises an exception. I know that I can define exception types after except, but there might be many. Also I know I can write: except: if str(sys.exc_info()[0]) == 'exceptions.SystemExit': raise But honestly I would like simething like that: except (!SystemExit): Is this possible somehow? Mage From domma at procoders.net Thu Apr 14 14:49:01 2005 From: domma at procoders.net (Achim Domma (Procoders)) Date: Thu, 14 Apr 2005 20:49:01 +0200 Subject: Socket Error In-Reply-To: <1113503903.874232.322370@o13g2000cwo.googlegroups.com> References: <1113503903.874232.322370@o13g2000cwo.googlegroups.com> Message-ID: kingofearth.com at gmail.com wrote: > NameError: name 'socket' is not defined You forgot to import the socket module: import socket regards, Achim From steven.bethard at gmail.com Wed Apr 13 11:26:53 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 13 Apr 2005 09:26:53 -0600 Subject: Is socket.shutdown(1) useless In-Reply-To: <1113397224.402755.286570@o13g2000cwo.googlegroups.com> References: <1113397224.402755.286570@o13g2000cwo.googlegroups.com> Message-ID: <1aGdnT6IAY6mp8DfRVn-rQ@comcast.com> pyguy2 at gmail.com wrote: > In my python books I find exclusive use of socket.close(). From my > other readings, I know about a "partial close operation". So, I figured > it would be useful to post some code about how socket.close() has an > implicit send in it and you can actually gain some clarity by being > more explicit with the partial close which means splitting > socket.close() up into socket.shutdown(1) and socket.close(). > > And got a response in essence saying, why bother, socket.shutdown, > isn't useful. I had to use socket.shutdown once because the socket architecture we had relied on sending a piece of data, waiting for it to be processed, and then receiving a result back. The server on the other end of the socket wouldn't process anything until it was sure that all data had been sent. So our code basically looked like: s = socket.socket(...) s.connect(...) s.send(...) s.shutdown(1) data = s.makefile().read() s.close() STeVe From steven.bethard at gmail.com Wed Apr 13 11:08:08 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 13 Apr 2005 09:08:08 -0600 Subject: os.path.walk In-Reply-To: References: <425c9902$1@dnews.tpgi.com.au> Message-ID: Peter Hansen wrote: > Micheal wrote: > >> If I have os.path.walk(name, processDirectory, None) and processDirectory >> needs three arguments how can I ass them because walk only takes 3? > > The best answer to this is: if you aren't stuck > using a version of Python prior to 2.4, don't > use os.path.walk but use os.walk() instead... I believe os.walk was introduced in 2.3 (according to the docs[1]), so unless you're using a really old Python, you should be able to use it. I also agree that os.walk is *much* simpler. STeVe [1] http://docs.python.org/lib/os-file-dir.html#l2h-1628 From rschroev_nospam_ml at fastmail.fm Thu Apr 14 10:52:08 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Thu, 14 Apr 2005 14:52:08 GMT Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Apr 11) In-Reply-To: References: Message-ID: Simon Brunning wrote: > ... Not that it really matters, but does anybody know why the weekly Python news always arrives twice? Does it only happen to me, or does it happen to others too? It's not that it irritates me or anything, I'm just being curious. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From radam2 at tampabay.rr.com Sun Apr 3 09:53:42 2005 From: radam2 at tampabay.rr.com (Ron_Adam) Date: Sun, 03 Apr 2005 13:53:42 GMT Subject: Docorator Disected References: <4p9t419ockcg8578g6guse3a14t16orebf@4ax.com> <424f04d0.137947037@news.oz.net> <1112500967.391604.289760@f14g2000cwb.googlegroups.com> <0mqu41pham7n91vb1qgtoe567unn1cffb6@4ax.com> <424F8F0E.2010701@v.loewis.de> Message-ID: On Sun, 03 Apr 2005 08:37:02 +0200, "Martin v. L?wis" wrote: >Ron_Adam wrote: >>>Ah, so you did not know functions are objects just like numbers, >>>strings or dictionaries. I think you may have been influenced by other >>>languages where there is a concept of static declaration of functions. >> >> >> No, I did not know that you could pass multiple sets of arguments to >> nested defined functions in that manner. > >Please read the statements carefully, and try to understand the mental >model behind them. He did not say that you can pass around multiple >sets of arguments. He said that functions (not function calls, but >the functions themselves) are objects just like numbers. There is >a way of "truly" understanding this notion, and I would encourage >you to try doing so. Hello Martin, It is interesting how sometimes what we already know, and a new situation presented in an indirect way, can lead us to viewing an isolated situation in a biased way. That's pretty much the situation I've experienced here with this one point. I already knew that functions are objects, and objects can be passed around. My mind just wasn't clicking on this particular set of conditions for some reason, probably because I was looking too closely at the problem. (Starting off as a tech, with knowledge of how microchips work, can sometimes be a obstacle when programming in high level languages.) I'm sure I'm not the only one who's had difficulties with this. But I'm somewhat disappointed in myself for not grasping the concept as it is, in this particular context, a bit sooner. Cheers, Ron >Regards, >Martin From ivanlan at pauahtun.org Mon Apr 25 13:32:24 2005 From: ivanlan at pauahtun.org (Ivan Van Laningham) Date: Mon, 25 Apr 2005 11:32:24 -0600 Subject: Multiple tuples for one for statement References: <1114398216.258027.105070@g14g2000cwa.googlegroups.com> <200504251356.07715.james@wrong.nu> <426CF1D5.E9F4396@pauahtun.org> <200504251457.28724.james@wrong.nu> Message-ID: <426D29A8.38E7DB90@pauahtun.org> Peter Hansen wrote: > > Ivan Van Laningham wrote: > > I can see that now. I had three hours sleep last night and my brain > > hurts, so I don't get it. I seek enlightenment. > > So do I: did you mean you don't even "get" what > my code is doing...? Yes. I barely remember my own name right now. > > (My sample works only because I created tuples that > had exactly three items each, of course. It's the > same as your previous code which didn't work, except > for the number of elements in each tuple. I wrote > it just to show that R.C.James's idea was a reasonable, > if probably mistaken, interpretation of the OP's request.) > I worked out that the a,b,c must match the length of the tuples. The fog past that point is too dense. Metta, Ivan ---------------------------------------------- Ivan Van Laningham God N Locomotive Works http://www.andi-holmes.com/ http://www.foretec.com/python/workshops/1998-11/proceedings.html Army Signal Corps: Cu Chi, Class of '70 Author: Teach Yourself Python in 24 Hours From benji at benjiyork.com Fri Apr 15 19:47:53 2005 From: benji at benjiyork.com (Benji York) Date: Fri, 15 Apr 2005 19:47:53 -0400 Subject: Python Google Server In-Reply-To: <1112717390.981837.39400@l41g2000cwc.googlegroups.com> References: <1112696434.623557.97000@g14g2000cwa.googlegroups.com> <7x7jjhw7ro.fsf@ruckus.brouhaha.com> <1112717390.981837.39400@l41g2000cwc.googlegroups.com> Message-ID: <426052A9.5040201@benjiyork.com> Fuzzyman wrote: > The trouble is the current policy is 'whitelist only'... so I need the > proxy installed on a server that is *on the whitelist*... which will > take a little time to arrange. If you construct a noop translation (English to English for example) Google becomes a (HTML only) proxy. Here's an example: http://google.com/translate_c?langpair=en%7Cen&u=http://python.org/ -- Benji York From finite.automaton at gmail.com Fri Apr 29 18:04:09 2005 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: 29 Apr 2005 15:04:09 -0700 Subject: Sorting an Edge List References: Message-ID: <1114812249.753317.192080@f14g2000cwb.googlegroups.com> Sort demands a unique ordering, which isn't present in your case. You're constructing an Eulerian path. See Fleury's algorithm: http://en.wikipedia.org/wiki/Eulerian_path From fredrik at pythonware.com Fri Apr 15 16:21:11 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 15 Apr 2005 22:21:11 +0200 Subject: Python 2.4.1 hang References: <1113595275.615168.189790@o13g2000cwo.googlegroups.com> Message-ID: Mahesh wrote: > I needed to get to the POST body and while I was trying out various > regular expressions, one of them caused Python to hang. The Python > process was taking up 100% of the CPU. I couldn't even see the "Max > recursion depth exceeded message". Is this a bug? no, it's just a very stupid way to implement a trivial operation. > import re > > s = \ > """POST /TradeManagement-RT3/ReportController.Servlet HTTP/1.1 > /snip> > > #pattern_str = "^POST.*\\r\\n\\r((\\n)|(\\n[^\r]*))" > #pattern_str = "^POST.*\\n((\\n)|(\\n[^\r]*&))" > pattern_str = "^POST(.*\\n*)+\\n\\n" # <--- Offending pattern the first .* is a variable-length match. so is the second .*. and then you're putting it inside a repeated capturing group. and then you're applying it to a moderately large string. the poor engine has to check zillions of combinations before finding something that works. if you want to split on "\r\n\r\n", use split: header, body = message.split("\r\n\r\n") for more robust code, consider using the rfc822 module: f = StringIO.String(message) request = f.readline() header = rfc822.Message(f) body = f.read() From gtg856h at mail.gatech.edu Wed Apr 27 23:46:34 2005 From: gtg856h at mail.gatech.edu (Brian Kazian) Date: Wed, 27 Apr 2005 23:46:34 -0400 Subject: TKinter and Python Sync. Problems Message-ID: I am currently having trouble running a piece of code I have written. My main code is called new.py, and when I run it, it pops up the TKinter root window as specified. However, if I try perform a function that uses an imported module, the code crashes, giving me this error: Exception in Tkinter callback Traceback (most recent call last): File "C:\Python24\lib\lib-tk\Tkinter.py", line 1345, in __call__ return self.func(*args) File "C:\jython\new.py", line 38, in save_var var = expression.Variable(name, description) AttributeError: 'module' object has no attribute 'Variable' Now, when I close the TKinter window that popped up when the code was compiled, an identical one is opened in its place. If I perform the same action as before, the program works flawlessly. Also worth noting is that when this same file is run from SPE, this problem does not ocur. Does anyone have any idea why this would happen? I do not understand why a new Window is created when I try to close it if run from the command line. Also, I don't understand why it can't find the proper module the on the first run, but can on the second. It seems weird that it doesn't also happen from the IDE. Another interesting thing to note is that if I run the module that it chokes on intially, ie. 'python expr.py', it brings up the GUI associated with the main code. The problem is, there is no TKinter related code in the expr module! If any additional info or clarification would be helpful, please let me know. Thanks in advance for the help, as I am truly perplexed as to what is going on!! From carsten at uniqsys.com Tue Apr 12 10:30:23 2005 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 12 Apr 2005 10:30:23 -0400 Subject: Informixdb: New maintainer, new version Message-ID: <1113316222.16002.51.camel@dot.uniqsys.com> Hi Everybody: Since the current maintainer of the informixdb module appears to have gone missing, I have decided to take over the project. The new home of the informixdb module is http://sourceforge.net/projects/informixdb . Version 1.4 features the following improvements: * Build uses distutils instead of deprecated Makefile.pre.in mechanism. * Connect method takes optional username and password parameters for connecting to a remote database. * Cursor attribute .sqlerrd exposes Informix's sqlca.sqlerrd resulting from the cursor's most recent .execute() call. If you have any questions or comments, please let me know. Best regards, -- Carsten Haese - Software Engineer | Phone: (419) 861-3331 Unique Systems, Inc. | FAX: (419) 861-3340 1446 Reynolds Rd, Suite 313 | Maumee, OH 43537 | mailto:carsten at uniqsys.com From nav+posts at bandersnatch.org Wed Apr 20 11:57:44 2005 From: nav+posts at bandersnatch.org (Nick Vargish) Date: 20 Apr 2005 11:57:44 -0400 Subject: How to Convert a makefile to Python Script References: <1113968971.081613.140640@l41g2000cwc.googlegroups.com> Message-ID: <87ll7d5tl3.fsf@localhost.localdomain> rkoida at yahoo.com writes: > I am working on a Problem to convert makefile in to a python script. > Are there any Modules? Please try to comment. How about this (untested): -------- cut here -------- import subprocess print ("import os") make = subprocess.Popen(["make", "-n"],stdout=subprocess.PIPE) makeout = make.communicate()[0] for l in makeout.split('\n'): print 'os.system("%s")' % l.replace('"', '\"') -------- cut here -------- The quote escaping replace() might not be quite right, but you get what I'm suggesting, right? To mangle a lwall quote, "The only substitute for make is make." Nick -- # sigmask (lambda deprecation version) 20041028 || feed this to a python print ''.join([chr(ord(x)-1) for x in 'Ojdl!Wbshjti!=ojdlAwbshjti/psh?']) From ali.jan at gmail.com Tue Apr 19 08:06:13 2005 From: ali.jan at gmail.com (Ali) Date: 19 Apr 2005 05:06:13 -0700 Subject: MessageBox ONOK? Message-ID: <1113912372.980136.9870@g14g2000cwa.googlegroups.com> Hi, How do i connect the onOK of a win32ui MessageBox with the Ok button so that I get to know when the user clicks the Ok button? Regards, Ali From lee at example.com Thu Apr 28 16:18:27 2005 From: lee at example.com (Lee Harr) Date: Thu, 28 Apr 2005 20:18:27 GMT Subject: interactive web graphics References: Message-ID: On 2005-04-27, Eckhoff, Michael A wrote: > Hello, > > I failed to locate a list for pygtk, so I thought I'd > ask my question here. Is it possible to write CGI > scripts that bring up a GUI (as in GTK+, QT, Tk, ...) > or an openGL display that is windowed inside a web > browser? > How about the blender web plugin? http://www.blender.org/modules/bc2002/plugin.html I am not sure the plugin has been updated to match recent blender releases, but recent blenders offer python scripting. Could be interesting anyhow. From bokr at oz.net Wed Apr 13 16:45:30 2005 From: bokr at oz.net (Bengt Richter) Date: Wed, 13 Apr 2005 20:45:30 GMT Subject: Python license (2.3) References: Message-ID: <425d6ebd.300805455@news.oz.net> On Wed, 13 Apr 2005 13:30:18 -0400, "Terry Reedy" wrote: > >"Antoon Pardon" wrote in message >news:slrnd5pqfh.lf2.apardon at rcpc42.vub.ac.be... >> I see this as my contribution to the communities who has provided me >> with all kinds of things that are usefull to me. I'm willing to put >> time into this, > >Great. My human, non-lawyer advice, if I were to give it, would be to >worry less and remember that PSF exists to promote Python, not to sue >Python promoters. > >>From what I understand from what you have written, you have written code >for a tutorial based on one module of the library. I personally would >treat this minor extraction differently from a 'derived' work consisting of >an alternate interpreter + library, such as from ActiveState, or Enthought, >or Jython, or Iron-Python. I think I would simply put lines in the header >something like: >"Derived from module heapify in the library included with CPython 2.x, (C) >, available from www.python.org/wherever. > As with code, perhaps authoritative and well-done examples for different situations would be the easiest to take patterns from. If there were a collection of URLs to various such software and their license notices in the wiki, perhaps that would help well motivated people like Antoon. If it is important to get right, maybe the PSF should hire a lawyer to work up some paradigmatic examples and put them in the wiki? BTW, I dislike large legal boilerplate (that IIRC I've even seen occupying more lines than the code it was describing in a few cases). Is a simple one-line notice referring to the full license text somewhere legally sufficient? How do you make the reference unambiguous? Md5 or SHA hash? Regards, Bengt Richter From aleksander.helgaker at gmail.com Wed Apr 20 08:18:17 2005 From: aleksander.helgaker at gmail.com (aleksander.helgaker at gmail.com) Date: 20 Apr 2005 05:18:17 -0700 Subject: building a small calculator Message-ID: <1113999497.480245.47240@g14g2000cwa.googlegroups.com> I'm learning to program python on my Mac and I'd like some help. I followed a tutorial which showed how to make a calculator for working out the area of a shape. E.g. the area of a circal is pi*r*r. To practice a bit I thought I'd make the program more advanced but I'm already having difficoulties. Here is what I have so far. # Area calculation program print "Welcome to the Area calculation program" print "---------------------------------------" print # Print out the menu: print "Please select a shape:" print "1 Rectangle" print "2 Circle" print "3 Square" # Get the user's choice: shape = input("> ") # Calculate the area: if shape == 1: height = input("Please enter the height: ") width = input("Please enter the width: ") area = height*width print "The area is", area elif shape == 2: radius = input("Please enter the radius: ") area = 3.14*(radius**2) print "The area is", area else: length = input("Please input the length: ") area = length**2 print "The area is", area Now once the user has select a shape and typed in the lengths required, the result is printed and the program quits. What I want to do is make the program display the result and then make it wait for the user to press return (or something like that) after which the screen will be cleared and they'll be back at the main menu. Also I would like to add option nr 4 to the menu and make that the quit command, but what command does python have to stop a program? I tried end but that did not work. From cam.ac.uk at mh391.invalid Fri Apr 29 18:21:43 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Fri, 29 Apr 2005 23:21:43 +0100 Subject: Best way to parse file into db-type layout? In-Reply-To: <7v1371pn9gvsh52m7nld6ddjm9b9k3elgf@4ax.com> References: <7v1371pn9gvsh52m7nld6ddjm9b9k3elgf@4ax.com> Message-ID: John Machin wrote: > [Michael Hoffman]: > >>for row in csv.reader(fileinput.input()): > > csv.reader requires that if the first arg is a file that it be opened > in binary mode. fileinput.input() is not a file. I have tested this code and it works fine for the provided example. -- Michael Hoffman From pgmoscatt at optushome.com.au Wed Apr 13 04:53:01 2005 From: pgmoscatt at optushome.com.au (Peter Moscatt) Date: Wed, 13 Apr 2005 18:53:01 +1000 Subject: A command in a String ? References: Message-ID: , Thanks for the help on this. Yea the 'exec' did the trick. The second example just placed all the strings in one option button. Pete On Wed, 13 Apr 2005 10:34:20 +0200, Fredrik Lundh wrote: > Peter Moscatt wrote: > >>I have a rather odd question: >> >> Is there a way Python can execute a command within a string ? >> >> For example if I had something like: >> _str = "fm=OptionMenu(root,xx,'string1','string2','string3')" >> >> And the execute _str. > > exec _str > >> The reason why I am trying to do this that as I am aware the OptionMenu >> hasn't the ability insert options therefore the options would be inserted >> by manipulating strings. > > does this do what you want? > > strings = "string1", "string2", "string3" > fm = OptionMenu(root, xx, *strings) > > From michele.simionato at gmail.com Thu Apr 28 01:20:13 2005 From: michele.simionato at gmail.com (Michele Simionato) Date: 27 Apr 2005 22:20:13 -0700 Subject: (PHP or Python) Developing something like www.tribe.net In-Reply-To: <1114663336.926935.97910@f14g2000cwb.googlegroups.com> References: <1113835147.364885.304290@l41g2000cwc.googlegroups.com> <1114503432.227799.52670@o13g2000cwo.googlegroups.com> <1114587592.260950.181990@l41g2000cwc.googlegroups.com> <1114587846.011299.125420@g14g2000cwa.googlegroups.com> <1114663336.926935.97910@f14g2000cwb.googlegroups.com> Message-ID: <1114665613.879362.75100@l41g2000cwc.googlegroups.com> Mir Nazim: > Can you please brief me a bit about your decision to CherryPy Decision? I made no decision about CherryPy, I am actually a Quixote user. I evalued CherryPy six months ago and I did not like it, since they were using custom classes and a strange compilation procedure. However, from the presentation I saw at the ACCU conference, it looks like now CherryPy is much more pythonic than before (use the definition you like for pythonic). If I was shopping for a web framework today, I would certainly consider CherryPy. CherryPy and Quixote are in the same league, Zope and Twisted and PEAK are in an enterely different league. They are meant for programming in the large and do not scale well for small size applications. CherryPy and Quixote are for programming in the small, I have not idea how they scale in the large. Is your application going to be large (many developers, hundred of components, hundreds of thousand of lines of code) or small? Michele Simionato From philippe at philippecmartin.com Thu Apr 28 14:01:16 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Thu, 28 Apr 2005 18:01:16 GMT Subject: how can I sort a bunch of lists over multiple fields? References: <1114623282.855415.132040@l41g2000cwc.googlegroups.com> <1114625172.700855.263140@l41g2000cwc.googlegroups.com> Message-ID: How about using the csv module instead of splitting ? wittempj at hotmail.com wrote: > What you want I guess is to read first all lines of the file into a > string as you did, and then let the split method split it based on > newlines only - see example below. > > Then you use split again to put all elements of one line into another > list - split it on commas. > > Now you can define sortfunctions for all columns you want to sort, e.g. > like below - and use those to compare elements. You get a script like: > -#!/usr/bin/env python > - > -def cmp_index(a, b, ndx): > - if a[ndx] < b[ndx]: > - return -1 > - elif a[ndx] > b[ndx]: > - return 1 > - else: > - return 0 > - > -def cmp_0(a, b): > - return cmp_index(a, b, 0) > - > -def cmp_1(a, b): > - return cmp_index(a, b, 1) > - > -s = 'Kikker en Eend,Max Veldhuis\nDikkie Dik,Jet Boeke\nRuminations on > C++,Andrew Koenig & Barbara Moo' > -s = s.split('\n') > -l = [] > -for i in s: > - l.append(i.split(',')) > - > -l.sort(cmp_0) > -print l > -l.sort(cmp_1) > -print l > > with output like: > martin at ubuntu:~ $ ./test.py > [['Dikkie Dik', 'Jet Boeke'], ['Kikker en Eend', 'Max Veldhuis'], > ['Ruminations on C++', 'Andrew Koenig & Barbara Moo']] > [['Ruminations on C++', 'Andrew Koenig & Barbara Moo'], ['Dikkie Dik', > 'Jet Boeke'], ['Kikker en Eend', 'Max Veldhuis']] > martin at ubuntu:~ $ From duncan.booth at invalid.invalid Fri Apr 1 03:20:33 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 1 Apr 2005 08:20:33 GMT Subject: string goes away References: Message-ID: Andreas Beyer wrote: > I loved to use > >>> string.join(list_of_str, sep) > instead of > >>> sep.join(list_of_str) > > I think the former is much more telling what is happening than the > latter. However, I will get used to it. No need to get used to it. Just reverse the order of the arguments and use: str.join(sep, list_of_str) Alternatively it can be clearer if you bind a name to the bound method: joinLines = '\n'.join joinWords = ' '.join lines = joinLines(somelines) words = joinWords(somewords) From RonGrossi_38_2513 at yahoo.com Wed Apr 13 14:27:37 2005 From: RonGrossi_38_2513 at yahoo.com (RonGrossi_38_2513 at yahoo.com) Date: 13 Apr 2005 11:27:37 -0700 Subject: =?iso-8859-1?q?THE_GREATEST_NEWS_EVER!_=B0=BA=B7=2E=5F=2E=5F=2E?= =?iso-8859-1?q?=B7=BA=B0=60=B0=BA=B7=2E=5F=2E=5F=2E=B7=BA=B0=60=B0?= =?iso-8859-1?q?=BA=B7=2E=5F=2E=5F=2E=B7=BA=B0=60=B0=BA=B7=2E=5F=2E?= =?iso-8859-1?q?=5F=2E=B7=BA=B0=60=B0=BA=B7=2E=5F=2E=5F=2E=B7=BA=B0?= =?iso-8859-1?q?=60=B0=BA=B7=2E=5F=2E=5F=2E=B7=BA=B0=60=B0=BA=B7=2E?= =?iso-8859-1?q?=5F=2E=5F=2E=B7=BA=B0=60=B0=BA=B7=2E=5F=2E=5F=2E=B7?= =?iso-8859-1?q?=BA=B0=60=B0=BA=B7=2E=5F=2E=5F=2E=B7=BA=B0=60=B0=BA?= =?iso-8859-1?q?=B7=2E=5F=2E=5F=2E=B7=BA=B0=60=B0=BA=B7=2E=5F=2E=5F?= =?iso-8859-1?q?=2E=B7=BA=B0=60=B0=BA=B7=2E=5F=2E=5F=2E=B7=BA=B0=60?= =?iso-8859-1?q?=B0=BA=B7=2E=5F=2E=5F=2E=B7=BA=B0=60=B0=BA=B7=2E=5F?= =?iso-8859-1?q?=2E=5F=2E=B7=BA=B0=60=B0=BA=B7=2E=5F=2E=5F=2E=B7=BA?= =?iso-8859-1?q?=B0=60=B0=BA=B7=2E=5F=2E=5F=2E=B7=BA=B0=60=B0=BA=B7?= =?iso-8859-1?q?=2E=5F=2E=5F=2E=B7_=28newsgroup-post_134=29?= Message-ID: <1113416856.914310.63930@l41g2000cwc.googlegroups.com> The Greatest News Ever! http://groups-beta.google.com/group/alt.politics.bush/browse_thread/thread/f9b35b05a72da1e1/66f1a43881a0fe82#66f1a43881a0fe82 ?._._.???`???._._.???`???._._.???`???._._.???`???._._.???`???._._.??._._.???`???._._.???`???._._.???`???._._.???`???._._.???`???._._.??._._.???`???._._.???`???._._.???`???._._.???`???._._.???`???._._.??._._.???`???._._.???`???._._.???`???._._.???`???._._.???`???._._.??._._.???`???._._.???`???._._.???`???._._.???`???._._.???`???._._.??._._.???`???._._.???`???._._.???`???._._.???`???._._.???`???._._.??._._.???`???._._.???`???._._.???`???._._.???`???._._.???`???._._.??._._.???`???._._.???`???._._.???`???._._.???`???._._.???`???._._.??._._.???`???._._.???`???._._.???`???._._.???`???._._.???`???._._.??._._.???`???._._.???`???._._.???`???._._.???`???._._.???`???._._.? __________________________________________ The reason some people don't know for sure if they are going to Heaven when they die is because they just don't know. The good news is that you can know for sure that you are going to Heaven which is described in the Holy Bible as a beautiful place with no death, sorrow, sickness or pain. God tells us in the Holy Bible how simple it is to be saved so that we can live forever with Him in Heaven. "For if you confess with your mouth Jesus is Lord and believe in your heart that God raised Him from the dead, you WILL BE SAVED." (Romans 10:9) Over 2000 years ago God came from Heaven to earth in the person of Jesus Christ to shed His blood and die on a cross to pay our sin debt in full. Jesus Christ was born in Israel supernaturally to a virgin Jewish woman named Mary and lived a sinless life for thirty-three years. At the age of thirty-three Jesus was scourged and had a crown of thorns pressed onto His head then Jesus was crucified. Three days after Jesus died on a cross and was placed in a grave Jesus rose from the dead as Jesus said would happen before Jesus died. If someone tells you that they are going to die and in three days come back to life again and it happens then this person must be the real deal. Jesus Christ is the only person that ever lived a perfect sinless life. This is why Jesus is able to cover our sins(misdeeds) with His own blood because Jesus is sinless. The Holy Bible says, "In Him(Jesus) we have redemption through His blood, the forgiveness of sins..." (Ephesians 1:7) If you would like God to forgive you of your past, present and future sins just ask Jesus Christ to be your Lord and Saviour. It doesn't matter how old you are or how many bad things that you have done in your life including lying and stealing all the way up to murder. Just pray the prayer below with your mouth and mean it from your heart and God will hear you and save you. Dear Jesus Christ, I want to be saved so that I can have a home in Heaven with You when I die. I agree with You that I am a sinner. I believe that You love me and want to save me. I believe that You bled and died on the cross to pay the penalty for my sins and that You rose from the dead. Please forgive my sins and come into my heart and be my Lord and Saviour. Thanks Lord Jesus Christ for forgiving me and saving me through Your merciful grace. Amen. Welcome to the family of God if you just allowed God to save you. Now you are a real Christian and you can know for sure that you will live in Heaven forever when this life comes to an end. As a child of God we are to avoid sin(wrongdoing), but if you do sin the Holy Bible says, "My dear children, I write this to you so that you will not sin. But if anybody does sin, we have one who speaks to the Father in our defense Jesus Christ, the Righteous One." Those of you that have not yet decided to place your trust in the Lord Jesus Christ may never get another chance to do so because you do not know when you will die. This means that if you die without trusting in Jesus Christ as your Lord and Saviour you will be forever separated from the love of God in a place called Hell. The Holy Bible descibes Hell as a place of eternal torment, suffering, pain and agony for all those who have rejected Jesus Christ. The good news is that you can avoid Hell by allowing Jesus Christ to save you today. Only then will you have true peace in your life knowing that no matter what happens you are on your way to Heaven. Servant of the Lord Jesus Christ, Internet Evangelist Ronald L. Grossi ____________________________________________________ Got Questions? http://www.gotquestions.org/archive.html Other Languages http://www.godssimpleplan.org/gsps.html Free Movie: To Hell and Back http://www.tbn.org/index.php/8/1.html Animation http://www.browser.to/jesus-animation The Passion Of The Christ http://www.thepassionofthechrist.com Beware Of Cults http://www.carm.org/cults/cultlist.htm About Hell http://www.equip.org/free/DH198.htm Is Jesus God? http://www.powertochange.com/questions/qna2.html Free Online Bible http://www.bibledatabase.net From gandalf at geochemsource.com Thu Apr 7 06:34:33 2005 From: gandalf at geochemsource.com (Laszlo Zsolt Nagy) Date: Thu, 07 Apr 2005 12:34:33 +0200 Subject: import statement - package visibility problem Message-ID: <42550CB9.8060309@geochemsource.com> Hi All! I have the following structure: /Lib/Server/Db/ __init_.py DatabaseConnection.py Adapters/ __init__.py FireBirdConnection.py Important file contents are: /Lib/Server/Db/__init__.py: import DatabaseConnection import Adapters /Lib/Server/Db/DatabaseConnection.py: class DatabaseConnection(object): pass /Lib/Server/Db/Adapters/__init__.py import FireBirdConnection /Lib/Server/Db/Adapters/FireBirdConnection.py: from DatabaseConnection import DatabaseConnection class FireBirdConnection(DatabaseConnection): pass Here is the problem. I go to the directory where 'Lib' resides. Then I do: C:\Temp\ccc>python Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import Lib Traceback (most recent call last): File "", line 1, in ? File "Lib\__init__.py", line 1, in ? import Server File "Lib\Server\__init__.py", line 1, in ? import Db File "C:\Python\Lib\Db\__init__.py", line 29, in ? import Adapters File "C:\Python\Lib\Db\Adapters\__init__.py", line 21, in ? import FireBirdConnection File "Db\Adapters\FireBirdConnection.py", line 27, in ? ImportError: No module named DatabaseConnection >>> My problem is that Lib/Server/Db/Adapters/FireBirdConnection.py does not see Lib/Server/Db/DatabaseConnection.py. Of course I read the documentation about the import statement but I do not see a good solution. Possible solutions and their drawbacks: Solution 1: Put the 'Db' directory into my PYTHONPATH or append it to "sys.path". It is too bad. This could make my 'Db' module visible but this is not a good solution. For example, I can have this module structure: Lib/ Client/ Db/ Adapters/ Server/ Db/ Adapters/ E.g. there could be two "Db" modules, one for Client and one for Server. Clearly, I cannot add EVERY module path to sys.path. It would be ambiguous to import 'Adapters', for example. Solution 2: Add the outermost 'Lib' directory to sys.path and use fully qualified module names. In the example above I could use this: /Lib/Server/Db/Adapters/FireBirdConnection.py: from Lib.Server.Db.Adapters.DatabaseConnection import DatabaseConnection In this case FireBirdConnection.py would be dependent on the full module path. Otherwise it is independent on the whole module path, it only depends on the 'upper level' module, regardless of its name. So here are the problems with this solution: - What if I want to rename 'Server' to 'Middletire'? Should I change all of my files inside the 'Midletire' dir? -What if I would like to unify the server and client Db sides? Should I rename "from Lib.Server.Db.Adapters.DatabaseConnection import DatabaseConnection" to "from Lib.Db.Adapters.DatabaseConnection import DatabaseConnection" in all files? - Lastly, the import statements are too long. They are hard to manage. I would like to use something like from __uppermodule__.DatabaseConnection import DatabaseConnection but probably there is a standard Pythoninc way to do it. Just I can't find it. Maybe we can start a new PEP on this. :-) Please advise. p.s.: sorry for the long e-mail -- _________________________________________________________________ Laszlo Nagy web: http://designasign.biz IT Consultant mail: gandalf at geochemsource.com Python forever! From xnews2 at fredp.lautre.net Thu Apr 14 17:24:32 2005 From: xnews2 at fredp.lautre.net (Fred Pacquier) Date: 14 Apr 2005 21:24:32 GMT Subject: Supercomputer and encryption and compression @ rate of 96% References: <1113470846.970773.4780@g14g2000cwa.googlegroups.com> <425e47a9$0$26352$db0fefd9@news.zen.co.uk> Message-ID: Christos "TZOTZIOY" Georgiou said : > Well, I take advantage of this "folding" idea for years now. Do you > remember DoubleSpace? I was getting to the limits [1] of my 100 MiB > hard disk, so I was considering upgrading my hardware. A female > friend of mine, knowing a little but not a lot about MS-DOS asked the > eye-opening question: "why don't you reapply double space to the > compressed drive?" Any BBS-era old-timers here remember NABOB ? :-) -- YAFAP : http://www.multimania.com/fredp/ From timr at probo.com Wed Apr 27 02:48:24 2005 From: timr at probo.com (Tim Roberts) Date: Tue, 26 Apr 2005 23:48:24 -0700 Subject: ADODB Currency type broken in Python win32? Message-ID: It looks to me like the handling of the currency type in an ADODB connecction from Python is broken. Currency data in an Access database is stored as a 64-bit integer, scaled by 10000. In an ADODB recordset, this is returned as a 2-tuple, where the second element is the currency value, but the value is stored as a normal integer, not a lont integer. Thus, it fails for values greater than about $214,700 (2**32 / 10**4). Here is an example: import win32com.client conn = win32com.client.Dispatch("ADODB.Connection") conn.Open("DRIVER={Microsoft Access Driver (*.mdb)};DBQ=anydatabase.mdb") cmd = win32com.client.Dispatch("ADODB.Command") cmd.ActiveConnection = conn cmd.CommandText = "SELECT CCur(250000) AS myMoney;" rs = cmd.Execute()[0] for f in rs.Fields: print f.Name print f.Type print f.Value One would expect myMoney 6 (0, 2500000000L) Instead, we get: myMoney 6 (0, -1794967296) The value has wrapped at 2**31. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From tzot at sil-tec.gr Wed Apr 20 12:00:30 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 20 Apr 2005 19:00:30 +0300 Subject: goto statement References: <20050420092359.81900.qmail@web8409.mail.in.yahoo.com> <42664190.6010507@i.com.ua> <87vf6hlkix.fsf@wilson.rwth-aachen.de> <70sc615akd7mfdkmrjls956o1u5rglm74t@4ax.com> Message-ID: On Wed, 20 Apr 2005 18:38:40 +0300, rumours say that Maxim Kasimov might have written: >> If you need more help, I would gladly send you the output of `man vi' >> from a non-GNU Unix. I can also send you the output of `man vim' from a >> GNU system. >is it wrong to debug python script using python, but not some magic commands found somewhere in man ? If you really believe you should use python to debug (and edit perhaps?) python, use idle and X11 forwarding through your ssh connection instead of vi. Then you have menu-driven block un/commenting and un/indenting. Otherwise, I believe your reply above is slightly adrift (you wondered what one can do to comment a block of code when using vi, and I replied to that; I don't quite understand what your exact point is.) -- TZOTZIOY, I speak England very best. "Be strict when sending and tolerant when receiving." (from RFC1958) I really should keep that in mind when talking with people, actually... From gvandyk.nospam at agileworks.net Mon Apr 18 10:33:12 2005 From: gvandyk.nospam at agileworks.net (Gerrit van Dyk) Date: Mon, 18 Apr 2005 16:33:12 +0200 Subject: ANN: Python Training In South Africa Message-ID: AgileWorks (Pty) Ltd will be presenting an "Introduction to Python" training course at "The Innovation Hub" from the 4-6th of May 2005. For more detail visit our website: (http://www.agileworks.net/AgileWorks/Training/Python/) From klaus at seistrup.dk Mon Apr 18 04:29:27 2005 From: klaus at seistrup.dk (Klaus Alexander Seistrup) Date: Mon, 18 Apr 2005 08:29:27 +0000 (UTC) Subject: Parse command line options References: <1113811225.458022.195270@g14g2000cwa.googlegroups.com> Message-ID: Hue wrote: > try: > > opts,args = getopt.getopt(sys.argv[1:], 'n:t:h:i:o:', > ["Number=","time=","help=","image_file=","Output Filename="]) > > except getopt.GetoptError: > print 'Unrecognized argument or option' > usage() > sys.exit(0) Proceed with e.g.: #v+ for (opt, arg) in opts: if opt in ('-n', '--No'): do_no() elif opt in ('-t', '--Time'): do_time() # [...] else: barf(opt, arg) # end if # end for #v- But be consistent when using long options: use all lowercase, use either dashes or underscores (not both), don't use whitespace. I usually do something like: #v+ Options = { 'i:': 'input=', 'o:': 'output=', 'c' : 'copyright', 'h' : 'help', 'v' : 'version', } shortOpts = ''.join(Options.keys()) longOpts = Options.values() # [...] try: (opts, args) = getopt.getopt(argv[1:], shortOpts, longOpts) except getopt.error, msg: die(msg) # end try # [...] for (opt, arg) in opts: # Handle all options : # end for #v- Additional, non-option, arguments will be in the "args" variable. Cheers, -- Klaus Alexander Seistrup Magnetic Ink, Copenhagen, Denmark http://magnetic-ink.dk/ From matt.fryer at gmail.com Wed Apr 27 10:36:28 2005 From: matt.fryer at gmail.com (Matt) Date: 27 Apr 2005 07:36:28 -0700 Subject: Which IDE is recommended? In-Reply-To: <426f90ac$1_2@rain.i-cable.com> References: <426f90ac$1_2@rain.i-cable.com> Message-ID: <1114612588.435456.296960@z14g2000cwz.googlegroups.com> The ActiveGrid IDE is a sample app with wxPython. It has a lot of good features including a source code debugger that allows you to debug wx apps and set breakpoints from the code editor. I am also biased though--I work on that IDE and use it for all my coding. Its pretty far along on Windows and getting better on Linux. We just got it working on a Mac yesterday so that version won't be out for a bit. From franz.steinhaeusler at utanet.at Tue Apr 5 05:38:50 2005 From: franz.steinhaeusler at utanet.at (Franz Steinhaeusler) Date: Tue, 05 Apr 2005 11:38:50 +0200 Subject: Change between Python 2.3 and 2.4 under WinXP References: <4251d375$0$23625$9b622d9e@news.freenet.de> Message-ID: On Tue, 05 Apr 2005 01:53:25 +0200, "Martin v. L?wis" wrote: >Fredrik Lundh wrote: > >> I'm not aware of any other tool that solves that specific problem. > >notepad does a fine job at creating batch files, IMO. > >Of course, it is not all that clear what the OP actually wanted. >[...] Hi, here I am again, the OP :) I think, I considered the problem more complicated as it is in fact. Maybe a batch file (py23.bat: c:\python23\python.exe should be enough) thanks again! -- Franz Steinh?usler http://drpython.sourceforge.net/ http://mitglied.lycos.de/drpython/ From peufeu at free.fr Wed Apr 13 11:32:24 2005 From: peufeu at free.fr (peufeu at free.fr) Date: Wed, 13 Apr 2005 17:32:24 +0200 Subject: database in python ? References: <1113197530.990898.46130@z14g2000cwz.googlegroups.com> <200504130853.31989.hancock@anansispaceworks.com> <1113339252.851450.184620@z14g2000cwz.googlegroups.com> Message-ID: >> postgresql >> is slower than MySQL, at least for modest size tables. There must, I When not using transactions, MySQL will blow away postgres in INSERT/UPDATE speed until the concurrency gets up a bit and the readers block writers strategy used by MyISAM starts to show its weaknesses. This is in agreement with mass hosting for instance, a lot of small databases on a mysql will not have concurrency problems. Of course when not using transactions you have to remind that your data is not secure, and any power crash might corrupt your database. Postgres on a RAID with battery backed up cache will no longer have to sync the disk on each transaction so it gets a lot faster, and you still have data security. You can also run it with fsync=off for a massive speedup in transactions per second but you lose data security. When using transactions (innodb) I've read that postgres is a bit faster. Regarding query optimization, for simple dumb queries like grabbing a row from a table, mysql will be a little faster (say 0.2 vs 0.3 ms), and for medium complex queries like joins on >= 4 medium sized tables (>10 K rows) postgres can be faster by anything from 1x to 1000x. I've seen it happen, the same query taking 0.5 seconds in my and 0.5 ms in postgres, simply because mysql can't plan it correctly. >> suppose, >> be some turnover point on the size of the database? Or are you arguing >> that >> postgresql is now faster than MySQL in the general case? Can you I'd suggest that on anything medium postgres will be a lot faster. > I don't know about the whole picture, but I know form evidence on this > group that there are PostgreSQL driver modules (the name "psycopg" comes > to mind, but this may be false memory) that appear to take diabolical > liberties with DBAPI-2.0, whereas my experience with MySQLdb has been > that I can interchange the driver with mxODBC (for example) as a drop-in > replacement (modulo the differing paramstyles :-(). psycopg is extremely fast and powerful, so it makes a lot more things that the dbapi says. I'd say that database independence is an utopia, once you start to use triggers and stored procedures and specific column types, you'll be more or less tied to one database, and doing this is necessary to get good performance and generally do things right. From rschroev_nospam_ml at fastmail.fm Mon Apr 11 11:13:20 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Mon, 11 Apr 2005 15:13:20 GMT Subject: database in python ? In-Reply-To: <5n2qi2-g9g.ln1@pluto.i.infosense.no> References: <1113197530.990898.46130@z14g2000cwz.googlegroups.com> <1113216765.784331.156820@f14g2000cwb.googlegroups.com> <5n2qi2-g9g.ln1@pluto.i.infosense.no> Message-ID: Ola Natvig wrote: > MySQL has support for transactions and foreign keys in it's InnoDB > engine. In 5.0 it supports views procedures. Some people seems to hate > MySQL :-) but a whole lot of other people like it a lot. There are other problems, such as failing silently in many circumstances, as documented on http://sql-info.de/mysql/gotchas.html. I'm not saying these issues should make one avoid MySQL at all costs, but I think one should at least be aware of them. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From jerf at jerf.org Thu Apr 14 16:17:25 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Thu, 14 Apr 2005 16:17:25 -0400 Subject: Supercomputer and encryption and compression @ rate of 96% References: <1113470846.970773.4780@g14g2000cwa.googlegroups.com> <425e47a9$0$26352$db0fefd9@news.zen.co.uk> <425e8d34$0$2589$da0feed9@news.zen.co.uk> Message-ID: On Thu, 14 Apr 2005 17:44:56 +0200, Fredrik Lundh wrote: > Will McGugan wrote: > >> Muchas gracias. Although there may be a bug. I compressed my Evanescence >> albumn, but after decompression it became the complete works of Charles > > strange. the algorithm should be reversible. sounds like an operating > system bug. what system are you using? > > After I compressed my OS (on the other machine) with your code, none, apparently. From simon.brunning at gmail.com Wed Apr 20 06:36:45 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Wed, 20 Apr 2005 11:36:45 +0100 Subject: goto statement In-Reply-To: <42662f0a$1_2@news.bluewin.ch> References: <20050420092359.81900.qmail@web8409.mail.in.yahoo.com> <42662f0a$1_2@news.bluewin.ch> Message-ID: <8c7f10c6050420033658165014@mail.gmail.com> On 4/20/05, Maurice Caret wrote: > > other equivalents are in > > http://docs.python.org/tut/node10.html I also missed , for the while statement. Those URLs just keeg getting better... -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From donn at drizzle.com Sun Apr 24 13:32:21 2005 From: donn at drizzle.com (Donn Cave) Date: Sun, 24 Apr 2005 17:32:21 -0000 Subject: Variables References: <426B0283.40602@cloudthunder.com> <426b255d.375304108@news.oz.net> <86ll78r63a.fsf@guru.mired.org> Message-ID: <1114363940.742689@yasure> Quoth Mike Meyer : ... | He's right - programming is an offshoot of mathematics. It adds | *dynamics* to the structures of mathematics. In mathematics, a | construct (graph, function, mapping, set, whatever) is immutable. You | can talk about things that change with time, but you do so with a | function f(t) that describes the changes to the thing over time - and | *that* function is immutable. You can say that it isn't time that's | changing, but frobnitz, with the same function describing the change - | and you get the same structures that you got with time. | | This change causes a fundamental change in the way practitioners | *look* at objects. Which is visible as a change in the | vocabulary. Yes, you can talk about programming with the vocabulary of | mathematics. But that's like dancing about architecture (*). There's a school of thought that holds this to be kind of an offshoot of programming, too, albeit a dominant one at present. In a "pure" functional programming language like Haskell for example, the "=" operator is equational in about the same way as it is in mathematics. Even Haskell's equivalent of "foo = raw_input()", the notation that appears to create a variable is strictly bound to an underlying system of functions and equations that preserves this equational property, and maybe for the sake of harmony between mathematicians this system could be applied to Python's semantics to show how it works in these terms. I guess it couldn't be done without some hand-waving, due to non-functional structures like loops, but those are just details. So here's a tiny Haskell example that reads a line from input and prints it out with quotes around it: module Main (main) where main = do line <- getLine putStrLn (show line) "main" is (=) a function that can be executed with that result. This executability is a property of the "IO Monad", and this function has that type -- main :: IO () -- but that's more than we need to know for the present purposes. The point is that this "do" structure looks like a statement syntax, but it's strictly equivalent to another more functional notation main = getLine >>= (\line -> putStrLn (show line)) Haskell's lambda syntax: \ arg -> expression. You could read this aloud as "bind getLine to a lambda function with one parameter ..." and the result is a functional relation that can be executed. Each step binds a function to a lamba that forms the entire rest of the "do" block, not just the next step -- it's a nested sequence, not a linear one. So I'm proposing that Python's = operator is like Haskell's "<-", and "foo = 5" is conceptually like "bind 5 to a lambda with one argument "foo" implementing the rest of the procedure body." The confusion is not because foo needs to be so different, it's that Python "=" is not at all math "=". Donn Cave, donn at drizzle.com From steve at holdenweb.com Tue Apr 5 10:53:45 2005 From: steve at holdenweb.com (Steve Holden) Date: Tue, 05 Apr 2005 10:53:45 -0400 Subject: Real ython Poetry [was: Re: boring the reader to death...] In-Reply-To: <424e8d1d$1@nntp0.pdx.net> References: <424e8d1d$1@nntp0.pdx.net> Message-ID: <4252A679.2030102@holdenweb.com> Scott David Daniels wrote: > Sunnan wrote: > >> ...Because what is "boring"? The opposite of dense, tense, intense. >> Utterly predictable; it's like the combination of all my prejudices. >> Even before I knew, I thought "Bet Python separates statements from >> expressions". > > > Python is for terse, pithy prose; Python is not for poetry. > > --Scott David Daniels > Scott.Daniels at Acm.Org I though that too, until Michael Spencer sent me the following executable Python limerick, which I declared the PyCon limerick competition and read as a part of my closing address: # Freely re-distributable under Poetic License* # Voice only the alphanumeric tokens from itertools import repeat for feet in [3,3,2,2,3]: print " ".join("DA-DA-DUM" for dummy in [None] for foot in repeat("metric", feet)) *thanks to Peter Hansen regards Steve -- Steve Holden +1 703 861 4237 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ From chad at zetaweb.com Tue Apr 26 23:58:42 2005 From: chad at zetaweb.com (Chad Whitacre) Date: Tue, 26 Apr 2005 23:58:42 -0400 Subject: parse tree has symbols not in the grammar? Message-ID: Hey all, I've been playing around with the parser module, and based on the documentation I would expect all symbols in a parse tree to be part of the grammar.[1] For example, I find this line in the symbol module docs: Refer to the file Grammar/Grammar in the Python distribution for the definitions of the names in the context of the language grammar.[2] However, the program below gives me a human-readable parse tree (also below) that contains symbols that don't seem to be in the grammar, e.g., small_stmt, expr_stmt, factor. Is my expectation wrong? Thanks. chad ---------- [1] http://python.org/doc/ref/grammar.txt [2] http://python.org/doc/lib/module-symbol.html ############################ # A PROGRAM # ############################ #!/usr/bin/env python """print out a human-readable parse tree for a simple code block """ import parser, symbol, token from pprint import pprint def experiment(block): """experimenting, like the man said """ ast = parser.suite(block) raw = ast.tolist() def interp(x): """given an int or a string, return a symbol, token, or other string """ if type(x) is type(0): if x < 256: return token.tok_name[x] else: return symbol.sym_name[x] return x def process(raw): """recursively convert a raw parse tree into something readable """ for node in raw: if type(node) is type([]): process(node) else: raw[raw.index(node)] = interp(node) process(raw) pprint(raw) experiment("""\ x = 3 for y in range(10): y == x """) ############################ # ITS OUTPUT # ############################ ['file_input', ['stmt', ['simple_stmt', ['small_stmt', ['expr_stmt', ['testlist', ['test', ['and_test', ['not_test', ['comparison', ['expr', ['xor_expr', ['and_expr', ['shift_expr', ['arith_expr', ['term', ['factor', ['power', ['atom', ['NAME', 'x']]]]]]]]]]]]]]], ['EQUAL', '='], ['testlist', ['test', ['and_test', ['not_test', ['comparison', ['expr', ['xor_expr', ['and_expr', ['shift_expr', ['arith_expr', ['term', ['factor', ['power', ['atom', ['NUMBER', '3']]]]]]]]]]]]]]]]], ['NEWLINE', '']]], ['stmt', ['compound_stmt', ['for_stmt', ['NAME', 'for'], ['exprlist', ['expr', ['xor_expr', ['and_expr', ['shift_expr', ['arith_expr', ['term', ['factor', ['power', ['atom', ['NAME', 'y']]]]]]]]]]], ['NAME', 'in'], ['testlist', ['test', ['and_test', ['not_test', ['comparison', ['expr', ['xor_expr', ['and_expr', ['shift_expr', ['arith_expr', ['term', ['factor', ['power', ['atom', ['NAME', 'range']], ['trailer', ['LPAR', '('], ['arglist', ['argument', ['test', ['and_test', ['not_test', ['comparison', ['expr', ['xor_expr', ['and_expr', ['shift_expr', ['arith_expr', ['term', ['factor', ['power', ['atom', ['NUMBER', '10']]]]]]]]]]]]]]]], ['RPAR', ')']]]]]]]]]]]]]]], ['COLON', ':'], ['suite', ['NEWLINE', ''], ['INDENT', ''], ['stmt', ['simple_stmt', ['small_stmt', ['expr_stmt', ['testlist', ['test', ['and_test', ['not_test', ['comparison', ['expr', ['xor_expr', ['and_expr', ['shift_expr', ['arith_expr', ['term', ['factor', ['power', ['atom', ['NAME', 'y']]]]]]]]]], ['comp_op', ['EQEQUAL', '==']], ['expr', ['xor_expr', ['and_expr', ['shift_expr', ['arith_expr', ['term', ['factor', ['power', ['atom', ['NAME', 'x']]]]]]]]]]]]]]]]], ['NEWLINE', '']]], ['DEDENT', '']]]]], ['NEWLINE', ''], ['ENDMARKER', '']] From bokr at oz.net Fri Apr 1 03:39:22 2005 From: bokr at oz.net (Bengt Richter) Date: Fri, 01 Apr 2005 08:39:22 GMT Subject: System bell References: <20050331235011.GD1786@ActiveState.com> Message-ID: <424d0662.7277153@news.oz.net> On Fri, 01 Apr 2005 02:06:07 -0500, Steve Holden wrote: >Trent Mick wrote: >> [Baza wrote] >> >>>Am I right in thinking that >>>print "\a" should sound the system, 'bell'? >> >> >> It works on the shell on Windows for me (WinXP). >> >> Trent >> >Interesting. From a Cygwin bash shell I got an elegant little dingish >sort of a beep (my volume control was set kind of low). I then ran the >same code in a Windows shell and nearly deafened myself. It appears that >the volume control doesn't affect the Windows XP commans shell beep - >even muting the Windows audio output doesn't stop it (though it does >stop the Cygwin beep). This could cause heart attacks! > Another couple of data points: Running python 2.3/MSVC6 or python 2.4/MinGW in an NT4 console window, print '\a' beeps via the PC internal speaker (like winsound.Beep). Running the bash shell of msys, echo -e '\a' also beeps via the PC speaker. These are not affected by any volume control that I know of. But running py2.3 idle, print '\a' displays a square empty box (which I take to be the symbol for "unprintable" characters). That seems like an oversight in terminal emulation. Regards, Bengt Richter From m at m.com Wed Apr 27 09:40:49 2005 From: m at m.com (monkey) Date: Wed, 27 Apr 2005 21:40:49 +0800 Subject: Can .py be complied? References: <426ec8f7_2@rain.i-cable.com> <426f562f$1_3@rain.i-cable.com> Message-ID: <426f9661$1_2@rain.i-cable.com> > And then example.pyc will appear beside example.py. This new file does > not require example.py (you can even delete it), and works on any > computer with Python installed Filip, you can read through my mind (-: You just told me what I want to know exactly, even I can't ask the question correctly. Thx.. > python24\python -OO) > and then import your example.py, you will get a file example.pyo, > which is also stripped of any documentation strings (a bit harder to > decode). Is .pyo still not secure for serious purpose? The -OO function refer to which area of python that I can read a doc in details? > The end-user needs the JRE, not Python. > > Kent Actually I still not dare to touch Jython, because I am still digging python now. But the JRE may not attract end-user, because it is still associate with "slow" and "eating much system resource", although Java is sure a respectfully programming language. What do you think? From peter at engcorp.com Thu Apr 28 20:57:51 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 28 Apr 2005 20:57:51 -0400 Subject: anonymous function objects? In-Reply-To: References: <7x7jimlfnj.fsf@ruckus.brouhaha.com> Message-ID: Uwe Mayer wrote: > Unfortunately I want to assign a handler function to an object and something > like this does not work: > >>>>class Foobar(object): pass > > ... > >>>>a = Foobar() >>>>def a.handler(): > > File "", line 1 > def a.handler(): > ^ > SyntaxError: invalid syntax But this does work, or something close to it: >>> class Foobar(object): pass ... >>> def handler(self): ... print 'in handler' ... >>> f = Foobar() >>> f.handler() Traceback (most recent call last): File "", line 1, in ? AttributeError: 'Foobar' object has no attribute 'handler' >>> >>> import new >>> f.handler = new.instancemethod(handler, f) >>> f.handler() in handler -Peter From max2 at fisso.casa Sat Apr 9 17:30:34 2005 From: max2 at fisso.casa (max(01)*) Date: Sat, 09 Apr 2005 21:30:34 GMT Subject: visibility between modules Message-ID: <_PX5e.1205415$35.44366387@news4.tin.it> hi. if i have a single program file, different class instances can share information in (at least) two fashions: 1. using instance variables: class AClass: def __init__(self): self.att_1 = 42 self.att_2 = "Hello!" class AnotherClass: def __init__(self): self.att_1 = anInstanceOfAClass.att_1 anInstanceOfAClass = AClass() anInstanceOfAnotherClass = AnotherClass() print anInstanceOfAnotherClass.att_1 ### This should print out 42 2. using globals: class AClass: def __init__(self): self.att_1 = 42 self.att_2 = "Hello!" class AnotherClass: pass aGlobalString = "No way." anInstanceOfAClass = AClass() anInstanceOfAClass.att2 = aGlobalString anInstanceOfAnotherClass = AnotherClass() anInstanceOfAnotherClass.att_1 = aGlobalString print anInstanceOfAClass.att2 ### This should output "No way." print anInstanceOfAnotherClass.att_1 ### And this too ---- i admit i prefer the fisrt way to do it. i have tried to make it work even if the "main program" and each class definition reside in different files, but i could not make it work: max2 at 172.17.1.201:/tmp$ cat AClass.py class AClass: def __init__(self): self.att_1 = 42 self.att_2 = "Hello!" max2 at 172.17.1.201:/tmp$ cat AnotherClass.py class AnotherClass: def __init__(self): self.att_1 = anInstanceOfAClass.att_1 max2 at 172.17.1.201:/tmp$ cat Main.py from AClass import * from AnotherClass import * anInstanceOfAClass = AClass() anInstanceOfAnotherClass = AnotherClass() print anInstanceOfAnotherClass.att_1 ### This should print out 42 max2 at 172.17.1.201:/tmp$ python Main.py Traceback (most recent call last): File "Main.py", line 4, in ? anInstanceOfAnotherClass = AnotherClass() File "/tmp/AnotherClass.py", line 3, in __init__ self.att_1 = anInstanceOfAClass.att_1 NameError: global name 'anInstanceOfAClass' is not defined max2 at 172.17.1.201:/tmp$ ---- any suggestion? bye max From lbruno at republico.estv.ipv.pt Thu Apr 7 06:31:11 2005 From: lbruno at republico.estv.ipv.pt (Luis Bruno) Date: Thu, 7 Apr 2005 11:31:11 +0100 Subject: logging as root using python script In-Reply-To: References: <1112847155.108154.180290@g14g2000cwa.googlegroups.com> <20050407105048.00004cd2@LAB2-13.esi> Message-ID: <20050407113111.000059aa@LAB2-13.esi> Martin Franklin wrote: > another alternative would be setuid I also thought about making the script setuid root, but I'm under the impression that Linux (at least) won't honor the suid bit on a script. That's from memory though. Cheers! From t.bettio at transnorm.ch Wed Apr 20 13:49:47 2005 From: t.bettio at transnorm.ch (Tiziano Bettio) Date: Wed, 20 Apr 2005 19:49:47 +0200 Subject: newbie question In-Reply-To: References: <465db603.0504191314.5d074cf8@posting.google.com> <1113947675.400070.319430@o13g2000cwo.googlegroups.com> Message-ID: <4266963B.3060001@transnorm.ch> Cameron Laird wrote: >In article , >Tiziano Bettio wrote: > . > . > . > > >>If u want to achieve high performance you'd rather use c++ and directly >>access libs like nvidias cg, ms directx or opengl... >> >> > . > . > . >Yes. Well, maybe. Python-coded programs, even graphically-intense >games, *can* exhibit good performance, and there are numerous >anecdotes about applications LOSING speed on conversion to C++ from >Python. Moreover, there's no inherent conflict between C++ and >Python; some successful applications use both. > >My summary: it's a subtler matter than, "for performance, abandon >Python on favor of C++". I think you know that, but I want to make >it explicit for less-experienced readers. > > yeah well, i didn't intended to say it in this specific way. tough to be more exact: for a game you can realize up to 95% in python without losing the needed performance. but there's almost always a little part where u really need to get even the last bit of performance out of the hardware or where nobody has already ported the lib you need into python, where c++ comes in rather handy. I didn't ment to offend any pythonian (wouldn't want to offend myself...), but i think we all agree that sometimes all of us have seen or even programmed something in c++ (or other languages) what could come in really handy for a project one is working on. so again, didn't ment to say that it's a performance matter (there are thousands of bad c++ programmers out there which are hiding behind compiled code...) :) cheers tc From aleksander.helgaker at gmail.com Wed Apr 20 08:31:15 2005 From: aleksander.helgaker at gmail.com (aleksander.helgaker at gmail.com) Date: 20 Apr 2005 05:31:15 -0700 Subject: building a small calculator In-Reply-To: References: <1113999497.480245.47240@g14g2000cwa.googlegroups.com> Message-ID: <1114000275.227950.50870@f14g2000cwb.googlegroups.com> I get the following error message when using the command sys.exit(). name 'sys' is not defined. From fredrik at pythonware.com Fri Apr 8 16:05:04 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 8 Apr 2005 22:05:04 +0200 Subject: problem saving tif files with PIL References: Message-ID: "mchl gdbt" wrote: > Ideally, I want the output image to be identical to the original in every way. I suspect that it > might be enough to just change the size numbers though I don't know how. I will be messing around > with the pixel colours eventually but the structure of the image must remain basically identical > so that application B works as before. PIL's an image manipulation library, not a TIFF manipulation library. for TIFF manipulation, using pytiff (and the underlying libtiff library) is probably your best bet: http://pubweb.northwestern.edu/~omh221/software_projects/pytiff/ From chromeclouds at yahoo.co.uk Tue Apr 12 06:55:56 2005 From: chromeclouds at yahoo.co.uk (Mark) Date: 12 Apr 2005 03:55:56 -0700 Subject: Cannot import mod_python modules Message-ID: <6c9897c2.0504120255.1f274@posting.google.com> Hi, I've just installed the Win32 build of mod_python 3.1.4 for Python 2.4 and have setup my Apache config file with the LoadModule and PythonHandler directives and then copied "mod_python.so" to my Apache modules directory. I restarted Apache and decided to do a quick cgi.test() and it shows that mod_python listed under server software section. OK, next I tried mptest.py, but I get an Internal Server Error. The traceback recorded in the error log says "No module named _apache" mptest.py: from mod_python import apache def handler(req): req.write("Hello World!") return apache.OK Why doesn't this work? or rather what have I missed? From vze4rx4y at verizon.net Sat Apr 30 04:44:21 2005 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Sat, 30 Apr 2005 08:44:21 GMT Subject: Micro-PEP: str.translate(None) to mean identity translation References: <4272e00c.260731842@news.oz.net> Message-ID: [Bengt Richter] > Just thought None as the first argument would be both handy and mnemonic, > signifying no translation, but allowing easy expression of deleting characters, > e.g., > > s = s.translate(None, 'badcharshere') Log a feature request on SF and assignment to me. I'll put this in for you. Raymond Hettinger From sunnan at handgranat.org Tue Apr 5 20:42:04 2005 From: sunnan at handgranat.org (Sunnan) Date: Wed, 06 Apr 2005 00:42:04 GMT Subject: Lambda: the Ultimate Design Flaw In-Reply-To: References: <87is3663cn.fsf@wilson.rwth-aachen.de> <3b99ncF6fd2apU1@individual.net> <3g_3e.134005$dP1.471451@newsc.telia.net> Message-ID: T.D. Lassagne wrote: > Please consider joining the International Sarcasm Society. Our motto is > "Like We Need YOUR Support". I *recognize* sarcasm; I just don't think it's very funny. Now parody, which this turned out to be, I can appreciate. From deetsNOSPAM at web.de Sat Apr 2 08:17:31 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Sat, 02 Apr 2005 15:17:31 +0200 Subject: Python plug-in Frameworks like Eclipse RCP... References: Message-ID: Jim Hargrave wrote: > Hum, maybe my question was too specific. What I would really like to > know is what is the best way to implement a Python application with a > pluggable architecture. In particular, I would like to use wxPython and > have plug ins automatically register themselves with the GUI by adding > themselves to the mean or adding a tab. Again this is much like Eclipse > RCP - but forget that part :-) This is close to beeing trivial in python - just utilize __import__ to dynamically load modules that shall act as plugins. These modules then only have to follow a sort of protocol - lets say you have a module called pluginloader.py that has a register-function. The loaded module could import pluginloader and register itself, or a class defined in itself. Like this ---------plugin_example.py------------- import pluginloader class ExamplePlugin(pluginloader.PluginBase): def __init__(self,...): .... pluginloader.register(ExamplePlugin()) ------------------------ -- Regards, Diez B. Roggisch From peufeu at free.fr Tue Apr 12 07:21:14 2005 From: peufeu at free.fr (=?iso-8859-15?Q?Pierre-Fr=E9d=E9ric_Caillaud?=) Date: Tue, 12 Apr 2005 13:21:14 +0200 Subject: semicolons References: <425AF6AB.900@mage.hu> Message-ID: sometimes i'll write if( key in myarray ) { ... in PHP and then realize I have to use array_key_exists and curse that the parameters are key then array, and bless scite auto-api-display for saving me each time... From removethis.kartic.krishnamurthy at gmail.com Thu Apr 28 18:02:52 2005 From: removethis.kartic.krishnamurthy at gmail.com (Kartic) Date: Thu, 28 Apr 2005 22:02:52 GMT Subject: why "import wx" doesn't work? In-Reply-To: <42715a8b$1_1@rain.i-cable.com> References: <427126ca$1_3@rain.i-cable.com> <42715a8b$1_1@rain.i-cable.com> Message-ID: The Great 'monkey' uttered these words on 4/28/2005 5:50 PM: >>Which version of wxPython are you running? What do you mean by "does not >>work"...does the import fail or is your code giving errors? > > > It is the current new version 2.6. The error message said that the class > wxApp is not defined... > But when using the default "from wxPython.wx import *", it works. See my previous post for examples... you are mixing the new import style and old style of using the classes. That will not work. Thanks, -K From codecraig at gmail.com Fri Apr 22 13:41:49 2005 From: codecraig at gmail.com (codecraig) Date: 22 Apr 2005 10:41:49 -0700 Subject: gui developing In-Reply-To: References: Message-ID: <1114191709.671893.254560@o13g2000cwo.googlegroups.com> I am fairly new to Python as well. However, coming from a Java background and Swing...I jumped into Jython. It let me use my previous swing knowledge to make GUI's. However, python comes with Tkinter which is the 'standard' gui library. I'd suggest checking out Tkinter, but i dont have much experience with others. some other ones I have heard about... wxWidgest, and Python Card From jfouhy at paradise.net.nz Tue Apr 26 19:13:09 2005 From: jfouhy at paradise.net.nz (jfouhy at paradise.net.nz) Date: 26 Apr 2005 16:13:09 -0700 Subject: goto statement References: <20050420092359.81900.qmail@web8409.mail.in.yahoo.com> <3cmtgvF6q13cvU1@individual.net> Message-ID: <1114557189.561270.233350@f14g2000cwb.googlegroups.com> Tim Daneliuk wrote: > OK - Here's some reasoning that may illuminate it. We could, in theory, > reduce any language to the minimal Boehm & Jacopini control structures > (iirc there were only four). In effect, anything beyond these is > syntactic sugar. IOW, feel free to use a minimalist Turing Machine > to implement your next 100,000 line program. Now, how does it go ... #!/usr/bin/env python _pc = 1 while True: if _pc == 1: # statement 1 _pc = _pc + 1 elif _pc == 2: # statement 2 _pc = _pc + 1 elif pc == 3: # statement 3 _pc = 17 # GOTO 17 elif pc == 4: # statement 4 _pc = _pc + 1 ... else: # Fallen off the end of our program. break From lostboard2001 at yahoo.com Fri Apr 1 20:44:03 2005 From: lostboard2001 at yahoo.com (lostboard2001 at yahoo.com) Date: 1 Apr 2005 17:44:03 -0800 Subject: Search-and-delete text processing problem... In-Reply-To: <0eadnS8Lk5Aaa9DfRVn-gw@speakeasy.net> References: <0eadnS8Lk5Aaa9DfRVn-gw@speakeasy.net> Message-ID: <1112406243.575705.99350@g14g2000cwa.googlegroups.com> Close: > if line[:4] == 'Bill': . ^^ > line == ' ' > From iayork at panix.com Tue Apr 26 15:07:12 2005 From: iayork at panix.com (Ian A. York) Date: Tue, 26 Apr 2005 19:07:12 +0000 (UTC) Subject: python on mac keystroke References: <2Fhbe.1394$zu.7@newssvr13.news.prodigy.com> Message-ID: In article <2Fhbe.1394$zu.7 at newssvr13.news.prodigy.com>, Eric Texier wrote: >I am testing python on a mac. In the python console, none of the >control as the arrow to scroll back to a preview line are >working. How can I fix this. If I understand what you're asking, you need to install readline, which isn't included in the OSX Python. Ian -- Ian York (iayork at panix.com) "-but as he was a York, I am rather inclined to suppose him a very respectable Man." -Jane Austen, The History of England From cjw at sympatico.ca Thu Apr 7 10:22:14 2005 From: cjw at sympatico.ca (Colin J. Williams) Date: Thu, 07 Apr 2005 10:22:14 -0400 Subject: Best editor? In-Reply-To: <1112755142.335149.218220@g14g2000cwa.googlegroups.com> References: <1112725379.514651.66540@l41g2000cwc.googlegroups.com> <1112755142.335149.218220@g14g2000cwa.googlegroups.com> Message-ID: Paul McGuire wrote: > SciTE (Scintilla Text Editor) is just right for me too. Low overhead, > great just as a Notepad alternative, but with good coding support too. > > -- Paul > Yes, I use SciTE. Syntax marking and multiple buffers. Works with Windows and Linux. Boa-constructor (Scintilla based editor), aside from being a GUI designer, provides all of the above, with a debug capability. PythonWin (scintilla based editor) is Windows only. It provides the Edit/Debug functionality of Boa and has an excellent auto-completion facility - this is particularly helpful when one doesn't remember the name or parameters of a function of method. It currently has a bug which slows things down at times but, I understand that this is fixed in the forthcoming build 204. From philippe at philippecmartin.com Thu Apr 14 19:17:02 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Thu, 14 Apr 2005 23:17:02 GMT Subject: Using python from a browser/security hole References: Message-ID: Since I need to access a local/client device from the page and that I wish to be cross-platform; does that mean Java is my only way out ? Regards, Philippe Neil Hodgson wrote: > Philippe: > >> I read that IE had the capability to embedd Python scripts, but what >> about the others ? > > While Python can be set up as a scripting language for IE, this is > normally disabled as it could be a security hole. The open call is > available from Python scripts so a web site could read or destroy your > files. > > Neil From bokr at oz.net Sun Apr 17 18:14:37 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 17 Apr 2005 22:14:37 GMT Subject: pre-PEP: Suite-Based Keywords References: <3cc186F6lodv5U1@individual.net> <4261c943.136032804@news.oz.net> <3cf2qfF6jo33oU1@individual.net> Message-ID: <4262c4b2.200399789@news.oz.net> On Sun, 17 Apr 2005 15:25:04 +0200, Reinhold Birkenfeld wrote: >Bengt Richter wrote: > >> Stretching for it, using my latest and greatest ;-) >> >> y = f(**:: >> x = 1 >> y = 'y for f' >> )*g(**:: >> x = 'x for g' >> y = 'y for g' >> def foo(): return 'foo for g' >> ) >> >> Note that there is no problem adding other parameters, because :: is just >> a unary expression returning dict subtype instance, e.g., >> >> y = f(11,22,**:: >> x = 1 >> y = 'y for f' >> )*g(*args_from_somewhere, **:: >> x = 'x for g' >> y = 'y for g' >> def foo(): return 'foo for g' >> ) > >You know that this is dead ugly? What aspect in particular? I.e., does this (currently legal) look prettier: y = f(11,22, **dict( x = 1, y = 'y for f' ))*g(*args_from_somewhere, **dict( x = 'x for g', y = 'y for g', foo = lambda: return 'foo for g' )) Can you express the same semantics in a prettier way? To boil it down, doesn't a suite bindings expression like d = :: x = 1 y = 'y for f' (which in this case doesn't even need parens) seem prettier than d = dict( x = 1, y = 'y for f' ) to you, especially given that (:: ...) gives you the power of full suite syntax to create bindings any way you want[1], not just keyword= ? (and you can leave out the commas ;-) [1] I.e., this should work to extend the power of the type expression in a way that shows what you can't do with dict(...) ;-) type('C', (), :: def __repr__(self): return ''% (hex(id(self)&(2L**32-1)) def cname(self): return type(self).__name__ classvar = 123 # ... anything you can do in a class definition body ) IMO that's pretty clean. > >The real ``problem'' (if you see one) is that the indentation syntax >doesn't allow for suites in expressions. I was trying to solve that "problem" with my "suite expressions" ;-) :: # suite bindings expression (as ordered dict) def(): # anonymous def (): # thunk (anonymous callable suite sharing local namespace) I think suite indentation rules for suite expressions are not that hard, once you decide to deal with it as a separate indentation space from outside the expression. That's already done to allow multiline expressions without indentation interpretation inside bracketed expressions. This is just adding indentation processing within certain types of expressions ("suite expressions" ;-) For the most part I like indentation syntax very well, and I suspect that if there were optional brackets, you would still be indenting for clarity, so the chances are the bracket version of the above would mainly add bracket noise to something close to the above. Regards, Bengt Richter From codecraig at gmail.com Thu Apr 14 18:31:17 2005 From: codecraig at gmail.com (codecraig) Date: 14 Apr 2005 15:31:17 -0700 Subject: SimpleXMLRPCServer - disable output In-Reply-To: References: <1113509250.602995.25500@o13g2000cwo.googlegroups.com> Message-ID: <1113517877.473126.259590@o13g2000cwo.googlegroups.com> Jeremy Jones wrote: > codecraig wrote: > > >Hi, > > I thought I posted this, but its been about 10min and hasnt shown up > >on the group. > > Basically I created a SimpleXMLRPCServer and when one of its methods > >gets called and it returns a response to the client, the server prints > >some info out to the console, such as, > > > >localhost - - [14/Apr/2005 16:06:28] "POST /RPC2 HTTP/1.0" 200 - > > > >Anyhow, is there a way I can surpress that so its not printed to the > >console? I looked at SimpleXMLRPCServer.py ...it doesn't explicitly > >print that, I think perhaps std is...but not sure. Any ideas?? > > > >thanks. > > > > > > > Here's the entire SimpleMLRPCServer class from SimpleXMLRPCServer.py: > > > class SimpleXMLRPCServer(SocketServer.TCPServer, > SimpleXMLRPCDispatcher): > """Simple XML-RPC server. > > Simple XML-RPC server that allows functions and a single instance > to be installed to handle requests. The default implementation > attempts to dispatch XML-RPC calls to the functions or instance > installed in the server. Override the _dispatch method inhereted > from SimpleXMLRPCDispatcher to change this behavior. > """ > > def __init__(self, addr, requestHandler=SimpleXMLRPCRequestHandler, > logRequests=1): > self.logRequests = logRequests > > SimpleXMLRPCDispatcher.__init__(self) > SocketServer.TCPServer.__init__(self, addr, requestHandler) > > You should be able to change logRequests to 0 and that should fix it. I just tested it at a prompt and it worked just fine. > > > Jeremy Jones Jeremy, So can you explain what I can do to set logRequests = 0? Do i just do.. server = SimpleXMLRPCServer(0) ??? I am sorta new to python thanks. From jimmy at retzlaff.com Fri Apr 15 20:37:07 2005 From: jimmy at retzlaff.com (Jimmy Retzlaff) Date: Fri, 15 Apr 2005 17:37:07 -0700 Subject: py2exe - create one EXE Message-ID: Codecraig wrote: > i tried the SingleInstaller link....which points to a > script using NSIS. I followed those instructions which generated an > .exe. HOwever, when i run the .exe nothing happens (meaning no > process starts, no output, no errors, nothing). > > any ideas on that? have ever used it? There are a couple of things you can try. First off, if you are using Python 2.4, then you may be missing msvcr71.dll and/or msvcp71.dll on the system you are trying to run on (the corresponding file(s) for Python 2.3 and earlier are extremely common so you aren't nearly as likely to run into this problem). Look for the line that looks like this in the NSIS script: File /r '${py2exe..... And add this line just after it (assuming you installed Python in the default location): File 'C:\Python24\msvc*.*' If you intend to distribute your result, then you can Google this group for discussions about msvcr71.dll and license requirements for redistribution - you won't find a definitive answer to the questions you'll see, but you should be aware of the issues. If that doesn't solve your problem, the next step to debugging it is to try running the multi-file version produced by setup.py. If that doesn't work, some common problems/workarounds can be found on the py2exe wiki. Obviously the single file version won't work until the multi file version works. Chris Liechti has another solution, but the last time I checked it was only for Python 2.3. It's on his page at: http://homepage.hispeed.ch/py430/python/ Jimmy From wnebfynj at mnovryyb.pbz Thu Apr 7 07:36:51 2005 From: wnebfynj at mnovryyb.pbz (JZ) Date: Thu, 7 Apr 2005 13:36:51 +0200 Subject: Best editor? References: <1112725379.514651.66540@l41g2000cwc.googlegroups.com> Message-ID: <7a2mcsi6t3u8$.jw7lghv8brwt.dlg@40tude.net> Dnia 5 Apr 2005 11:22:59 -0700, ChinStrap napisa?(a): > Opinions on what the best is? Eclipse + plugins: pydev (http://pydev.sourceforge.net/updates/) and subclipse(http://subclipse.tigris.org/update/). It is free, stable, contains integrated (visual) debugger, code completion, refactoring, PyLint for deep analise of python code, and fine work with SVN. For win32 lighter solution is PythownWin (http://activestate.com/Products/ActivePython/). It's very stable, fast and has very good debugger. -- JZ From mefjr75 at hotmail.com Tue Apr 26 00:46:54 2005 From: mefjr75 at hotmail.com (M.E.Farmer) Date: 25 Apr 2005 21:46:54 -0700 Subject: Pickle an image? In-Reply-To: References: Message-ID: <1114490814.513103.180490@g14g2000cwa.googlegroups.com> GMane Python wrote: > Hey all. > I have a ( list | tuple | dictionary ) with several graphics in it. > Trying to cPickle it to a file, I get errors. For instance, > UnpickleableError: Cannon pickle objects. > > Anyone know of a way to get around this? I'd like to pickle a list or > dictionary of about 5 .JPG images. > > Thanks! > Dave Open your images in binary mode and read them in as binary strings then save them in a list/dict/tuple , then pickle it. >>> import Image, pickle, cStringIO >>> i = open('c:/1.jpg', 'rb') >>> i.seek(0) >>> w = i.read() >>> i.close() >>> dic = {'1':w,'2':w,'3':w,'4':w} >>> p = pickle.dumps(dic) # storage would happen at this point Ok now you take your pickled string and unpickle your object and select the item you want and put it in a cStringIO or StringIO so we can open it directly with PIL. # sometime in the future >>> o = pickle.loads(p) >>> one_im = o['1'] >>> c = StringIO.StringIO() >>> c.write(one_im) >>> c.seek(0) >>> im = Image.open(c) >>> im.show() Alternatively you can create a StringIO object and pickle that in your dictionary so you can just load it later with PIL. Pickling will bloat the size of your file so you might want to use some compression, although most formats will compress very little the pickling overhead can __mostly__ be avoided. There are boundless ways to do this and this just one of them. hth, M.E.Farmer From steven.bethard at gmail.com Thu Apr 21 11:10:49 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 21 Apr 2005 09:10:49 -0600 Subject: deprecation of has_key? In-Reply-To: References: <1114069715.945176.73750@l41g2000cwc.googlegroups.com> <426775C8.3000303@holdenweb.com> Message-ID: Denis S. Otkidach wrote: > On Thu, 21 Apr 2005 08:50:25 -0600 Steven Bethard wrote: > > SB> Huh? I'm not following your logic. Why is "item in dict" less > SB> readable than "dict.has_key(item)"? Something to do with expecting > SB> inverses that don't exist? > SB> > SB> Personally, I use "item in dict" because it's quite readable to me, > SB> and generally faster. > > For me dictionary is a collection of key-value pairs, but not a > collection of keys (that's what set is). Ahh, ok. Now I understand. I think you could probably search the python-dev archives and see why the decision was made as it was. For pretty much all my purposes, "key in dict" is much more useful than "item in dict". Practicality beats Purity and all. ;) STeVe From iny+news at iki.fi Fri Apr 22 00:32:03 2005 From: iny+news at iki.fi (Ilpo =?iso-8859-1?Q?Nyyss=F6nen?=) Date: Fri, 22 Apr 2005 07:32:03 +0300 Subject: Regular Expressions - Python vs Perl References: <1114092105.964664.211430@l41g2000cwc.googlegroups.com> Message-ID: James Stroud writes: > Is it relevant that Python can produce compiled expressions? I don't think > that there is such a thing with Perl. The problem in python here is that it needs to always recompile the regexp. I would like to have a way to write a regexp as a constant and then python should compile that regexp to the byte-code file. This is a problem when one has a big amount of regexps. One example is the xmlproc parser in PyXML, This is not a problem in a program that continues to run long times, but I want short lived programs like command line apps. Of course we do have ways to go around that limitation, but that is just ugly. -- Ilpo Nyyss?nen # biny # /* :-) */ From hancock at anansispaceworks.com Wed Apr 20 09:18:35 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Wed, 20 Apr 2005 08:18:35 -0500 Subject: Why Python does *SLICING* the way it does?? In-Reply-To: <_Lm9e.23143$Xm3.17864@trndny01> References: <1113976729.450677.261130@o13g2000cwo.googlegroups.com> <_Lm9e.23143$Xm3.17864@trndny01> Message-ID: <200504200818.35304.hancock@anansispaceworks.com> On Wednesday 20 April 2005 01:36 am, Raymond Hettinger wrote: > > > Many people I know ask why Python does slicing the way it does..... [...] > Python's way has some useful properties: [...] > OTOH, it has some aspects that bite: [...] > I suspect that whether it feels natural depends on your previous background and > whether you're working in an environment with arrays indexed from one or from > zero. For instance, C programmers are used to seeing code like: for(i=0 ; > i to N: a[I]=f(I); NEXT. Hence, the C coders may find Python's a[:n] to be > more natural than BASIC programmers. Well, I learned Basic, Fortran, C, Python --- more or less. And I first found Python's syntax confusing as it didn't follow the same rules as any of the previous ones. However, I used to make "off by one" errors all the time in both C and Fortran, whereas I hardly ever make them in Python. So I like Python's slicing because it "bites *less*" than intervals in C or Fortran. Cheers, Terry -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From polykrombelcentercom Sat Apr 30 16:45:06 2005 From: polykrombelcentercom (Zoool (at dot)) Date: Sat, 30 Apr 2005 22:45:06 +0200 Subject: [newbie] Embedding Flash OCX object References: <6ZadnfF---HWO-7fRVnyuw@scarlet.biz> <6URce.2055$2f2.1166@newssvr19.news.prodigy.com> Message-ID: Thanks Kartic, Don't know if i have understand everything, but i 'll try using your lights, To integrate a flash movie using wx, here is a piece of code (the Flash.py is auto-generated by makepy.py) ### testFlash.py from wxPython.wx import * import os if wxPlatform == '__WXMSW__': from wxPython.lib.activexwrapper import MakeActiveXClass #import win32com.client.gencache #import win32com.client import flash flashControl = flash class FlashPanel(wxPanel): def __init__(self, parent, flashFile): wxPanel.__init__(self, parent, -1) sizer = wxBoxSizer(wxVERTICAL) ActiveXWrapper = MakeActiveXClass(flashControl.ShockwaveFlash) self.Flash = ActiveXWrapper( self, -1) self.Flash.Movie = os.path.join(os.getcwd(), flashFile) self.Flash.Menu=False self.Flash.OnFSCommand = self.OnFSCommand sizer.Add(self.Flash, 1, wxEXPAND) self.SetSizer(sizer) self.SetAutoLayout(True) EVT_WINDOW_DESTROY(self, self.OnDestroy) def OnDestroy(self, evt): if self.Flash: self.Flash.Cleanup() self.Flash = None def OnFSCommand(self, command, *args): if command=="openFile": self.openFile() if command=="saveFile": self.saveFile(*args) def openFile(self): dlg = wxFileDialog(self, "Choose", "", "", "*.*", wxOPEN) if dlg.ShowModal()==wxID_OK: filename = dlg.GetFilename() dirname = dlg.GetDirectory() f = open(os.path.join(dirname, filename), "r") self.Flash.SetVariable("PyReply", f.read()) f.close() dlg.Destroy() def saveFile(self, text): dlg = wxFileDialog(self, "Save As", "", "", "*.*", wxSAVE|wxOVERWRITE_PROMPT) if dlg.ShowModal()==wxID_OK: filename = dlg.GetFilename() dirname = dlg.GetDirectory() f = open(os.path.join(dirname, filename), "w") f.write(text) f.close() dlg.Destroy() if __name__ == '__main__': class FlashFrame(wxFrame): def __init__(self): wxFrame.__init__(self, None, -1, "PyFlash -- Simple File Viewer", size=(550, 400)) self.flashPanel = FlashPanel(self, "testFlash.swf") app = wxPySimpleApp() frame = FlashFrame() frame.Show(True) app.MainLoop() ### Flash.py # -*- coding: mbcs -*- # Created by makepy.py version 0.4.8 # By python version 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit (Intel)] # From type library '{D27CDB6B-AE6D-11CF-96B8-444553540000}' # On Tue Mar 16 01:58:37 2004 """Shockwave Flash""" makepy_version = '0.4.8' python_version = 0x20303f0 import win32com.client.CLSIDToClass, pythoncom import win32com.client.util from pywintypes import IID from win32com.client import Dispatch # The following 3 lines may need tweaking for the particular server # Candidates are pythoncom.Missing and pythoncom.Empty defaultNamedOptArg=pythoncom.Empty defaultNamedNotOptArg=pythoncom.Empty defaultUnnamedArg=pythoncom.Empty CLSID = IID('{D27CDB6B-AE6D-11CF-96B8-444553540000}') MajorVersion = 1 MinorVersion = 0 LibraryFlags = 8 LCID = 0x0 from win32com.client import DispatchBaseClass class IShockwaveFlash(DispatchBaseClass): """Shockwave Flash""" CLSID = IID('{D27CDB6C-AE6D-11CF-96B8-444553540000}') coclass_clsid = IID('{D27CDB6E-AE6D-11CF-96B8-444553540000}') #default_interface = IShockwaveFlash #default_source = _IShockwaveFlashEvents def Back(self): """method Back""" return self._oleobj_.InvokeTypes(114, LCID, 1, (24, 0), (),) def CurrentFrame(self): """method CurrentFrame""" return self._oleobj_.InvokeTypes(128, LCID, 1, (3, 0), (),) def FlashVersion(self): """method FlashVersion""" return self._oleobj_.InvokeTypes(132, LCID, 1, (3, 0), (),) def Forward(self): """method Forward""" return self._oleobj_.InvokeTypes(115, LCID, 1, (24, 0), (),) def FrameLoaded(self, FrameNum=defaultNamedNotOptArg): """method FrameLoaded""" return self._oleobj_.InvokeTypes(131, LCID, 1, (11, 0), ((3, 1),),FrameNum) def GetVariable(self, name=defaultNamedNotOptArg): """method GetVariable""" # Result is a Unicode object - return as-is for this version of Python return self._oleobj_.InvokeTypes(152, LCID, 1, (8, 0), ((8, 1),),name) def GotoFrame(self, FrameNum=defaultNamedNotOptArg): """method GotoFrame""" return self._oleobj_.InvokeTypes(127, LCID, 1, (24, 0), ((3, 1),),FrameNum) def IsPlaying(self): """method IsPlaying""" return self._oleobj_.InvokeTypes(129, LCID, 1, (11, 0), (),) def LoadMovie(self, layer=defaultNamedNotOptArg, url=defaultNamedNotOptArg): """method LoadMovie""" return self._oleobj_.InvokeTypes(142, LCID, 1, (24, 0), ((3, 1), (8, 1)),layer, url) def Pan(self, x=defaultNamedNotOptArg, y=defaultNamedNotOptArg, mode=defaultNamedNotOptArg): """method Pan""" return self._oleobj_.InvokeTypes(119, LCID, 1, (24, 0), ((3, 1), (3, 1), (3, 1)),x, y, mode) def PercentLoaded(self): """method PercentLoaded""" return self._oleobj_.InvokeTypes(130, LCID, 1, (3, 0), (),) def Play(self): """method Play""" return self._oleobj_.InvokeTypes(112, LCID, 1, (24, 0), (),) def Rewind(self): """method Rewind""" return self._oleobj_.InvokeTypes(116, LCID, 1, (24, 0), (),) def SetVariable(self, name=defaultNamedNotOptArg, value=defaultNamedNotOptArg): """method SetVariable""" return self._oleobj_.InvokeTypes(151, LCID, 1, (24, 0), ((8, 1), (8, 1)),name, value) def SetZoomRect(self, left=defaultNamedNotOptArg, top=defaultNamedNotOptArg, right=defaultNamedNotOptArg, bottom=defaultNamedNotOptArg): """method SetZoomRect""" return self._oleobj_.InvokeTypes(109, LCID, 1, (24, 0), ((3, 1), (3, 1), (3, 1), (3, 1)),left, top, right, bottom) def Stop(self): """method Stop""" return self._oleobj_.InvokeTypes(113, LCID, 1, (24, 0), (),) def StopPlay(self): """method StopPlay""" return self._oleobj_.InvokeTypes(126, LCID, 1, (24, 0), (),) def TCallFrame(self, target=defaultNamedNotOptArg, FrameNum=defaultNamedNotOptArg): """method TCallFrame""" return self._oleobj_.InvokeTypes(155, LCID, 1, (24, 0), ((8, 1), (3, 1)),target, FrameNum) def TCallLabel(self, target=defaultNamedNotOptArg, label=defaultNamedNotOptArg): """method TCallLabel""" return self._oleobj_.InvokeTypes(156, LCID, 1, (24, 0), ((8, 1), (8, 1)),target, label) def TCurrentFrame(self, target=defaultNamedNotOptArg): """method TCurrentFrame""" return self._oleobj_.InvokeTypes(145, LCID, 1, (3, 0), ((8, 1),),target) def TCurrentLabel(self, target=defaultNamedNotOptArg): """method TCurrentLabel""" # Result is a Unicode object - return as-is for this version of Python return self._oleobj_.InvokeTypes(146, LCID, 1, (8, 0), ((8, 1),),target) def TGetProperty(self, target=defaultNamedNotOptArg, Property=defaultNamedNotOptArg): """method TGetProperty""" # Result is a Unicode object - return as-is for this version of Python return self._oleobj_.InvokeTypes(154, LCID, 1, (8, 0), ((8, 1), (3, 1)),target, Property) def TGetPropertyAsNumber(self, target=defaultNamedNotOptArg, Property=defaultNamedNotOptArg): """method TGetPropertyAsNumber""" return self._oleobj_.InvokeTypes(172, LCID, 1, (5, 0), ((8, 1), (3, 1)),target, Property) def TGetPropertyNum(self, target=defaultNamedNotOptArg, Property=defaultNamedNotOptArg): """method TGetPropertyNum""" return self._oleobj_.InvokeTypes(158, LCID, 1, (5, 0), ((8, 1), (3, 1)),target, Property) def TGotoFrame(self, target=defaultNamedNotOptArg, FrameNum=defaultNamedNotOptArg): """method TGotoFrame""" return self._oleobj_.InvokeTypes(143, LCID, 1, (24, 0), ((8, 1), (3, 1)),target, FrameNum) def TGotoLabel(self, target=defaultNamedNotOptArg, label=defaultNamedNotOptArg): """method TGotoLabel""" return self._oleobj_.InvokeTypes(144, LCID, 1, (24, 0), ((8, 1), (8, 1)),target, label) def TPlay(self, target=defaultNamedNotOptArg): """method TPlay""" return self._oleobj_.InvokeTypes(147, LCID, 1, (24, 0), ((8, 1),),target) def TSetProperty(self, target=defaultNamedNotOptArg, Property=defaultNamedNotOptArg, value=defaultNamedNotOptArg): """method TSetProperty""" return self._oleobj_.InvokeTypes(153, LCID, 1, (24, 0), ((8, 1), (3, 1), (8, 1)),target, Property, value) def TSetPropertyNum(self, target=defaultNamedNotOptArg, Property=defaultNamedNotOptArg, value=defaultNamedNotOptArg): """method TSetPropertyNum""" return self._oleobj_.InvokeTypes(157, LCID, 1, (24, 0), ((8, 1), (3, 1), (5, 1)),target, Property, value) def TStopPlay(self, target=defaultNamedNotOptArg): """method TStopPlay""" return self._oleobj_.InvokeTypes(148, LCID, 1, (24, 0), ((8, 1),),target) def Zoom(self, factor=defaultNamedNotOptArg): """method Zoom""" return self._oleobj_.InvokeTypes(118, LCID, 1, (24, 0), ((3, 1),),factor) _prop_map_get_ = { "AlignMode": (121, 2, (3, 0), (), "AlignMode", None), "AllowScriptAccess": (171, 2, (8, 0), (), "AllowScriptAccess", None), "BGColor": (140, 2, (8, 0), (), "BGColor", None), "BackgroundColor": (123, 2, (3, 0), (), "BackgroundColor", None), "Base": (136, 2, (8, 0), (), "Base", None), "DeviceFont": (138, 2, (11, 0), (), "DeviceFont", None), "EmbedMovie": (139, 2, (11, 0), (), "EmbedMovie", None), "FlashVars": (170, 2, (8, 0), (), "FlashVars", None), "FrameNum": (107, 2, (3, 0), (), "FrameNum", None), "InlineData": (191, 2, (13, 0), (), "InlineData", None), "Loop": (106, 2, (11, 0), (), "Loop", None), "Menu": (135, 2, (11, 0), (), "Menu", None), "Movie": (102, 2, (8, 0), (), "Movie", None), "MovieData": (190, 2, (8, 0), (), "MovieData", None), "Playing": (125, 2, (11, 0), (), "Playing", None), "Quality": (105, 2, (3, 0), (), "Quality", None), "Quality2": (141, 2, (8, 0), (), "Quality2", None), "ReadyState": (-525, 2, (3, 0), (), "ReadyState", None), "SAlign": (134, 2, (8, 0), (), "SAlign", None), "SWRemote": (159, 2, (8, 0), (), "SWRemote", None), "Scale": (137, 2, (8, 0), (), "Scale", None), "ScaleMode": (120, 2, (3, 0), (), "ScaleMode", None), "SeamlessTabbing": (192, 2, (11, 0), (), "SeamlessTabbing", None), "TotalFrames": (124, 2, (3, 0), (), "TotalFrames", None), "WMode": (133, 2, (8, 0), (), "WMode", None), } _prop_map_put_ = { "AlignMode": ((121, LCID, 4, 0),()), "AllowScriptAccess": ((171, LCID, 4, 0),()), "BGColor": ((140, LCID, 4, 0),()), "BackgroundColor": ((123, LCID, 4, 0),()), "Base": ((136, LCID, 4, 0),()), "DeviceFont": ((138, LCID, 4, 0),()), "EmbedMovie": ((139, LCID, 4, 0),()), "FlashVars": ((170, LCID, 4, 0),()), "FrameNum": ((107, LCID, 4, 0),()), "InlineData": ((191, LCID, 4, 0),()), "Loop": ((106, LCID, 4, 0),()), "Menu": ((135, LCID, 4, 0),()), "Movie": ((102, LCID, 4, 0),()), "MovieData": ((190, LCID, 4, 0),()), "Playing": ((125, LCID, 4, 0),()), "Quality": ((105, LCID, 4, 0),()), "Quality2": ((141, LCID, 4, 0),()), "SAlign": ((134, LCID, 4, 0),()), "SWRemote": ((159, LCID, 4, 0),()), "Scale": ((137, LCID, 4, 0),()), "ScaleMode": ((120, LCID, 4, 0),()), "SeamlessTabbing": ((192, LCID, 4, 0),()), "WMode": ((133, LCID, 4, 0),()), } class _IShockwaveFlashEvents: """Event interface for Shockwave Flash""" CLSID = CLSID_Sink = IID('{D27CDB6D-AE6D-11CF-96B8-444553540000}') coclass_clsid = IID('{D27CDB6E-AE6D-11CF-96B8-444553540000}') _public_methods_ = [] # For COM Server support _dispid_to_func_ = { 150 : "OnFSCommand", 1958 : "OnProgress", -609 : "OnReadyStateChange", } def __init__(self, oobj = None): if oobj is None: self._olecp = None else: import win32com.server.util from win32com.server.policy import EventHandlerPolicy cpc=oobj._oleobj_.QueryInterface(pythoncom.IID_IConnectionPointContainer) cp=cpc.FindConnectionPoint(self.CLSID_Sink) cookie=cp.Advise(win32com.server.util.wrap(self, usePolicy=EventHandlerPolicy)) self._olecp,self._olecp_cookie = cp,cookie def __del__(self): try: self.close() except pythoncom.com_error: pass def close(self): if self._olecp is not None: cp,cookie,self._olecp,self._olecp_cookie = self._olecp,self._olecp_cookie,None,None cp.Unadvise(cookie) def _query_interface_(self, iid): import win32com.server.util if iid==self.CLSID_Sink: return win32com.server.util.wrap(self) # Event Handlers # If you create handlers, they should have the following prototypes: # def OnFSCommand(self, command=defaultNamedNotOptArg, args=defaultNamedNotOptArg): pass # def OnProgress(self, percentDone=defaultNamedNotOptArg): # def OnReadyStateChange(self, newState=defaultNamedNotOptArg): from win32com.client import CoClassBaseClass class FlashObjectInterface(CoClassBaseClass): # A CoClass # IFlashObjectInterface Interface CLSID = IID('{D27CDB71-AE6D-11CF-96B8-444553540000}') coclass_sources = [ ] coclass_interfaces = [ ] class FlashProp(CoClassBaseClass): # A CoClass # Macromedia Flash Player Properties CLSID = IID('{1171A62F-05D2-11D1-83FC-00A0C9089C5A}') coclass_sources = [ ] coclass_interfaces = [ ] # This CoClass is known by the name 'ShockwaveFlash.ShockwaveFlash.1' class ShockwaveFlash(CoClassBaseClass): # A CoClass # Shockwave Flash CLSID = IID('{D27CDB6E-AE6D-11CF-96B8-444553540000}') coclass_sources = [ _IShockwaveFlashEvents, ] default_source = _IShockwaveFlashEvents coclass_interfaces = [ IShockwaveFlash, ] default_interface = IShockwaveFlash IDispatchEx_vtables_dispatch_ = 1 IDispatchEx_vtables_ = [ (('GetDispID', 'bstrName', 'grfdex', 'pid'), 1610743808, (1610743808, (), [(8, 1, None, None), (19, 1, None, None), (16387, 2, None, None)], 1, 1, 4, 0, 28, (3, 0, None, None), 0)), (('RemoteInvokeEx', 'id', 'lcid', 'dwFlags', 'pdp', 'pvarRes', 'pei', 'pspCaller', 'cvarRefArg', 'rgiRefArg', 'rgvarRefArg'), 1610743809, (1610743809, (), [(3, 1, None, None), (19, 1, None, None), (19, 1, None, None), (36, 1, None, None), (16396, 2, None, None), (36, 2, None, None), (13, 1, None, "IID('{6D5140C1-7436-11CE-8034-00AA006009FA}')"), (3, 1, None, None), (16387, 1, None, None), (16396, 3, None, None)], 1, 1, 4, 0, 32, (3, 0, None, None), 0)), (('DeleteMemberByName', 'bstrName', 'grfdex'), 1610743810, (1610743810, (), [(8, 1, None, None), (19, 1, None, None)], 1, 1, 4, 0, 36, (3, 0, None, None), 0)), (('DeleteMemberByDispID', 'id'), 1610743811, (1610743811, (), [(3, 1, None, None)], 1, 1, 4, 0, 40, (3, 0, None, None), 0)), (('GetMemberProperties', 'id', 'grfdexFetch', 'pgrfdex'), 1610743812, (1610743812, (), [(3, 1, None, None), (19, 1, None, None), (16403, 2, None, None)], 1, 1, 4, 0, 44, (3, 0, None, None), 0)), (('GetMemberName', 'id', 'pbstrName'), 1610743813, (1610743813, (), [(3, 1, None, None), (16392, 2, None, None)], 1, 1, 4, 0, 48, (3, 0, None, None), 0)), (('GetNextDispID', 'grfdex', 'id', 'pid'), 1610743814, (1610743814, (), [(19, 1, None, None), (3, 1, None, None), (16387, 2, None, None)], 1, 1, 4, 0, 52, (3, 0, None, None), 0)), (('GetNameSpaceParent', 'ppunk'), 1610743815, (1610743815, (), [(16397, 2, None, None)], 1, 1, 4, 0, 56, (3, 0, None, None), 0)), ] IFlashFactory_vtables_dispatch_ = 0 IFlashFactory_vtables_ = [ ] IFlashObjectInterface_vtables_dispatch_ = 1 IFlashObjectInterface_vtables_ = [ ] IServiceProvider_vtables_dispatch_ = 0 IServiceProvider_vtables_ = [ (('RemoteQueryService', 'guidService', 'riid', 'ppvObject'), 1610678272, (1610678272, (), [(36, 1, None, None), (36, 1, None, None), (16397, 2, None, None)], 1, 1, 4, 0, 12, (3, 0, None, None), 0)), ] IShockwaveFlash_vtables_dispatch_ = 1 IShockwaveFlash_vtables_ = [ (('ReadyState', 'pVal'), -525, (-525, (), [(16387, 10, None, None)], 1, 2, 4, 0, 28, (3, 0, None, None), 0)), (('TotalFrames', 'pVal'), 124, (124, (), [(16387, 10, None, None)], 1, 2, 4, 0, 32, (3, 0, None, None), 0)), (('Playing', 'pVal'), 125, (125, (), [(16395, 10, None, None)], 1, 2, 4, 0, 36, (3, 0, None, None), 0)), (('Playing', 'pVal'), 125, (125, (), [(11, 1, None, None)], 1, 4, 4, 0, 40, (3, 0, None, None), 0)), (('Quality', 'pVal'), 105, (105, (), [(16387, 10, None, None)], 1, 2, 4, 0, 44, (3, 0, None, None), 0)), (('Quality', 'pVal'), 105, (105, (), [(3, 1, None, None)], 1, 4, 4, 0, 48, (3, 0, None, None), 0)), (('ScaleMode', 'pVal'), 120, (120, (), [(16387, 10, None, None)], 1, 2, 4, 0, 52, (3, 0, None, None), 0)), (('ScaleMode', 'pVal'), 120, (120, (), [(3, 1, None, None)], 1, 4, 4, 0, 56, (3, 0, None, None), 0)), (('AlignMode', 'pVal'), 121, (121, (), [(16387, 10, None, None)], 1, 2, 4, 0, 60, (3, 0, None, None), 0)), (('AlignMode', 'pVal'), 121, (121, (), [(3, 1, None, None)], 1, 4, 4, 0, 64, (3, 0, None, None), 0)), (('BackgroundColor', 'pVal'), 123, (123, (), [(16387, 10, None, None)], 1, 2, 4, 0, 68, (3, 0, None, None), 0)), (('BackgroundColor', 'pVal'), 123, (123, (), [(3, 1, None, None)], 1, 4, 4, 0, 72, (3, 0, None, None), 0)), (('Loop', 'pVal'), 106, (106, (), [(16395, 10, None, None)], 1, 2, 4, 0, 76, (3, 0, None, None), 0)), (('Loop', 'pVal'), 106, (106, (), [(11, 1, None, None)], 1, 4, 4, 0, 80, (3, 0, None, None), 0)), (('Movie', 'pVal'), 102, (102, (), [(16392, 10, None, None)], 1, 2, 4, 0, 84, (3, 0, None, None), 0)), (('Movie', 'pVal'), 102, (102, (), [(8, 1, None, None)], 1, 4, 4, 0, 88, (3, 0, None, None), 0)), (('FrameNum', 'pVal'), 107, (107, (), [(16387, 10, None, None)], 1, 2, 4, 0, 92, (3, 0, None, None), 0)), (('FrameNum', 'pVal'), 107, (107, (), [(3, 1, None, None)], 1, 4, 4, 0, 96, (3, 0, None, None), 0)), (('SetZoomRect', 'left', 'top', 'right', 'bottom'), 109, (109, (), [(3, 1, None, None), (3, 1, None, None), (3, 1, None, None), (3, 1, None, None)], 1, 1, 4, 0, 100, (3, 0, None, None), 0)), (('Zoom', 'factor'), 118, (118, (), [(3, 1, None, None)], 1, 1, 4, 0, 104, (3, 0, None, None), 0)), (('Pan', 'x', 'y', 'mode'), 119, (119, (), [(3, 1, None, None), (3, 1, None, None), (3, 1, None, None)], 1, 1, 4, 0, 108, (3, 0, None, None), 0)), (('Play',), 112, (112, (), [], 1, 1, 4, 0, 112, (3, 0, None, None), 0)), (('Stop',), 113, (113, (), [], 1, 1, 4, 0, 116, (3, 0, None, None), 0)), (('Back',), 114, (114, (), [], 1, 1, 4, 0, 120, (3, 0, None, None), 0)), (('Forward',), 115, (115, (), [], 1, 1, 4, 0, 124, (3, 0, None, None), 0)), (('Rewind',), 116, (116, (), [], 1, 1, 4, 0, 128, (3, 0, None, None), 0)), (('StopPlay',), 126, (126, (), [], 1, 1, 4, 0, 132, (3, 0, None, None), 0)), (('GotoFrame', 'FrameNum'), 127, (127, (), [(3, 1, None, None)], 1, 1, 4, 0, 136, (3, 0, None, None), 0)), (('CurrentFrame', 'FrameNum'), 128, (128, (), [(16387, 10, None, None)], 1, 1, 4, 0, 140, (3, 0, None, None), 0)), (('IsPlaying', 'Playing'), 129, (129, (), [(16395, 10, None, None)], 1, 1, 4, 0, 144, (3, 0, None, None), 0)), (('PercentLoaded', 'percent'), 130, (130, (), [(16387, 10, None, None)], 1, 1, 4, 0, 148, (3, 0, None, None), 0)), (('FrameLoaded', 'FrameNum', 'loaded'), 131, (131, (), [(3, 1, None, None), (16395, 10, None, None)], 1, 1, 4, 0, 152, (3, 0, None, None), 0)), (('FlashVersion', 'version'), 132, (132, (), [(16387, 10, None, None)], 1, 1, 4, 0, 156, (3, 0, None, None), 0)), (('WMode', 'pVal'), 133, (133, (), [(16392, 10, None, None)], 1, 2, 4, 0, 160, (3, 0, None, None), 0)), (('WMode', 'pVal'), 133, (133, (), [(8, 1, None, None)], 1, 4, 4, 0, 164, (3, 0, None, None), 0)), (('SAlign', 'pVal'), 134, (134, (), [(16392, 10, None, None)], 1, 2, 4, 0, 168, (3, 0, None, None), 0)), (('SAlign', 'pVal'), 134, (134, (), [(8, 1, None, None)], 1, 4, 4, 0, 172, (3, 0, None, None), 0)), (('Menu', 'pVal'), 135, (135, (), [(16395, 10, None, None)], 1, 2, 4, 0, 176, (3, 0, None, None), 0)), (('Menu', 'pVal'), 135, (135, (), [(11, 1, None, None)], 1, 4, 4, 0, 180, (3, 0, None, None), 0)), (('Base', 'pVal'), 136, (136, (), [(16392, 10, None, None)], 1, 2, 4, 0, 184, (3, 0, None, None), 0)), (('Base', 'pVal'), 136, (136, (), [(8, 1, None, None)], 1, 4, 4, 0, 188, (3, 0, None, None), 0)), (('Scale', 'pVal'), 137, (137, (), [(16392, 10, None, None)], 1, 2, 4, 0, 192, (3, 0, None, None), 0)), (('Scale', 'pVal'), 137, (137, (), [(8, 1, None, None)], 1, 4, 4, 0, 196, (3, 0, None, None), 0)), (('DeviceFont', 'pVal'), 138, (138, (), [(16395, 10, None, None)], 1, 2, 4, 0, 200, (3, 0, None, None), 0)), (('DeviceFont', 'pVal'), 138, (138, (), [(11, 1, None, None)], 1, 4, 4, 0, 204, (3, 0, None, None), 0)), (('EmbedMovie', 'pVal'), 139, (139, (), [(16395, 10, None, None)], 1, 2, 4, 0, 208, (3, 0, None, None), 0)), (('EmbedMovie', 'pVal'), 139, (139, (), [(11, 1, None, None)], 1, 4, 4, 0, 212, (3, 0, None, None), 0)), (('BGColor', 'pVal'), 140, (140, (), [(16392, 10, None, None)], 1, 2, 4, 0, 216, (3, 0, None, None), 0)), (('BGColor', 'pVal'), 140, (140, (), [(8, 1, None, None)], 1, 4, 4, 0, 220, (3, 0, None, None), 0)), (('Quality2', 'pVal'), 141, (141, (), [(16392, 10, None, None)], 1, 2, 4, 0, 224, (3, 0, None, None), 0)), (('Quality2', 'pVal'), 141, (141, (), [(8, 1, None, None)], 1, 4, 4, 0, 228, (3, 0, None, None), 0)), (('LoadMovie', 'layer', 'url'), 142, (142, (), [(3, 1, None, None), (8, 1, None, None)], 1, 1, 4, 0, 232, (3, 0, None, None), 0)), (('TGotoFrame', 'target', 'FrameNum'), 143, (143, (), [(8, 1, None, None), (3, 1, None, None)], 1, 1, 4, 0, 236, (3, 0, None, None), 0)), (('TGotoLabel', 'target', 'label'), 144, (144, (), [(8, 1, None, None), (8, 1, None, None)], 1, 1, 4, 0, 240, (3, 0, None, None), 0)), (('TCurrentFrame', 'target', 'FrameNum'), 145, (145, (), [(8, 1, None, None), (16387, 10, None, None)], 1, 1, 4, 0, 244, (3, 0, None, None), 0)), (('TCurrentLabel', 'target', 'pVal'), 146, (146, (), [(8, 1, None, None), (16392, 10, None, None)], 1, 1, 4, 0, 248, (3, 0, None, None), 0)), (('TPlay', 'target'), 147, (147, (), [(8, 1, None, None)], 1, 1, 4, 0, 252, (3, 0, None, None), 0)), (('TStopPlay', 'target'), 148, (148, (), [(8, 1, None, None)], 1, 1, 4, 0, 256, (3, 0, None, None), 0)), (('SetVariable', 'name', 'value'), 151, (151, (), [(8, 1, None, None), (8, 1, None, None)], 1, 1, 4, 0, 260, (3, 0, None, None), 0)), (('GetVariable', 'name', 'pVal'), 152, (152, (), [(8, 1, None, None), (16392, 10, None, None)], 1, 1, 4, 0, 264, (3, 0, None, None), 0)), (('TSetProperty', 'target', 'property', 'value'), 153, (153, (), [(8, 1, None, None), (3, 1, None, None), (8, 1, None, None)], 1, 1, 4, 0, 268, (3, 0, None, None), 0)), (('TGetProperty', 'target', 'property', 'pVal'), 154, (154, (), [(8, 1, None, None), (3, 1, None, None), (16392, 10, None, None)], 1, 1, 4, 0, 272, (3, 0, None, None), 0)), (('TCallFrame', 'target', 'FrameNum'), 155, (155, (), [(8, 1, None, None), (3, 1, None, None)], 1, 1, 4, 0, 276, (3, 0, None, None), 0)), (('TCallLabel', 'target', 'label'), 156, (156, (), [(8, 1, None, None), (8, 1, None, None)], 1, 1, 4, 0, 280, (3, 0, None, None), 0)), (('TSetPropertyNum', 'target', 'property', 'value'), 157, (157, (), [(8, 1, None, None), (3, 1, None, None), (5, 1, None, None)], 1, 1, 4, 0, 284, (3, 0, None, None), 0)), (('TGetPropertyNum', 'target', 'property', 'pVal'), 158, (158, (), [(8, 1, None, None), (3, 1, None, None), (16389, 10, None, None)], 1, 1, 4, 0, 288, (3, 0, None, None), 0)), (('TGetPropertyAsNumber', 'target', 'property', 'pVal'), 172, (172, (), [(8, 1, None, None), (3, 1, None, None), (16389, 10, None, None)], 1, 1, 4, 0, 292, (3, 0, None, None), 0)), (('SWRemote', 'pVal'), 159, (159, (), [(16392, 10, None, None)], 1, 2, 4, 0, 296, (3, 0, None, None), 0)), (('SWRemote', 'pVal'), 159, (159, (), [(8, 1, None, None)], 1, 4, 4, 0, 300, (3, 0, None, None), 0)), (('FlashVars', 'pVal'), 170, (170, (), [(16392, 10, None, None)], 1, 2, 4, 0, 304, (3, 0, None, None), 0)), (('FlashVars', 'pVal'), 170, (170, (), [(8, 1, None, None)], 1, 4, 4, 0, 308, (3, 0, None, None), 0)), (('AllowScriptAccess', 'pVal'), 171, (171, (), [(16392, 10, None, None)], 1, 2, 4, 0, 312, (3, 0, None, None), 0)), (('AllowScriptAccess', 'pVal'), 171, (171, (), [(8, 1, None, None)], 1, 4, 4, 0, 316, (3, 0, None, None), 0)), (('MovieData', 'pVal'), 190, (190, (), [(16392, 10, None, None)], 1, 2, 4, 0, 320, (3, 0, None, None), 0)), (('MovieData', 'pVal'), 190, (190, (), [(8, 1, None, None)], 1, 4, 4, 0, 324, (3, 0, None, None), 0)), (('InlineData', 'ppIUnknown'), 191, (191, (), [(16397, 10, None, None)], 1, 2, 4, 0, 328, (3, 0, None, None), 0)), (('InlineData', 'ppIUnknown'), 191, (191, (), [(13, 1, None, None)], 1, 4, 4, 0, 332, (3, 0, None, None), 0)), (('SeamlessTabbing', 'pVal'), 192, (192, (), [(16395, 10, None, None)], 1, 2, 4, 0, 336, (3, 0, None, None), 0)), (('SeamlessTabbing', 'pVal'), 192, (192, (), [(11, 1, None, None)], 1, 4, 4, 0, 340, (3, 0, None, None), 0)), ] RecordMap = { } CLSIDToClassMap = { '{D27CDB6C-AE6D-11CF-96B8-444553540000}' : IShockwaveFlash, '{D27CDB6D-AE6D-11CF-96B8-444553540000}' : _IShockwaveFlashEvents, '{D27CDB6E-AE6D-11CF-96B8-444553540000}' : ShockwaveFlash, '{D27CDB71-AE6D-11CF-96B8-444553540000}' : FlashObjectInterface, '{1171A62F-05D2-11D1-83FC-00A0C9089C5A}' : FlashProp, } CLSIDToPackageMap = {} win32com.client.CLSIDToClass.RegisterCLSIDsFromDict( CLSIDToClassMap ) VTablesToPackageMap = {} VTablesToClassMap = { '{D27CDB72-AE6D-11CF-96B8-444553540000}' : 'IFlashObjectInterface', '{D27CDB6C-AE6D-11CF-96B8-444553540000}' : 'IShockwaveFlash', '{A6EF9860-C720-11D0-9337-00A0C90DCAA9}' : 'IDispatchEx', '{D27CDB70-AE6D-11CF-96B8-444553540000}' : 'IFlashFactory', '{6D5140C1-7436-11CE-8034-00AA006009FA}' : 'IServiceProvider', } NamesToIIDMap = { '_IShockwaveFlashEvents' : '{D27CDB6D-AE6D-11CF-96B8-444553540000}', 'IFlashObjectInterface' : '{D27CDB72-AE6D-11CF-96B8-444553540000}', 'IFlashFactory' : '{D27CDB70-AE6D-11CF-96B8-444553540000}', 'IShockwaveFlash' : '{D27CDB6C-AE6D-11CF-96B8-444553540000}', 'IServiceProvider' : '{6D5140C1-7436-11CE-8034-00AA006009FA}', 'IDispatchEx' : '{A6EF9860-C720-11D0-9337-00A0C90DCAA9}', } "Kartic" a ?crit dans le message de news: 6URce.2055$2f2.1166 at newssvr19.news.prodigy.com... > The Great 'Exeem' uttered these words on 4/30/2005 11:37 AM: >> Kartic, >> >> Thanks for your reply, >> >> I already use the wxPython to embbed my flash animation >> >> ### >> from wxPython.lib.activexwrapper import MakeActiveXClass >> >> ActiveXWrapper = MakeActiveXClass(flashActiveXLib.ShockwaveFlash, >> eventClass=None, eventObj=self) >> >> Flash = ActiveXWrapper( self, -1, style=wxSUNKEN_BORDER) >> #### >> >> It work fine and i can control my flash animation from Python without >> problem.. >> >> But the Wrapper need the flash.ock to be installed on the user system in >> order to work, >> and i would like to make an executable application that include the >> flash.ocx or load it on startup for >> users who doesn't have the flash player installed. >> I would like also to be able to load a flash animation from memory and >> not to load it from external file. >> >> Don't know if you understand me.. Take a look at >> http://www.flashplayercontrol.com/ .. I'd like such a solution for >> Python, >> don't know if i can use that dll from Python or make a module myself.. >> >> Anyway, thank a lot for your interest >> >> Dan > > > Dan, > > Ah! I see what you are trying to do. While I don't have a working piece of > code to share with you, I can give you a few ideas that you could > consider: > > 1. Supply the Macromedia OCX with your app. Try to use the wxActivex class > and if that fails, register your copy of the OCX. You can do this either > using a batch file invoking regsvr32 or use Win32 to register. The flip > side: The flash will be loaded from a file rather than memory. > > 2. Wrap the flashplayercontrol.com's DLL in an Activex control using VB > and distribute your OCX. And then use wxActivex to access your OCX. > > 3. Use SWIG to generate Python bindings for the DLL. I have never done > this and I am sure some of the more erudite members of the newsgroup can > shed some light. > > 4. Call the supplied DLL using Ctypes. In this case, you can convert the > example under the "Features" link of that site in DLL calls using Ctypes. > Question: How will that integrate with wx? > > Hope that helped a bit. > > Thanks, > -Kartic From a.schmolck at gmx.net Sun Apr 24 19:25:18 2005 From: a.schmolck at gmx.net (Alexander Schmolck) Date: Mon, 25 Apr 2005 00:25:18 +0100 Subject: How to "generalize" a function? References: <851x8zyhtl.fsf@ishmael.pequod.dyndns.org> Message-ID: Thomas K?llmann writes: > confFile.close You want ``confFile.close()`` -- the above won't do anything [1]. 'as Footnotes: [1] Best practice would be something like this (don't worry to much about it -- it just ensures the file is properly closed, even if something goes wrong): confFile = None try: confFile = open(networkConf, 'w') confFile.writelines(conf) finally: if confFile: confFile.close() From fuzzyman at gmail.com Fri Apr 8 05:16:23 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 8 Apr 2005 02:16:23 -0700 Subject: [ANN] Voidspace Pythonutils Updates Message-ID: Lots of updates to the Voidspace modules and recipes. Update to the Firedrop plugins see : http://www.voidspace.org.uk/python/programs.shtml#firedrop New version of FireSpell the spell checker (based on PyEnchant by Ryan Kelly) New plugin called FireMail which lets you send blog entries (or articles) by email - either as HTML or text. All the plugins are available for download. There is also docs on installing and using the plugins and docs on writing plugins. downman.py http://www.voidspace.org.uk/python/cgi.shtml#downman More improvements to downman.py - the simple download manager CGI 2005/03/15 Version 0.4.0 Configuration moved into external config file. HTML stuff mmoved into downman_templates.py Put quotes round filename (This stops firefox truncating filenames with spaces) Flush the output buffer as we serve the file (may help those who have to use env in the shebang line) guestbook.py http://www.voidspace.org.uk/python/guestbook.html Quite a big change - with a cleaning up of the default HTML templates and several new features to help combat guestbook spam. 2005/04/06 Version 1.3.0 Lots of restyling in the HTML templates - not *quite* so horrible now. We write new entries at the start of the file rather than the end (undoes a bug introduced in 1.2.0) Max of two URLs in an entry. A few extra words added to the banned list. (Still trying to combat guestbook spam) New value 'BREAKVAL' added to templates (so we can use the XHTML
if needed) The '_charset_' field added to the form and value checked (in case page encoding changed by guests browser) Now use rel="nofollow" in links to foil spammers Email addresses shown using javascript in an attempt to foil address harvesters. Obviously invalid email addresses and urls are removed. (very basic) Jalopy and Login Tools Not a huge amount of progress - but a few bugs fixed. http://www.voidspace.org.uk/python/jalopy.html http://www.voidspace.org.uk/python/logintools.html 2005/03/23 Admin levels are now preserved when new users are created or invited. Corrected bug causing accounts to not be editable. Changed all the shebang lines to '#! /usr/bin/python' Updated to latest versions of all the pythonutils modules (like ConfigObj) Fixed typo in HTML for editing users (causing crashes). cgiutils.py http://www.voidspace.org.uk/python/recipebook.shtml#utils cgitutils now has much better functions for handling emails. It includes a function for creating HTML emails and a single function will do the sending, rather than 3 functions for the three different cases as before (using sendmail, using smtplib, using smtplib with login). 2005/04/07 Version 0.3.0 Changed the email functions, this may break things (but it's better this way) Added createhtmlemail, removed loginmailme mailme is now a wrapper for sendmailme, mailme, *and* the old loginmailme upload.py http://www.voidspace.org.uk/python/cgi.shtml#upload 2005/04/07 Version 1.1.1 We now set I/O to binary mode for windows. googleCacheServer.py http://www.voidspace.org.uk/python/recipebook.shtml#google An innovative use of the google api ! Version 0.1.3 5th April 2005 This is a simple implementation of a proxy server that fetches web pages from the google cache. It's based on SimpleHTTPServer and lets you explore the internet from your browser, using the google cache. See the world how google sees it. Alternatively - retro internet - no CSS, no javascript, no images, this is back to the days of MOSAIC ! Best Regards, Fuzzy http://www.voidspace.org.uk/python From gandalf at geochemsource.com Thu Apr 7 07:41:17 2005 From: gandalf at geochemsource.com (Laszlo Zsolt Nagy) Date: Thu, 07 Apr 2005 13:41:17 +0200 Subject: doubt regarding main function In-Reply-To: <20050407113852.51725.qmail@web8401.mail.in.yahoo.com> References: <20050407113852.51725.qmail@web8401.mail.in.yahoo.com> Message-ID: <42551C5D.8040706@geochemsource.com> >if __name__ == '__main__': > test() > >What is the advantage of this way calling a >function. > > For example, you can have a python script that has this function: def search(keywords,engine='www.google.com') At the end of the script, you can have this: if __name__ == '__main__': import sys print search(sys.argv[1]) E.g. if you run the script as a program, then you can use it for searching and print the results. But you can use it as a library, like import searchengine # This won't execute the search method because (searchengine.__name__ == '__main__') evaluates to False # Use the module here results = searchengine.search('Python') Of course this is just one possible use. For example, you can run a self testing function (when not used as a module). Best, Laci 2.0 -- _________________________________________________________________ Laszlo Nagy web: http://designasign.biz IT Consultant mail: gandalf at geochemsource.com Python forever! From noemail at noemail.com Tue Apr 12 17:16:04 2005 From: noemail at noemail.com (Jim) Date: Tue, 12 Apr 2005 17:16:04 -0400 Subject: A beginer question about SOAP and Python: : {} Message-ID: <4c-dnVn7LJL3p8HfRVn-sw@rogers.com> Hi all, I am new to SOAP and Python. I am practicing learning SOAP with Python. I sent a request and I got the following response: : {} What does that mean? and how can I print the result hash string ? Please reply to the group. Thanks for your help. Jim. From a at a.com Fri Apr 22 16:36:23 2005 From: a at a.com (Non-Offensive, Professional Sounding Name) Date: Fri, 22 Apr 2005 15:36:23 -0500 Subject: Ron Grossi: God is not a man References: <1114098221.580669.86300@g14g2000cwa.googlegroups.com> <1114127633.859113.292290@l41g2000cwc.googlegroups.com> Message-ID: <#2tJ0r3RFHA.3664@TK2MSFTNGP15.phx.gbl> Good gracious. I got tired just scrolling down through that mess. That eloquent diatribe lacks only the virtue of being true. Oabid, you have seriously been deceived by the demon posing as the false god Allah. "Obaid R." wrote in message news:1114127633.859113.292290 at l41g2000cwc.googlegroups.com... > SUMMARY > ======= > > For the past few weeks, a self-professed > internet evangelist has posted several times [lies mixed with truth thankfully snipped] From mahs at telcopartners.com Mon Apr 4 12:44:07 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Mon, 04 Apr 2005 09:44:07 -0700 Subject: Semi-newbie, rolling my own __deepcopy__ In-Reply-To: <1112629066.785241.275670@z14g2000cwz.googlegroups.com> References: <1112629066.785241.275670@z14g2000cwz.googlegroups.com> Message-ID: ladasky at my-deja.com wrote: > Hi, folks, > > First, the obligatory cheerleading -- then, my questions... > > I love Python! I am only an occasional programmer. Still, the logic > of the language is clear enough that I can retain pretty much all that > I have learned from one infrequent programming session to the next. > That's quite an accomplishment for a language this powerful. Also, I'm > finally beginning to grasp OOP. I could never quite get the hang of it > in C++ or Java. Recently, I discovered __getitem__ and pickle. Oh, > yeah. > > Anyway, my present problem is that I want to make copies of instances > of my own custom classes. I'm having a little trouble understanding > the process. Not that I think that it matters -- but in case it does, > I'll tell you that I'm running Python 2.3.4 on a Win32 machine. > > I started naively, thinking that I could just call copy.deepcopy() and > be done with it. After getting a TypeError from the interpreter, I > read the deepcopy docs and discovered that I need to implement a > __deepcopy__ method in my class. But the docs are a bit vague here. > What exactly should this __deepcopy__ do? I tried looking for examples > of __deepcopy__ code on the Net, but I'm not quite understanding what > I'm finding there. I guess that I'm getting deeper into the guts of > Python than I planned. > > AFAIK, I'm supposed to add a "def __deepcopy__(self, memo):" to my > class definition. This will get called when I invoke > copy.deepcopy(myObject). The object to be copied is self, I presume. > What exactly is memo? The docs say that it's a dictionary which "keeps > track of what has already been copied." Somewhere I remember reading > that the namespace of an object is a dictionary. So is memo identical > to the dictionary of the new object that I'm trying to create? What > exactly do I add to memo? I think that I should make shallow copies of > methods, but deep copies of data structures (the contents of which I'm > likely to change). Do I iterate through and copy the items in > dir(self)? Do I update memo manually, or does passing memo into copy() > or deepcopy() automatically update memo's contents? Are there any > items that I *shouldn't* copy from self to memo? Should __deepcopy__ > return memo? > > Sorry for all the confusion -- and thanks for your help! > > -- > Rainforest laid low. > "Wake up and smell the ozone," > Says man with chainsaw. > John J. Ladasky Jr., Ph.D. > If you google for: python __deepcopy__ cookbook you will find a couple of examples of this method in use, among them: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/259179 class deque(object): def __init__(self, iterable=()): if not hasattr(self, 'data'): self.left = self.right = 0 self.data = {} self.extend(iterable) [...snip methods...] def __deepcopy__(self, memo={}): from copy import deepcopy result = self.__class__() memo[id(self)] = result result.__init__(deepcopy(tuple(self), memo)) return result HTH Michael From radam2 at tampabay.rr.com Sat Apr 2 11:43:01 2005 From: radam2 at tampabay.rr.com (Ron_Adam) Date: Sat, 02 Apr 2005 16:43:01 GMT Subject: Docorator Disected References: <4p9t419ockcg8578g6guse3a14t16orebf@4ax.com> <1112455359.773729.92080@l41g2000cwc.googlegroups.com> Message-ID: <6git41doqfbk01h8lsk1gl7u91qgspivrp@4ax.com> On 2 Apr 2005 07:22:39 -0800, "El Pitonero" wrote: >Is it possible that you mistakenly believe your @decorator() is being >executed at the line "func('Hello')"? > >Please add a print statement to your code: > >def decorator(d_arg): > def get_function(function): > print 'decorator invoked' > def wrapper(f_arg): > new_arg = f_arg+'-'+d_arg > result = function(new_arg) > return result > return wrapper > return get_function Thanks, you are correct. I'll post a revised dissection with print statements documenting the flow in a few minutes. I'm still a bit fuzzy on how the arguments are stored and passed. Regards, Ron_Adam From garykpdx at hotmail.com Wed Apr 20 12:18:38 2005 From: garykpdx at hotmail.com (garykpdx at hotmail.com) Date: 20 Apr 2005 09:18:38 -0700 Subject: using locales Message-ID: <1114013918.059442.30770@l41g2000cwc.googlegroups.com> Is there some sort of tutorial on locales or the locale module? I can't seem to find a list showing all possible locales. I made 'en' work alright, but when I tried 'de' or 'de_DE' or 'es_ES', etc. it said that those were not valid locaes. Worst of all, when I tried 'es' it said that this was estonian?! Obviously, this is not what ISO 639 says. 'es' should be Spanish, and Estonian should be 'et. Anyway, I'd love to have a method called get_available_locales to tell me what I can use on my machine, or something like that. Can anyone tell me how I *do* get these names? Thanks From donn at u.washington.edu Thu Apr 28 12:14:55 2005 From: donn at u.washington.edu (Donn Cave) Date: Thu, 28 Apr 2005 09:14:55 -0700 Subject: mbx repair script References: Message-ID: In article , "David Isaac" wrote: > I'm looking for a Python script to repair the mbx header > for a mail file where only the header is corrupted. "Repair" and "corrupted" covers a lot of territory. In the simplest case, a Python script would just be a nuisance. All mbx files start with a 2048 byte header, and a valid header can be copied to another file and still be valid. For example, if the damaged file still has 2048 bytes of header, 1. Find or create another mbx file "spud". 2. Copy header: $ dd if=spud count=4 > newbx 3. Copy old file: $ dd if=oldbx skip=4 >> newbx 4. change ownership and permission to match oldbx. This approach isn't perfect - for example, it doesn't preserve user flag information, but then, user flags can be messed up by common IMAP4 operations like copying a message from one folder to another. It assumes you know where message data actually starts in the file, but I think you'd need to know that in any event. If the damage is really just that someone edited the file in vi and you need to restore the NUL characters, you could probably write something. Again, you have to be able to recognize the start of message data (or rather, the first MBX message header line.) If the NULs are gone, this is probably preceded by a series of CRLF ('\r\n'.) Keep track of how much has been written to the output file, and at this point, write '\0'*(2048 - n). Donn Cave, donn at u.washington.edu From mwm at mired.org Sat Apr 30 17:40:05 2005 From: mwm at mired.org (Mike Meyer) Date: Sat, 30 Apr 2005 16:40:05 -0500 Subject: bytecode non-backcompatibility References: <1114418065.581779.52480@l41g2000cwc.googlegroups.com> <426F2C3A.80402@v.loewis.de> Message-ID: <86pswcj64q.fsf@guru.mired.org> Maurice LING writes: > So if C extension API (or whatever that is really called) is stable, > the system admin can just copy all of /sw/lib/python2.3/site-packages > into /sw/lib/python2.4/site-packages and it should work. From what > you've said, it seems that this isn't possible. Correct. This isn't possible. It's not clear it's *desirable*, either. For one thing, code can fail to port across versions, so things will break at random (instead of all at once, I admit). For another, I dislike the idea of a module sitting unupdate for long periods of time (decades, say). Updating Python provides a good excuse to update all the python modules, etc. Now, it would be nice if Python provided an easy way to do the update. The FreeBSD packaging system happens to provide a way to automate this process, but it's still not exactly easy. > So my alternative > solution is that PyPI have a mechanism to maintain what had been > installed in the site-package directory and to download the libraries > and install into the new site-package directory... PyPI is the wrong place to maintain a record of installed software. Distutils is the software that does the installing (ok, on most modules, anyway), and is the software that should record what packages are installed. Neither distutils nor PyPI has a "download" functionality. For that matter, PyPI doesn't have a hard requirement on listing where a module comes from. I'd say distutils is the software that should provide it, so I can say: python setup.py install --depends and get all the dependencies. But that's not at all clear. PyPI will have to cooperate by providing URLs to packages, instead of to pages. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From jstroud at mbi.ucla.edu Sun Apr 3 00:51:09 2005 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 2 Apr 2005 21:51:09 -0800 Subject: Finding attributes in a list In-Reply-To: <5e183f3d050402204426e9099f@mail.gmail.com> References: <1112101524.879186.260630@o13g2000cwo.googlegroups.com> <4249f2d0.22628407@news.oz.net> <5e183f3d050402204426e9099f@mail.gmail.com> Message-ID: <200504022151.09978.jstroud@mbi.ucla.edu> On Saturday 02 April 2005 08:44 pm, Marcus Goldfish wrote: > (2) The Player class looks like a nice model for a data table when one > wants to sort by arbitrary column. Would you agree? The Player class is (and any class) is absolutely fabulous when you have heterogenous data (string, int, etc). I would not fall into the trap of LoDs (Lists of Dictionaries). They get unwieldy because you always have to manage them with functions. You end up writing a module built around your specific dictionary and you end up with a duct-taped object oriented design anyway. Classes are way better--so use them up front, even if you think that your data structure will never be complicated enough to warrant a class. It eventually will if it is worth a damn to begin with. Given this is a soccer team we are talking about, it is definitely worth being a full fledged class. However, if it were basketball... > (3) Suppose one wished to construct a player list...[snip] team = [Player(azip[0],azip[1],azip[2]) for azip in zip(names,attack,defense)] You have to love listcomp. Better (IMHO) would be team = [Player(azip) for azip in zip(names,attack,defense)] where a Player might come to life with class Player(object): def __init__(self, atup): self.name, self.attack, self.defense = atup BUT, even way better (again, IMHO) would be ateam = Team(zip(names,attack,defense)) where team could be initialized by a tuple: class Team(list): def __init__(self, azip): for azip in alist: self.data.append(Player(atup)) James -- James Stroud, Ph.D. UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From cjw at sympatico.ca Fri Apr 1 17:37:37 2005 From: cjw at sympatico.ca (Colin J. Williams) Date: Fri, 01 Apr 2005 17:37:37 -0500 Subject: unittest vs py.test? In-Reply-To: <1112372685.034751.99410@o13g2000cwo.googlegroups.com> References: <114pqf31isr8k4d@news.supernews.com> <1112372685.034751.99410@o13g2000cwo.googlegroups.com> Message-ID: Grig Gheorghiu wrote: > In my mind, practicing TDD is what matters most. Which framework you > choose is a function of your actual needs. The fact that there are 3 of > them doesn't really bother me. I think it's better to have a choice > from a small number of frameworks rather than have no choice or have a > single choice that might not be the best for your specific environment > -- provided of course that this doesn't evolve into a PyWebOff-like > nightmare :-) > > Grig > Grig, Many thanks for your helpful essays. unittest seems rather heavy. I don't like mixing tests with documentation, it gives the whole thing a cluttered look. Py.test is the more appealing but it doesn't appear to be ready for packaging yet. Thanks, Colin W. From fredrik at pythonware.com Fri Apr 8 13:08:35 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 8 Apr 2005 19:08:35 +0200 Subject: __iadd__ and __isub__ map to += and -= but don't return result References: <000e01c53c4c$4c1bd280$0201a8c0@mcuf7> Message-ID: Anthra Norell wrote: > If I am missing a point here, what could it be? the documentation? > class Vertex (list): > def __init__ (self, *coordinates): self [:] = list (coordinates [0:2]) > def __add__ (self, V): return Vertex (self [X] + V [X], self [Y] + V [Y]) > def __iadd__ (self, V): self [X] += V [X]; self [Y] += V [Y] > >>> V1 += V2 # *** > V1 # *** > # *** died ? > >>> print V1 > None # *** V1 died ! if you leave out the return statement, Python automagically inserts a "return None" at the end of your method. and the __iadd__ documentation says: These methods are called to implement the augmented arithmetic operations (+=, -=, *=, /=, %=, **=, <<=, >>=, &=, ^=, |=). These methods should attempt to do the operation in-place (modifying self) and return the result (which could be, but does not have to be, self). in other words, it works exactly as documented. you return None, you get None. From peter at engcorp.com Fri Apr 1 18:08:39 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 01 Apr 2005 18:08:39 -0500 Subject: unittest vs py.test? In-Reply-To: References: <114pqf31isr8k4d@news.supernews.com> <1112372685.034751.99410@o13g2000cwo.googlegroups.com> Message-ID: <1I2dnUmAu5ZPSdDfRVn-rA@powergate.ca> Colin J. Williams wrote: > unittest seems rather heavy. I don't like mixing tests with > documentation, it gives the whole thing a cluttered look. unittest can really be rather light. Most of our test cases are variations on the following, with primarily application-specific code added rather than boilerplate or other unittest-related stuff: import unittest class TestCase(unittest.TestCase): def test01(self): '''some test....''' self.assertEquals(a, b) def test02(self): '''another test''' self.assertRaises(Error, func, args) if __name__ == '__main__': unittest.main() That's it... add testXX() methods as required and they will be executed in sorted order (alphabetically) automatically when you run from the command line. The above might look excessive in comparison to the test code, but add some real code and the overhead quickly dwindles to negligible. I'm a little puzzled why folks so often consider this particularly "heavy". No need to deal with suites, TestResult objects, etc, as others have suggested, unless you are trying to extend it in some special way. -Peter From python-url at phaseit.net Mon Apr 4 13:08:02 2005 From: python-url at phaseit.net (Simon Brunning) Date: Mon, 04 Apr 2005 17:08:02 GMT Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Apr 4) Message-ID: QOTW: "Paraphrasing Occam, I would say 'don't multiply base classes without necessity'. ;)" - Michele Simionato "The world diversifies, the world congeals." - Raymond Hettinger (commenting on the fact that py.test happily runs unittest test suites) "I can think of no better reason for a programmer to regularly learn languages: 'our tools warp our thinking.' A programmer is a professionally warped thinker." - Scott David Daniels Highlight of the week; Python 2.4.1 final is out: http://groups-beta.google.com/group/comp.lang.python.announce/msg/b82afbc729226433 The effbot was once asked how to find an object's name: "The same way as you get the name of that cat you found on your porch: the cat (object) itself cannot tell you its name, and it doesn't really care -- so the only way to find out what it's called is to ask all your neighbours (namespaces) if it's their cat (object) ... and don't be surprised if you'll find that it's known by many names, or no name at all!" Duncan Booth shows us how to ask the neighbours: http://groups-beta.google.com/group/comp.lang.python/msg/237dc92f3629dd9a Ian Bicking and David Hansson talk marketing: http://blog.ianbicking.org/why-web-programming-matters-most.html http://www.loudthinking.com/arc/000432.html Incidentally, when will a hero(ine) emerge to do for GUI toolkits what the PyWebOff has started for Web frameworks? A couple of nice decorator examples this week: Scott David Daniels suggests that a decorator might tidy up wxPython event handlers, and Oren Tirosh shows us how to hide globals from a function: http://groups-beta.google.com/group/comp.lang.python/msg/338134f3bd7c439c http://groups-beta.google.com/group/comp.lang.python/msg/d34e97cc2ae284d6 Guido demonstrates multimethods, and Ian Bicking gives us an alternative implementation using generic functions: http://www.artima.com/weblogs/viewpost.jsp?thread=101605 http://blog.ianbicking.org/more-on-multimethods.html Is Python supposed to be boring? http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/ccf712755b3af3f4/437f80709adcbd86?rnum=1#ba7ad3fb3f503426 Evan Jones shows us How to Use UTF-8 with Python: http://evanjones.ca/python-utf8.html ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. For far, FAR more Python reading than any one mind should absorb, much of it quite interesting, several pages index much of the universe of Pybloggers. http://lowlife.jp/cgi-bin/moin.cgi/PythonProgrammersWeblog http://www.planetpython.org/ http://mechanicalcat.net/pyblagg.html comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Brett Cannon continues the marvelous tradition established by Andrew Kuchling and Michael Hudson of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ The Python Business Forum "further[s] the interests of companies that base their business on ... Python." http://www.python-in-business.org Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Cetus collects Python hyperlinks. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ (requires subscription) http://groups-beta.google.com/groups?q=python-url+group:comp.lang.python*&start=0&scoring=d& http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From abhishek216 at yahoo.com Tue Apr 19 07:58:18 2005 From: abhishek216 at yahoo.com (Abhishek S) Date: Tue, 19 Apr 2005 04:58:18 -0700 (PDT) Subject: Memory leak in python Message-ID: <20050419115818.67408.qmail@web31708.mail.mud.yahoo.com> Hi, using python2.2.2 I am seeing that the python application is very slowly eating up the memory. i need help to indentify it. It start with 11MB and keeps growing by 1 MB around every 30mins. #top | grep python 10351 root 15 0 26584 25M 3896 S 0.5 0.8 46:05 1 python2 10351 root 15 0 26592 25M 3896 S 3.5 0.8 46:06 1 python2 10351 root 15 0 26596 25M 3896 S 30.9 0.8 46:07 0 python2 10351 root 15 0 26608 25M 3896 S 73.0 0.8 46:11 0 python2 10351 root 15 0 26612 25M 3896 S 73.2 0.8 46:15 0 python2 10351 root 15 0 26616 25M 3896 S 78.6 0.8 46:18 1 python2 10351 root 15 0 26620 25M 3896 S 78.4 0.8 46:22 1 python2 10351 root 15 0 26620 25M 3896 S 77.4 0.8 46:26 1 python2 10351 root 15 0 26620 25M 3896 S 73.2 0.8 46:30 1 python2 10351 root 15 0 26620 25M 3896 S 65.8 0.8 46:33 1 python2 10351 root 15 0 26620 25M 3896 S 43.3 0.8 46:35 1 python2 10351 root 15 0 26620 25M 3896 S 53.8 0.8 46:38 1 python2 10351 root 15 0 26620 25M 3896 S 26.3 0.8 46:39 1 python2 10351 root 15 0 26636 26M 3896 S 33.5 0.8 46:41 1 python2 10351 root 15 0 26640 26M 3896 S 25.7 0.8 46:42 1 python2 10351 root 15 0 26656 26M 3896 S 23.9 0.8 46:44 1 python2 10351 root 15 0 26656 26M 3896 S 11.7 0.8 46:44 1 python2 10351 root 15 0 26660 26M 3896 S 10.7 0.8 46:45 1 python2 10351 root 15 0 26668 26M 3896 S 3.7 0.8 46:45 1 python2 10351 root 15 0 26668 26M 3896 S 1.7 0.8 46:45 1 python2 10351 root 15 0 26668 26M 3896 S 0.7 0.8 46:45 1 python2 10351 root 15 0 26668 26M 3896 S 0.3 0.8 46:45 1 python2 10351 root 15 0 26684 26M 3896 S 4.5 0.8 46:45 1 python2 10351 root 15 0 26688 26M 3896 S 2.1 0.8 46:45 1 python2 let me know how to approch this. gc.collect - does not collect anything. Thanks, Abhishek __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From claird at lairds.us Thu Apr 28 11:08:06 2005 From: claird at lairds.us (Cameron Laird) Date: Thu, 28 Apr 2005 15:08:06 GMT Subject: Getting the sender widget's name in function (Tkinter) References: <1114545565.116766.157000@f14g2000cwb.googlegroups.com> <1114547849.644971.191270@f14g2000cwb.googlegroups.com> Message-ID: In article , Eric Brunel wrote: >On 26 Apr 2005 13:37:29 -0700, infidel wrote: > >> from Tkinter import Tk, Button >> >> def say_hello(event): >> print 'hello!' >> print event.widget['text'] >> >> root = Tk() >> button1 = Button(root, text='Button 1') >> button1.bind('', say_hello) >> button1.pack() >> button2 = Button(root, text='Button 2') >> button2.bind('', say_hello) >> button2.pack() >> root.mainloop() > >Unfortunately, making a binding to on Button widgets does not >have the same behavior as setting their 'command' option. The binding >will fire when the button is *pressed*; the command will be called when >the button is *released*. So, binding to instead of > make things a little better, but still does not have the same >effect, since ButtonPress and ButtonRelease events are balanced: the >widget getting the ButtonRelease event is always the same as the one >getting the ButtonPress event. So if the mouse button is pressed inside >the Button, then the mouse pointer goes out of it, and then the mouse >button is released, the Button will still get the ButtonRelease event >and fire the binding. This is not the normal behavior for a button and >this is not the behavior you get via the 'command' option (just try >it...). > >So having a different function for each button or using tiissa's >solution is definitely better. . . . Without unraveling my own confusion about who has said what to whom, does everyone realize that Tkinter bind()ings inherently can access the widgets which generate their events? Please refer to Table 7-2 in (and thank Fredrik, once again, for his marvelous work in putting this material online). From cdkrug at worldnet.att.net Thu Apr 28 13:58:47 2005 From: cdkrug at worldnet.att.net (Charles Krug) Date: Thu, 28 Apr 2005 17:58:47 GMT Subject: OOP References: <1114709684.096071.109960@l41g2000cwc.googlegroups.com> Message-ID: On 28 Apr 2005 10:34:44 -0700, demon_slayer2839 at yahoo.com wrote: > Hey yall, > I'm new to Python and I love it. Now I can get most of the topics > covered with the Python tutorials I've read but the one thats just > stumping me is Object Orientation. I can't get the grasp of it. Does > anyone know of a good resource that could possibly put things in focus > for me? Thanks. > "Learning Python" (Lutz/Ascher) has a good discussion of the basics. Unfortunately, most of the OOP writings I've read fall into two catagories: Trivial examples where you say, "But why Bother??" and examples that you don't understand until you've some OO design under your belt and can understand what it's all good for. Objects are, at the end of the day, data and the accompanying methods. Once you've read the various tutorials take a stab at converting a problem you know well into objects. You'll get it wrong at first. Most everyone does. Don't sweat it. Eventually, you'll just "get" it. From jerf at jerf.org Sat Apr 23 00:02:21 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Sat, 23 Apr 2005 00:02:21 -0400 Subject: Python Imaging Library and PyGTK - color image path? References: Message-ID: On Fri, 22 Apr 2005 22:43:13 -0400, Jeremy Bowers wrote: > (Use case, in case it matters: I am trying to embed a graphic into a text > widget. This is going fine. Because I want the text widget to be able use > different size text, and no one image can look right with everything from > 8pt to 40pt text (all reasonable possibilities), I load a large image in > from the disk and scale it down as needed; the images are designed to > scale well and later I can make multiple source images if that is > desirable. But I can't figure out how to get the scaled image into GTK. > This surprises me.) As usual, posting for help after poking around for a long while guarantees you'll figure it out in the next few minutes. You need to create GDK pixbufs, which can be resized and scaled and stuff. There is definitely some room for confusion here with GTK Images, GDK Images, GTK pixbufs, and GDK pixbufs.... From peter at engcorp.com Wed Apr 20 11:46:34 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 20 Apr 2005 11:46:34 -0400 Subject: Faster os.walk() In-Reply-To: References: <1114011606.600970.43300@l41g2000cwc.googlegroups.com> Message-ID: Laszlo Zsolt Nagy wrote: > fuzzylollipop wrote: > >> I am trying to get the number of bytes used by files in a directory. >> I am using a large directory ( lots of stuff checked out of multiple >> large cvs repositories ) and there is lots of wasted time doing >> multiple os.stat() on dirs and files from different methods. >> >> > Do you need a precise value, or are you satisfied with approximations too? > Under which operating system? The 'du' command can be your firend. How can "du" find the sizes without do os.stat() on each file? From mauriceling at acm.org Sun Apr 3 06:21:59 2005 From: mauriceling at acm.org (Maurice Ling) Date: Sun, 03 Apr 2005 20:21:59 +1000 Subject: text analysis in python Message-ID: <424FC3C7.1030205@acm.org> Hi, I'm a postgraduate and my project deals with a fair bit of text analysis. I'm looking for some libraries and tools that is geared towards text analysis (and text engineering). So far, the most comprehensive toolkit in python for my purpose is NLTK (natural language tool kit) by Edward Loper and Steven Bird, followed by mxTextTools. Are there any OSS tools out there that is more comprehensive than NLTK? In the Java world, there is GATE (general architecture for text engineering) and it seems very impressive. Are there something like that for Python? Thanks in advance. Cheers Maurice -------------- next part -------------- A non-text attachment was scrubbed... Name: mauriceling.vcf Type: text/x-vcard Size: 347 bytes Desc: not available URL: From "Kato Dakota" at yahoo.com Sat Apr 9 14:25:40 2005 From: "Kato Dakota" at yahoo.com (Kato Dakota) Date: Sat, 09 Apr 2005 18:25:40 GMT Subject: THE GREATEST NEWS EVER ! =?iso-8859-1?q?=B0=BA=B7=2E=2E=2E=B7?= =?iso-8859-1?q?=B0=60=B0=BA=B7=2E=2E=2E=B7=B0=60=B0=BA=B7=2E=2E=2E=B7=B0?= =?iso-8859-1?q?=60=B0=BA=B7=2E=2E=2E=B7=B0=60=B0=BA=B7=2E=2E=2E=B7=B0=60?= =?iso-8859-1?q?=B0=BA=B7=2E=2E=2E=B7=B0=60=B0=BA=B7=2E=2E=2E=B7=B0=60=B0?= =?iso-8859-1?q?=BA=B7=2E=2E=2E=B7=B0=60=B0=BA=B7=2E=2E=2E=B7=B0=60=B0=BA?= =?iso-8859-1?q?=B7=2E=2E=2E=B7=B0=60=B0=BA=B7=2E=2E=2E=B7=B0=60=B0=BA=B7?= =?iso-8859-1?q?=2E=2E=2E=B7=B0=60=B0=BA=B7=2E=2E=2E=B7=B0=60=B0=BA=B7=2E?= =?iso-8859-1?q?=2E=2E=B7=B0=60=B0=BA=B7=2E=2E=2E=B7=B0=60=B0=BA=B7=2E=2E?= =?iso-8859-1?q?=2E=B7=B0=60=B0=BA=B7=2E=2E=2E=B7=B0=60=B0=BA=B7=2E=2E=2E?= =?iso-8859-1?q?=B7=B0=60=B0=BA=B7=2E=2E=2E=B7=B0=60=B0=BA=B7=2E=2E=2E=B7?= =?iso-8859-1?q?=B0=60=B0=BA=B7=2E=2E=2E=B7=B0=60=B0=BA=B7=2E=2E=2E=B7=B0?= =?iso-8859-1?q?=60=B0=BA=B7=2E=2E=2E=B7=B0=60=B0=BA=B7=2E=2E=2E=B7=B0=60_?= =?iso-8859-1?q?=28newsgroup-post_127=29?= In-Reply-To: <1113068396.414326.217300@o13g2000cwo.googlegroups.com> References: <1113068396.414326.217300@o13g2000cwo.googlegroups.com> Message-ID: RonGrossi_38157 at yahoo.com wrote: > > The reason some people don't know for sure > if they are going to Heaven when they die > is because they just don't know. > SATAN RULEZ!! From martin.witte at gmail.com Sun Apr 24 12:45:02 2005 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 24 Apr 2005 09:45:02 -0700 Subject: optparse: store callback return value In-Reply-To: <1114340683.593168.148310@g14g2000cwa.googlegroups.com> References: <1114340683.593168.148310@g14g2000cwa.googlegroups.com> Message-ID: <1114361102.007871.193580@f14g2000cwb.googlegroups.com> Callbacks are functions called when an optparse.OptionParser() object has a callback option defined (don't know how to say this less obvious sounding...) (they are documented in http://docs.python.org/lib/optparse-option-callbacks.html) Example (based on an example in the documentation): this script: -#!/usr/bin/env python -import optparse -def record_foo_seen(option, opt_str, value, parser): - print 'saw foo' - -parser = optparse.OptionParser() -parser.add_option("--foo", action="callback", callback=record_foo_seen) -(options, args) = parser.parse_args() - -print options, args prints when executed with or without argument: martin at ubuntu:~$ ./test2.py --foo saw foo {} [] martin at ubuntu:~$ ./test2.py {} [] martin at ubuntu:~$ From jjl at pobox.com Wed Apr 6 14:46:00 2005 From: jjl at pobox.com (John J. Lee) Date: 06 Apr 2005 19:46:00 +0100 Subject: Best editor? References: <1112725379.514651.66540@l41g2000cwc.googlegroups.com> Message-ID: "ChinStrap" writes: > When not using the interactive prompt, what are you using? I keep > hearing everyone say Emacs, but I can't understand it at all. I keep > trying to learn and understand why so many seem to like it because I > can't understand customization even without going through a hundred > menus that might contain the thing I am looking for (or I could go > learn another language just to customize!). [...] > Opinions on what the best is? Or reading I could get to maybe sway me > to Emacs (which has the major advantage of being on everyone's system). Two reasons I use emacs: 1. For any question "Can I do X with emacs", the answer is almost always "yes, use this code that's already written and working" 2. I already know it ;-) BTW, I use vi keybindings, and I imagine all other editors can do the same (though perhaps not as well as viper, the emacs package that does this -- see 1. above), so that's no reason in itself to use vim. John From gry at ll.mit.edu Wed Apr 6 11:00:35 2005 From: gry at ll.mit.edu (gry at ll.mit.edu) Date: 6 Apr 2005 08:00:35 -0700 Subject: formatting file In-Reply-To: References: Message-ID: <1112799635.165142.136620@f14g2000cwb.googlegroups.com> SPJ wrote: > I am new to python hence posing this question. > I have a file with the following format: > > test1 1.1-1 installed > test1 1.1-1 update > test2 2.1-1 installed > test2 2.1-2 update > > I want the file to be formatted in the following way: > > test1 1.1-1 1.1-2 > test2 2.1-1 2.1-2 For data that has a clear tree structure with keys, a quick solution is often a dictionary, or dictionary of dictionaries. The setdefault idiom below is very handy for this sort of thing. The test name "test1" is key to the top dict. The operation "update" is the key to the sub dictionary. Setdefault returns the dict for the specified test, or a new dict if there is none. .d={} .for line in open('tests.txt'): . test,version,operation = l.split() . d.setdefault(test,{})[operation] = version .for test,d in d.items(): . print test, d['installed'], d['update'] [BWT, your given test data appears to have been wrong "test1 1.1-1 update"; please be careful not to waste people's time who try to help...] -- George From lbates at syscononline.com Mon Apr 11 10:51:47 2005 From: lbates at syscononline.com (Larry Bates) Date: Mon, 11 Apr 2005 09:51:47 -0500 Subject: My stupid newbie mistake In-Reply-To: References: Message-ID: Because Python allows you to replace built-in methods with your own. Later you will find that this can be extremely powerful. You will stumble on this if you name a list 'list' a string 'str', integer 'int', float 'float', dictionary 'dict', ... (at least I did ). -Larry Bates Matt Feinstein wrote: > I named a file 'try.py' and then was stumped, for a while, when > > >>>>import try > > > gave a syntax error... So, how about a > 'YouAreUsingAReservedWordStupid' exception ? > > Matt Feinstein > > -- > There is no virtue in believing something that can be proved to be true. From jstroud at mbi.ucla.edu Tue Apr 19 15:18:13 2005 From: jstroud at mbi.ucla.edu (James Stroud) Date: Tue, 19 Apr 2005 12:18:13 -0700 Subject: python In-Reply-To: <27b90ebf.0504191109.b4d8513@posting.google.com> References: <27b90ebf.0504191109.b4d8513@posting.google.com> Message-ID: <200504191218.13423.jstroud@mbi.ucla.edu> python.org On Tuesday 19 April 2005 12:09 pm, waqar wrote: > I am new to python. I need some information on following specifically: > > - Background & Evolution of python > - current application areas > - future trend. > > Kindly any one provide me such information or tell websites for that > purpose. -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From roccomoretti at hotpop.com Sun Apr 24 17:04:32 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Sun, 24 Apr 2005 16:04:32 -0500 Subject: Python or PHP? In-Reply-To: References: <1114254894.512656.297040@l41g2000cwc.googlegroups.com> <426A534D.1080002@mage.hu> Message-ID: Roman Neuhauser wrote: > # mage at mage.hu / 2005-04-23 15:53:17 +0200: > >>Lad wrote: >> >> >>>Is anyone capable of providing Python advantages over PHP if there are >>>any? The irreverant would point you to http://www.python.org/doc/Humor.html#vowels *I* wouldn't consider doing anything like that, though. >>check this: http://wiki.w4py.org/pythonvsphp.html > > The comparison found there is biased, the author is a Python > partisan. > Yeah, as opposed to the completely unbiased opinions the OP expected to find on comp.lang.PYTHON From ptmcg at austin.rr.com Tue Apr 26 05:56:46 2005 From: ptmcg at austin.rr.com (Paul McGuire) Date: 26 Apr 2005 02:56:46 -0700 Subject: Order of elements in a dict References: Message-ID: <1114509406.165590.90260@o13g2000cwo.googlegroups.com> Here is a brute-force list comprehension that does not depend on preserving order between dict.keys() and dict.values(): dict( [ (a[1],a[0]) for a in d.items() ] ) Or for map/lambda lovers: rev = lambda a: (a[1],a[0]) dict( map( rev, d.items() ) But you still have no control over the order returned by d.items(), so if your initial dict has duplicate values, there is no telling which key a duplicate would map to. The real general-purpose dict inversion results in a dict with each value containing a list of keys in the original dict that mapped to the given value. That is: d = {3: 4, 1: 2, 0:4} would invert to: d2 = { 2:[1], 4:[0,3] } I couldn't cram this into a list comp, so here is a short for loop to create d2: d2 = {} for k,v in d.items(): d2[v] = d2.get(v, list()) + [k] -- Paul From anthra.norell at tiscalinet.ch Fri Apr 8 11:04:43 2005 From: anthra.norell at tiscalinet.ch (Anthra Norell) Date: Fri, 8 Apr 2005 17:04:43 +0200 Subject: __iadd__ and __isub__ map to += and -= but don't return result Message-ID: <000e01c53c4c$4c1bd280$0201a8c0@mcuf7> Hi! If I am missing a point here, what could it be? Watch the hot spots (***) Frederic ############################################################################# # Python 2.4, Windows ME X = 0, Y = 1 class Vertex (list): def __init__ (self, *coordinates): self [:] = list (coordinates [0:2]) def __add__ (self, V): return Vertex (self [X] + V [X], self [Y] + V [Y]) def __iadd__ (self, V): self [X] += V [X]; self [Y] += V [Y] >>> V1 = Vertex (1, 2) >>> V2 = Vertex (4, 6) >>> V1 + V2 [5, 8] # OK >>> V1 += V2 # *** V1 # *** # *** died ? >>> print V1 None # *** V1 died ! >>> V2 [5, 8] # V2 is fine # Adding three traces to follow the state of self def __iadd__ (self, V): print 'A', self self [X] += V [X] print 'B', self self [Y] += V [Y] print 'C', self >>> V1 += V2 A [1, 2] B [5, 2] C [5, 8] # *** self is still OK when method terminates. # *** Also shows that operator += did call __iadd__, # *** (though the 2.4 doc no longer mentions it) # Explicit call works fine >>> V1.__iadd__ (V2) A [1, 2] B [5, 2] C [5, 8] >>> V1 [5, 8] <<<< OK !!! -------------- next part -------------- An HTML attachment was scrubbed... URL: From dek at bosshog.lbl.gov Mon Apr 25 10:43:27 2005 From: dek at bosshog.lbl.gov (David E. Konerding DSD staff) Date: Mon, 25 Apr 2005 14:43:27 +0000 (UTC) Subject: Python callbacks & PyGILState_Release() References: Message-ID: In article , Randall Hopper wrote: > Thomas Heller: > |> Python -> C++ -> Python Callback > |> > |> (example attached) an exception raised in the callback doesn't make it back > |> across C++ to Python. > ... > |> void callback_wrapper( void *user_data ) > |> { > |> // Acquire interpreter lock > |> PyGILState_STATE gstate = PyGILState_Ensure(); > |> ... > |> // Call Python > |> pyresult = PyEval_CallObject( pyfunc, pyargs ); > |> ... > | > | if (pyresult == NULL) > | PyErr_Print(); > | > |> // Free interpreter lock > |> PyGILState_Release(gstate); > |> } > | > |PyErr_Print() will do the 'right' thing?s. > > Thanks for the reply. However, this won't: > > a) Stop the main Python script, and > b) Print the full stack trace (including Python and C++ SWIG wrapper) > > Is there a clean way to save the full exception state in the callback > before the PyGILState_Release(), and restore it when we return across the > C++ wrapper? > > If I knew what the proper "save" and "restore" exception state code bits > were, I could easily implement this with exception typemaps in SWIG. > > Thanks, > > Randall > > P.S. Perhaps PyGILState_Release should take an argument instructing it to > exclude exception state when resetting the interpreter state back to its > original state. Randall: It's not the job of the PyGILState_* functions to manage exception details for you. I always solved this problem a different way, by saving the exception in an instance variable within the Python callback, and using a condition variable so that the main thread could abort on a callback's failure. Notably, our callsbacks are always invoked from a C++ thread that the main Python interepreter didn't create, and our main Python intepreter is blocked on a mutex most of the time. I saved the exception state by retrieveing it from sys.exc_info(), which contains all the traceback object data as Python variable. I think you can get the same info from your C++ callback wrapper, and use PyErr_Fetch and PyErr_Restore to save and restore the exception sate. Dave From duncan.booth at invalid.invalid Mon Apr 11 04:52:41 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 11 Apr 2005 08:52:41 GMT Subject: Help understanding code References: <42591EE2.9040203@verizon.net> Message-ID: Fredrik Lundh wrote: > Dhruva Hein wrote: >> results = pc() >> <=== what is the difference between pc and pc()? > > pc refers to an object, pc() calls it. in this case, it looks like pc is > the > portal catalog, and calling the catalog returns the contents. > Unfortunately there is quite a bit going on behind the scenes here so if you don't know Plone it will be confusing: Calling the catalog is equivalent to calling the catalog method searchResults. This performs a catalog search and if (as in this case) no other arguments are passed to it it will pick up the search parameters from the current REQUEST object. Also it will add some additional search parameters: there must be a match between the user's allowed roles or userid and the 'allowedRolesAndUsers' index, and if the user doesn't have permission to access expired content, it will add some additional parameters to constrain the search to objects after their effective date and before their expired date. > that line is equivalent to > > temp = numbers["bytype"] > temp[ctype] = num ... and since temp is a constant throughout the loop it can be extracted from the loop and given a better name. All of that code would have been clearer if the original author had simply kept a reference to the bytype and bystate dictionaries and not insisted on the extra level of indirection by accessing them through the numbers dictionary. From jjl at pobox.com Fri Apr 22 16:54:00 2005 From: jjl at pobox.com (John J. Lee) Date: 22 Apr 2005 20:54:00 +0000 Subject: Python licence again References: <1114197761.019100.38890@o13g2000cwo.googlegroups.com> Message-ID: <87fyxilehj.fsf@pobox.com> Laszlo Zsolt Nagy writes: > fuzzylollipop wrote: > > >try spelling license correctly next time and heading the google > >suggestions that probably looked like "didn't you mean : Python License" > > > Oh yes, that was the problem. I'm not aware of that. Unfortunately, > I'm not an American. I'm Hungarian > and my dictionary said 'licence' is correct. But I looked at > 'license'. It means almost the same. :-) > > Is it something like 'center' or 'color' for Americans and 'centre' or > 'colour' for British people? Yes. ISTR that licence is a British English spelling, though my British brain has been thoroughly contaminated by US spellings and usage by now. (Or are they like practice and practise, which (can) mean subtly different things in British English (which few native English speakers can keep straight, certainly not me...)?) I will never pronounce thorough 'thurrow', though. One must draw a line. John From robin at reportlab.com Thu Apr 28 09:22:13 2005 From: robin at reportlab.com (Robin Becker) Date: Thu, 28 Apr 2005 14:22:13 +0100 Subject: regex over files In-Reply-To: <17008.19697.939514.53469@montanaro.dyndns.org> References: <426D0659.7080307@chamonix.reportlab.co.uk> <426D08BC.1040703@klix.ch> <426E021E.8000809@jessikat.fsnet.co.uk> <17006.31984.182979.430076@montanaro.dyndns.org> <426E893D.2070905@chamonix.reportlab.co.uk> <426EAA9D.2050904@jessikat.fsnet.co.uk> <426F5B62.3010801@chamonix.reportlab.co.uk> <17008.19697.939514.53469@montanaro.dyndns.org> Message-ID: <4270E385.6040403@chamonix.reportlab.co.uk> Skip Montanaro wrote: ..... > > Let me return to your original problem though, doing regex operations on > files. I modified your two scripts slightly: > ..... > Skip I'm sure my results are dependent on something other than the coding style I suspect file/disk cache and paging operates here. Note that we now agree on total match length and split count. However, when the windows VM goes into paging mode the mmap thing falls off the world as I would expect for a thrashing system. eg small memory (relatively) C:\code\reportlab\demos\gadflypaper>\tmp\sscan0.py xxx_100mb.dat fn=xxx_100mb.dat n=1898737 l=90506416 time=3.55 C:\code\reportlab\demos\gadflypaper>\tmp\sscan1.py xxx_100mb.dat fn=xxx_100mb.dat n=1898737 l=90506416 time=8.25 C:\code\reportlab\demos\gadflypaper>\tmp\sscan1.py xxx_100mb.dat fn=xxx_100mb.dat n=1898737 l=90506416 time=9.77 C:\code\reportlab\demos\gadflypaper>\tmp\sscan0.py xxx_100mb.dat fn=xxx_100mb.dat n=1898737 l=90506416 time=5.09 C:\code\reportlab\demos\gadflypaper>\tmp\sscan1.py xxx_100mb.dat fn=xxx_100mb.dat n=1898737 l=90506416 time=6.17 C:\code\reportlab\demos\gadflypaper>\tmp\sscan0.py xxx_100mb.dat fn=xxx_100mb.dat n=1898737 l=90506416 time=4.64 and large memory C:\code\reportlab\demos\gadflypaper>\tmp\sscan0.py xxx_200mb.dat fn=xxx_200mb.dat n=3797470 l=181012689 time=20.16 C:\code\reportlab\demos\gadflypaper>\tmp\sscan1.py xxx_200mb.dat fn=xxx_200mb.dat n=3797470 l=181012689 time=136.42 At the end of this run I had to wait quite a long time for other things to become responsive (ie things were entirely paged out). Here I've implemented slightly modified versions of the scanners that you put forward. eg #sscan0.py thanks to Bengt import sys, time, re fn = sys.argv[1] rxo = re.compile('XXXXX') def frxsplit(path, rxo, chunksize=4096): buffer = '' for chunk in iter((lambda f=open(path,'rb'): f.read(chunksize)),''): buffer += chunk pieces = rxo.split(buffer) for piece in pieces[:-1]: yield piece buffer = pieces[-1] yield buffer l=n=0 t0 = time.time() for mat in frxsplit(fn,rxo): n += 1 l += len(mat) t1 = time.time() print "fn=%s n=%d l=%d time=%.2f" % (fn, n, l, (t1-t0)) #sscan1.py thanks to Skip import sys, time, mmap, os, re fn = sys.argv[1] fh=os.open(fn,os.O_BINARY|os.O_RDONLY) s=mmap.mmap(fh,0,access=mmap.ACCESS_READ) l=n=0 t0 = time.time() for mat in re.split("XXXXX", s): n += 1 l += len(mat) t1 = time.time() print "fn=%s n=%d l=%d time=%.2f" % (fn, n, l, (t1-t0)) -- Robin Becker From danb_83 at yahoo.com Wed Apr 13 11:02:12 2005 From: danb_83 at yahoo.com (Dan Bishop) Date: 13 Apr 2005 08:02:12 -0700 Subject: Compute pi to base 12 using Python? References: <1113390479.738210.49530@z14g2000cwz.googlegroups.com> Message-ID: <1113404532.101185.226690@g14g2000cwa.googlegroups.com> Dick Moores wrote: > Dan Bishop wrote at 04:07 4/13/2005: ... > >For a floating-point number x, the representation with d "decimal" > >places count be found by taking the representation of int(round(x * > >radix ** d)) and inserting a "." d places from the right. > > But I'm sorry, but I can't follow you. I do have the first 10000 or so > places of pi base 10 (), but > could you show me what to do with, say, just 3.14159? First, decide how many "decimal" places to use for the conversion. Five decimal digits is equivalent to 5*log(10)/log(12) = 4.63 base-12 digits, so use 4 digits. Next, multiply by 12**4, obtaining the value 65144.01024, and round to the nearest integer, 65144. Convert this to base 12, obtaining 31848. But this is 12**4 times the number we really want, so divide this by 12**4 (i.e., shift the radix point left 4 places), for a final result of 3.1848. From bingham at cenix-bioscience.com Wed Apr 20 11:51:16 2005 From: bingham at cenix-bioscience.com (Aaron Bingham) Date: Wed, 20 Apr 2005 17:51:16 +0200 Subject: Why Python does *SLICING* the way it does?? In-Reply-To: (Bernhard Herzog's message of "Wed, 20 Apr 2005 17:28:01 +0200") References: <1113976729.450677.261130@o13g2000cwo.googlegroups.com> <87r7h5lk5a.fsf@wilson.rwth-aachen.de> Message-ID: Bernhard Herzog writes: > There are very good reasons for half-open intervals and starting at 0 > apart from memory organization. Dijkstra explained this quite well in > http://www.cs.utexas.edu/users/EWD/ewd08xx/EWD831.PDF Thanks for the excellent link! -- -------------------------------------------------------------------- Aaron Bingham Software Engineer Cenix BioScience GmbH -------------------------------------------------------------------- From jfj at freemail.gr Mon Apr 25 09:30:05 2005 From: jfj at freemail.gr (jfj) Date: Mon, 25 Apr 2005 16:30:05 +0300 Subject: What's do list comprehensions do that generator expressions don't? In-Reply-To: <86hdhvotgq.fsf@guru.mired.org> References: <86ll77pgqz.fsf@guru.mired.org> <426CB5DC.1050301@freemail.gr> <86hdhvotgq.fsf@guru.mired.org> Message-ID: <426CF0DD.5050909@freemail.gr> Mike Meyer wrote: > jfj writes: > > >>I think a better question would be "What do *generator expressions* do >>that list comprehensions don't?". And always use list comprehensions >>unless you want the extra bit. > > > As the OP, I can say why I didn't ask those questions. Sorry. I was referring to the subject line:) > > Generator expressions don't build the entire list in memory before you > have to deal with it. This makes it possible to deal with expressions > that are to long to fit in memory. > > Which means that the real rule should be always use generator > expressions, unless you *know* the expression will always fit in > memory. > Consider this code which I also included the first reply: x = [i for in in something()] random.shuffle (x) x.sort () Shuffle and sort are two examples where need *the entire list* to work. Similarily for a dictionary where the values are small lists. In this example using a generator buys you *nothing* because you will immediately build a list. So there are cases where we need the list as the product of an algorithm and a generator is not good enough. In fact, in my experience with python so far I'd say that those cases are the most common case. That is the one question. The other question is "why not list(generator) instead of [list comprehension]?" I guess that lists are *so important* that having a primary language feature for building them is worth it. On the other hand "list()" is not a primary operator of the python language. It is merely a builtin function. jfj From bh at intevation.de Wed Apr 20 11:28:01 2005 From: bh at intevation.de (Bernhard Herzog) Date: Wed, 20 Apr 2005 17:28:01 +0200 Subject: Why Python does *SLICING* the way it does?? References: <1113976729.450677.261130@o13g2000cwo.googlegroups.com> <87r7h5lk5a.fsf@wilson.rwth-aachen.de> Message-ID: Torsten Bronger writes: > It's interesting to muse about a language that starts at "1" for all > arrays and strings, as some more or less obsolete languages do. I > think this is more intuitive, since most people (including > mathematicians) start counting at "1". The reason for starting at > "0" is easier memory address calculation, so nothing for really high > level languages. There are very good reasons for half-open intervals and starting at 0 apart from memory organization. Dijkstra explained this quite well in http://www.cs.utexas.edu/users/EWD/ewd08xx/EWD831.PDF Bernhard -- Intevation GmbH http://intevation.de/ Skencil http://skencil.org/ Thuban http://thuban.intevation.org/ From news at NOwillmcguganSPAM.com Fri Apr 8 17:16:48 2005 From: news at NOwillmcguganSPAM.com (Will McGugan) Date: Fri, 08 Apr 2005 22:16:48 +0100 Subject: Counting iterations In-Reply-To: <1112994185.983954.234650@l41g2000cwc.googlegroups.com> References: <1112994185.983954.234650@l41g2000cwc.googlegroups.com> Message-ID: <4256f4c0$0$2603$da0feed9@news.zen.co.uk> Derek Basch wrote: > Is there a better way to count iterations that this?: > > pets = 0 > for i in pets: > pets += 1 > print "pet" + "#" + pets > You can use 'enumerate' to get the index, but the code above wont work - you are trying to iterate over a non-sequence. Will McGugan -- "".join( [ {'@':'@','.':'.'}.get(c,None) or chr(97+((ord(c)-97)+13)%26) for c in "jvyy at jvyyzpthtna.pbz" ] ) From phil at riverbankcomputing.co.uk Tue Apr 5 06:43:38 2005 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Tue, 5 Apr 2005 11:43:38 +0100 (BST) Subject: Eric3 under WinXP In-Reply-To: <8to45154ueb3m8gfb0sj1v3ud24j5jnm7d@4ax.com> References: <8to45154ueb3m8gfb0sj1v3ud24j5jnm7d@4ax.com> Message-ID: <6651.82.68.80.137.1112697818.squirrel@river-bank.demon.co.uk> > On Tue, 5 Apr 2005 10:14:48 +0100 (BST), "Phil Thompson" > wrote: > >>> On Tue, 5 Apr 2005 09:17:05 +0100 (BST), "Phil Thompson" >>> wrote: >>> >>> What steps are missing? >> >>If you are using the evaluation version of Qt then you need the >> evaluation >>version of PyQt. This already includes SIP and QScintilla. >> >>Phil > Hello Phil, > > Ok, new begin. > > I installed PyQt 3.14.1 Evaluation now. > If I want to start for example aclock.py, I get: > > ImportError: No module named qt > Is there any dll missing? > > Or doesn't it fit with "Qt 3.3.4 Evaluation" > > Any hints? What version of Python do you have installed? The binary is built against v2.4. BTW, your email address is bouncing messages. Phil From shane at hathawaymix.org Fri Apr 29 22:43:53 2005 From: shane at hathawaymix.org (Shane Hathaway) Date: Fri, 29 Apr 2005 20:43:53 -0600 Subject: Python Challenge ahead [NEW] for riddle lovers In-Reply-To: <200504291940.29908.bulliver@badcomputer.org> References: <4272C8A0.7050404@hathawaymix.org> <200504291940.29908.bulliver@badcomputer.org> Message-ID: <4272F0E9.5040406@hathawaymix.org> darren kirby wrote: > quoth the Shane Hathaway: > >>pythonchallenge wrote: >> >>>For the riddles' lovers among you, you are most invited to take part >>>in the Python Challenge, the first python programming riddle on the net. >>> >>>You are invited to take part in it at: >>>http://www.pythonchallenge.com >> >>That was pretty fun. Good for a Friday. Too bad it comes to an abrupt >>"temporary end". >> >>Shane >> >>P.S. I hope I didn't hammer your server on step 3. I was missing the >>mark. :-) > > > You're not the only one. This is where I am currently stuck. It's starting to > hurt my head. > > There are 478 results in the form *BBBsBBB* but the thing said 'exactly' > right, well there are 10 results in the form *sBBBsBBBs* > None of them seem to work... I did the same thing. Now just combine those ten results. Shane From radam2 at tampabay.rr.com Sun Apr 3 12:38:28 2005 From: radam2 at tampabay.rr.com (Ron_Adam) Date: Sun, 03 Apr 2005 16:38:28 GMT Subject: Docorator Disected References: <4p9t419ockcg8578g6guse3a14t16orebf@4ax.com> <424f04d0.137947037@news.oz.net> <1112500967.391604.289760@f14g2000cwb.googlegroups.com> <0mqu41pham7n91vb1qgtoe567unn1cffb6@4ax.com> <424f982c.175671582@news.oz.net> Message-ID: On Sun, 03 Apr 2005 07:53:07 GMT, bokr at oz.net (Bengt Richter) wrote: >>No, I did not know that you could pass multiple sets of arguments to >That phraseology doesn't sound to me like your concept space is quite isomorphic >with reality yet, sorry ;-) You'll be happy to know, my conceptual conceptions are conclusively isomorphic this morning. :-) >It sounds like you are thinking of "multiple sets of arguments" >as an aggregate that is passed as such, and that isn't happening, as I believe El Pitonero >is trying to indicate with his parenthesized visualization below. Well there are multiple sets of arguments, and there are multiple functions involved. It's just a matter of how they get matched up. Depending on what level you look at it, it could be both ways. But the correct way to view it is in the context of the language it self, and not the underlying byte code, c++ or assembly code. >What is happening is that an expression "foo(2)(6)" is being evaluated left to right. >First foo as a name evaluates to whatever it is bound to, which is the foo function. >Then () is the calling operator, which says evaluate the list inside the parens left to right >and call the thing you had so far, which was foo here. The arg list was just 2, so foo is called >with 2, and foo returns something, with which we will do the next operation if there is one. Like this of course: def foo(x): def fee(y): return y*x return fee statement: z = foo(2)(6) becomes: z = fee(6) becomes: z = 12 The position of the 'def fee' inside of 'def foo' isn't relevant, it's only needed there so it can have access to foo's name space. It could be at the top or bottom of the function it is in, and it wouldn't make a difference. This would be the same without the nesting: def foo(xx): global x x = xx return fee def fee(y): global x return y*x z = foo(2)(6) >So if you are seeing (2)(6) as something to pass, as opposed to a sequence of operations, I think there's >a misconception involved. Perhaps I am taking your words askew ;-) It's not entirely a misconception. Lets see where this goes... > >>> dis.dis(compiler.compile('foo(2)(6)','','eval')) > 1 0 LOAD_NAME 0 (foo) > 3 LOAD_CONST 1 (2) > 6 CALL_FUNCTION 1 > 9 LOAD_CONST 2 (6) > 12 CALL_FUNCTION 1 > 15 RETURN_VALUE In this example, you have byte code that was compiled from source code, and then an interpreter running the byte code; which in it self, is a program written in another language to execute the byte code, C++; which gets translated into yet another language, assembly; which at one time would have corresponded to specific hardwired registers and circuits,(I could go further...ie... translators... PNP... holes...), but with modern processors, it may yet get translated still further. While all of this isn't relevant, it's knowledge in my mind, and effects my view of programming sometimes. Now take a look at the following descriptions of the above byte codes from http://docs.python.org/lib/bytecodes.html LOAD_NAME namei Pushes the value associated with "co_names[namei]" onto the stack. LOAD_CONST consti Pushes "co_consts[consti]" onto the stack. CALL_FUNCTION argc Calls a function. The low byte of argc indicates the number of positional parameters, the high byte the number of keyword parameters. On the stack, the opcode finds the keyword parameters first. For each keyword argument, the value is on top of the key. Below the keyword parameters, the positional parameters are on the stack, with the right-most parameter on top. Below the parameters, the function object to call is on the stack. RETURN_VALUE Returns with TOS to the caller of the function. *TOS = Top Of Stack. The calling routine, puts (passes) the second set of arguments onto the stack before calling the function returned on the stack by the previous call. Which is exactly how I viewed it when I referred to coming full circle and the second sets of arguments are pass with a "stack(?)". Or it could be said equally the functions (objects) are passed with the stack. So both view are correct depending on the view point that is chosen. Cheers, Ron >HTH > >Regards, >Bengt Richter From scmarsh at hotmail.com Mon Apr 18 22:03:32 2005 From: scmarsh at hotmail.com (scott) Date: Tue, 19 Apr 2005 02:03:32 GMT Subject: EasyDialogs module problem with python 2.4.1 In-Reply-To: <42641956$0$21477$9b622d9e@news.freenet.de> References: <%fS8e.1066640$6l.831254@pd7tw2no> <42641956$0$21477$9b622d9e@news.freenet.de> Message-ID: Martin v. L?wis wrote: > Try pythonw. Thanks, that was it. One more question, when I use the EasyDialogs module to, for example, display a message in a dialog box, the dialog box doesn't appear directly. I need to switch to 'python' by clicking on it on the dock or alt-tabbing to 'python' in order to see the dialog box. ------------------ scott$ pythonw Python 2.4.1 (#2, Mar 31 2005, 00:05:10) [GCC 3.3 20030304 (Apple Computer, Inc. build 1666)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import EasyDialogs >>> EasyDialogs.Message('hi') (At this point the 'python' icon appears on the dock and starts jumping. The actual dialog box won't appear until I manually switch to python with alt-tab.) ------------------- This again is in contrast to using Pyshell, where the dialog box automagically appears without further user input upon entry of EasyDialogs.Message('hi'). Question: Can I get this Pyshell behavior using python from the terminal? From raghulj at gmail.com Thu Apr 7 00:12:35 2005 From: raghulj at gmail.com (Raghul) Date: 6 Apr 2005 21:12:35 -0700 Subject: logging as root using python script Message-ID: <1112847155.108154.180290@g14g2000cwa.googlegroups.com> Hi Is it possible to login as a root in linux using python script? What I need is when I execute a script it should login as root and execute my command and logout from root to my existing account. IS is possible? Thanx in advance. From rdm at rcblue.com Wed Apr 13 20:30:54 2005 From: rdm at rcblue.com (Dick Moores) Date: Wed, 13 Apr 2005 17:30:54 -0700 Subject: Compute pi to base 12 using Python? Message-ID: <6.2.1.2.2.20050413173043.070989e0@rcblue.com> Bengt Richter wrote at 14:52 4/13/2005: >import sys > >def main(): > k, a, b, a1, b1 = 2L, 4L, 1L, 12L, 4L > while 1: > p, q, k = k*k, 2L*k+1L, k+1L > a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1 > d, d1 = a/b, a1/b1 > while d == d1: > output(d) > a, a1 = 10L*(a%b), 10L*(a1%b1) > d, d1 = a/b, a1/b1 > >def output(d): > sys.stdout.write(`int(d)`) > sys.stdout.flush() > >main() > ># Reading/writing Python source often gives me the impression of ># reading/writing a poem! ># Layout, indentation, rythm, I like the look and feel! > ># What does this tiny program do? It is not a sonnet, even not a ># pi-sonnet, but it surely produces Pi! It sure does. When I ran it my jaw dropped. I had 7,947 CORRECT digits in 2 minutes 0 seconds (by my stopwatch)! Now on to base 12. Thanks! Dick Moores rdm at rcblue.com From fredrik at pythonware.com Tue Apr 26 05:24:57 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 26 Apr 2005 11:24:57 +0200 Subject: Order of elements in a dict References: Message-ID: Marcio Rosa da Silva wrote: > In dictionaries, unlinke lists, it doesn't matter the order one inserts the contents, elements are > stored using its own rules. > > Ex: > > >>> d = {3: 4, 1: 2} > >>> d > {1: 2, 3: 4} > > So, my question is: if I use keys() and values() it will give me the keys and values in the same > order? http://docs.python.org/lib/typesmapping.html "Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary's history of insertions and deletions. If items(), keys(), values(), iteritems(), iterkeys(), and itervalues() are called with no intervening modifications to the dictionary, the lists will directly correspond." From sdementen at hotmail.com Fri Apr 8 05:32:37 2005 From: sdementen at hotmail.com (Sébastien de Menten) Date: Fri, 08 Apr 2005 09:32:37 +0000 Subject: args attribute of Exception objects Message-ID: Hi, When I need to make sense of a python exception, I often need to parse the string exception in order to retrieve the data. Example: try: print foo except NameError, e: print e.args symbol = e.args[0][17:-16] ==> ("NameError: name 'foo' is not defined", ) or try: (4).foo except NameError, e: print e.args ==> ("'int' object has no attribute 'foo'",) Moreover, in the documentation about Exception, I read """Warning: Messages to exceptions are not part of the Python API. Their contents may change from one version of Python to the next without warning and should not be relied on by code which will run under multiple versions of the interpreter. """ So even args could not be relied upon ! Two questions: 1) did I miss something in dealing with exceptions ? 2) Could this be changed to .args more in line with: a) first example: e.args = ('foo', "NameError: name 'foo' is not defined") b) second example: e.args = (4, 'foo', "'int' object has no attribute 'foo'",) the message of the string can even be retrieved with str(e) so it is also redundant. BTW, the Warning in the doc enables to change this :-) To be backward compatible, the error message could also be the first element of the tuple. Seb ps: There may be problems (that I am not aware) with an exception keeping references to other objects From kay.schluehr at gmx.net Sat Apr 16 12:07:09 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 16 Apr 2005 09:07:09 -0700 Subject: pre-PEP: Suite-Based Keywords - syntax proposal References: Message-ID: <1113667629.375491.44380@l41g2000cwc.googlegroups.com> The idea is interesting but not unambigously realizable. Maybe one should introduce some extra syntax for disambiguation and thereby generalize the proposal. as : # list of definitions and assignments Proposed specifiers are dict, tuple, *, ** and func. - as dict: conversion into a dictionary Example: d = as dict: doc = "I'm the 'x' property." def fget(self): return self.__x We would get d = {"doc":"I'm the 'x' property.", "fget":fget} - as **: conversion into keyword-arguments. This comes close in spirit to the original proposal Example: x = property(): as **: doc = "I'm the 'x' property." def fget(self): return self.__x - as tuple: conversion into a tuple. Preserving order. Example: t = as tuple: doc = "I'm the 'x' property." def fget(self): return self.__x >>> t[1] - as *: conversion into an argument tuple. Preserving order. Example: x = property(): as *: def get_x(): return self.__x def set_x(value): self.__x = value del_x = None doc = "I'm the 'x' property." - as func(*args,**kw): Anoymus functions. Replacement for lambda. Support for arbirtray statements? Examples: p = as func(x,y): x+y p(1,2) i,j = 3,4 if (as func(x,y): x+y) (i,j) > 10: print True Ciao, Kay From jelleferinga at gmail.com Fri Apr 29 11:56:11 2005 From: jelleferinga at gmail.com (jelle) Date: 29 Apr 2005 08:56:11 -0700 Subject: how to pass an array to a VB array via COM In-Reply-To: References: Message-ID: <1114790171.348692.50240@l41g2000cwc.googlegroups.com> Hi Stefan, Thanks for your insightful and in-depth response! Wonderful to hear that a solution is in the works, that's absolutely wonderful news. If I can help you out beta-testing the PySafeArray implementation, I'd be delighted to do so. Thanks again, Jelle. From cesarbs at gmail.com Thu Apr 14 10:02:26 2005 From: cesarbs at gmail.com (=?ISO-8859-1?Q?C=E9sar_Leonardo_Blum_Silveira?=) Date: Thu, 14 Apr 2005 11:02:26 -0300 Subject: A little request about spam In-Reply-To: References: <1113416856.914310.63930@l41g2000cwc.googlegroups.com> <740c3aec05041405157cb90625@mail.gmail.com> <7ee3dcd80504140551385ce25e@mail.gmail.com> Message-ID: Yeah that is happening to me too! Almost all my python-list e-mails go to the Spam box. Maybe we should contact the gmail admins? On 4/14/05, mark hellewell wrote: > On 4/14/05, James wrote: > > Yes - it's been like that for the last month or so now and it's quite > > annoying, especially seeing as before it was working at near enough > > 100% accuracy. > > And I don't suppose there's much we can do about it? > > mark > -- > http://mail.python.org/mailman/listinfo/python-list > From richardblackwood at cloudthunder.com Sun Apr 24 00:02:55 2005 From: richardblackwood at cloudthunder.com (Richard Blackwood) Date: Sun, 24 Apr 2005 00:02:55 -0400 Subject: Variables In-Reply-To: References: <426B0283.40602@cloudthunder.com> <426b0d03_3@newspeer2.tds.net> <426B1300.6090802@cloudthunder.com> Message-ID: <426B1A6F.2060401@cloudthunder.com> Robert Kern wrote: > Richard Blackwood wrote: > >> Kent Johnson wrote: >> >>> Richard Blackwood wrote: >>> >>>>>> To All: >>>>>> >>>>>> Folks, I need your help. I have a friend who claims that if I >>>>>> write: >>>>>> >>>>>> foo = 5 >>>>>> >>>>>> then foo is NOT a variable, necessarily. >>>>> >>>>> >>>>> >>>>> >>>> Indeed, this language is math. My friend says that foo is a >>>> constant and necessarily not a variable. >>> >>> >>> >>> >>> Well, we mostly talk Python here, not math. In Python, if you say >>> foo = 5 >>> foo is a name bound to an immutable value. >>> >>> If I had written foo = raw_input(), he would >>> >>>> say that foo is a variable. >>> >>> >>> >>> >>> That's funny. foo is still a name bound to an immutable (string) >>> value. foo is no more or less variable than it was with foo = 5. >>> >>> Which is perfectly fine except that he >>> >>>> insists that since programming came from math, the concept of >>>> variable is necessarily the identical. This can not be true. For >>>> example, I may define foo as being a dictionary, but I can not do >>>> this within math because there is no concept of dictionaries within >>>> mathematics; yet foo is a variable, a name bound to a value which >>>> can change. >>> >>> >>> >>> >>> Sounds like you are having a stupid and meaningless argument with >>> your friend. What you call foo won't change what it is. He should >>> learn Python, then he would understand the true zen of foo. >> >> >> >> That is exactly how I feel about it. Foo is what it is. Variable, >> name bound to immutable value, etc., what we call it doesn't really >> change how I program, only how I communicate with other programmers >> (and mathematicians). Is the notion of variable not a fundamental >> concept in programming? Surely there must be an unambiguous >> definition I can relay to him. > > > Why should there be? Different programming languages have different > models. In C, a variable corresponds to a memory slot. In Python, it's > a just a name that can be bound to an object. > > If you must, http://en.wikipedia.org/wiki/Variable > Fantastic, wikipedia deals precisely with the difference between variables in mathematics versus programming. However, he would never trust a definition from such an "unreputable" source. If you have any other sources I might direct him to...he maintains that the notion of foo being a variable where it's value is known (versus unknown) is illogical. From bokr at oz.net Sat Apr 16 23:24:50 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 17 Apr 2005 03:24:50 GMT Subject: pre-PEP: Suite-Based Keywords - syntax proposal References: <1113667629.375491.44380@l41g2000cwc.googlegroups.com> <42618007.117284766@news.oz.net> Message-ID: <4261d351.138606786@news.oz.net> On Sun, 17 Apr 2005 01:10:47 GMT, bokr at oz.net (Bengt Richter) wrote: [...] > >The "::" expression I'm proposing generalizes capturing suite bindings into an ordered sequence of (key,value) >tuples, like an ordered vars().items() limited to the bindings produced in the suite following "::" >Thus > items = :: > x = 1 > y = [1,2] > def foo():pass > > print items => (('x', 1), ('y', [1, 2]), ('foo', )) > Update, sorry. Galloping evolution here ;-) The '::' unary suite operator should return an ordered dict subtype representing the bindings, so print items => {'x':1, 'y':[1, 2], 'foo':} instead. This allows cleaner suite-based keyword calling, since no dict(::) is necessary, so def foo(**kw): print kw followed by foo(**:: x = 1 y = [1,2] def foo():pass) will print the same. Since :: is an expression, it can go anywhere an expression can go. I like orthogonality ;-) Methods allow (with order preserved from binding in suite) (:: x=1; y=2).keys() # => ['x', 'y'] and (:: x=1; y=2).values() # => [1, 2] and (:: x=1; y=2).items() # => [('x', 1), ('y', 2)] note that :: is ;-greedy in one-line suites, so :: x=1; y=2 is not (:: x=1); y=2 Regards, Bengt Richter From bogus@does.not.exist.com Wed Apr 6 10:45:02 2005 From: bogus@does.not.exist.com () Date: Wed, 06 Apr 2005 14:45:02 -0000 Subject: (no subject) Message-ID: #! rnews 4875 Newsgroups: comp.lang.python Path: news.xs4all.nl!newsspool.news.xs4all.nl!transit.news.xs4all.nl!news-spur1.maxwell.syr.edu!news.maxwell.syr.edu!nntp.abs.net!attws2!ip.att.net!NetNews1!xyzzy!nntp From: Harry George Subject: Re: Best editor? X-Nntp-Posting-Host: cola2.ca.boeing.com Content-Type: text/plain; charset=us-ascii Message-ID: User-Agent: Gnus/5.09 (Gnus v5.9.0) Emacs/21.3 Lines: 106 Sender: hgg9140 at cola2.ca.boeing.com Organization: The Boeing Company References: <1112725379.514651.66540 at l41g2000cwc.googlegroups.com> Mime-Version: 1.0 Date: Wed, 6 Apr 2005 14:22:57 GMT Xref: news.xs4all.nl comp.lang.python:371122 "ChinStrap" writes: > When not using the interactive prompt, what are you using? I keep > hearing everyone say Emacs, but I can't understand it at all. I keep > trying to learn and understand why so many seem to like it because I > can't understand customization even without going through a hundred > menus that might contain the thing I am looking for (or I could go > learn another language just to customize!). > > Personally I like SciTE, it has everything I think a midweight editor > should: code folding, proper python support, nice colors out of the > box, hotkey access to compile (I'm sure emacs does this, but I couldn't > figure out for the life of me how), etc. > > Opinions on what the best is? Or reading I could get to maybe sway me > to Emacs (which has the major advantage of being on everyone's system). > The key (as others have said) is to know your editor and be effective with it. As long as it can handle ASCII, does autoindent, and knows tab-is-4-chars, then it is a viable choice. Since you asked specifically about emacs, and whether or not it is worthwhile... I've used emacs for 15 years, and am still learning useful new tricks at a rate of about one per 6 months. But I've also found that the essentials can be taught in a 2 hour session and mastered in about 2 weeks of use. I've taught dozens of people using this "Essential Emacs" approach. We find that emacs is for people who will be doing serious editing all day long (e.g., programmers). I like that comment from another poster: "Emacs is a good place to live, but I wouldn't want to visit there." For people who will just be editing an occassional file (and no python code), we recommend notepad or nedit. Now then, how do we use emacs? 1. Proper setup is essential. Assuming you have python-mode.el and .elc in emacs's program-modes dir, then your .emacs needs: ;---python--------------------------- (load "python-mode") (setq auto-mode-alist (cons '("\\.py$" . python-mode) auto-mode-alist)) (setq interpreter-mode-alist (cons '("python" . python-mode) interpreter-mode-alist)) (autoload 'python-mode "python-mode" "Python editing mode." t) (add-hook 'python-mode-hook 'turn-on-font-lock) (setq python-mode-hook 'python-initialise) (defun python-initialise () (interactive) (setq default-tab-width 4) (setq indent-tabs-mode nil) ) 2. I almost never use the interactive prompt. There are people here who do, but as soon as the script is more than a couple lines long, it takes longer to reenter the code (even copy-and-paste) than to edit-save-run a dummy batch script. When I'm doing Extreme Programming with such people, I insist on using a stopwatch and checking which approach is more efficient -- they usually come over to my approach. 3. I run emacs with split windows: a) Edit the working code b) Edit the unittest code c) Run a shell script, where I (re)run the "go_test" script by doing alt-p ret In another frame (same emacs process, different frame) I keep the oracle (known good) and test outputs in split windows, and maybe do ediff-buffers on them if the deltas are not obvious. For each module under consideration (view or edit), I use a separate emacs process in a similar manner. In normal work, that means 1-4 emacs processes running, each with its own shell and own test cycles. 4. Elsewhere I'm running emacs rmail all day, and run emacs gnus several times a day (like now). 5. When I do Extreme Programming, the other author(s) tend to be using emacs, vim, or nedit. We don't let people use notepad for python becuause it doesn't know proper formatting. IDE's tend to want to own the whole show, which makes cross-tool Extreme Programming a pain. As long as the other programmers have set their editors for auto-indention and tab-is-4-chars, then we get along fine. [I do notice a sizeable delay when vim people search for the appropriate shell windows, instead of having them in a (joined-at-the-hip) split window. This has more to do with bookkeeping than with editors per se, but it is a data point.] 6. On IDE's and code-completion: If you are going to be typing the same thing over and over, why not use a function, or maybe code generation? -- harry.g.george at boeing.com 6-6M21 BCA CompArch Design Engineering Phone: (425) 294-4718 From mkashkin at gmail.com Thu Apr 28 17:02:27 2005 From: mkashkin at gmail.com (Mikhail 'Xen' Kashkin) Date: 28 Apr 2005 14:02:27 -0700 Subject: goto statement References: <20050420092359.81900.qmail@web8409.mail.in.yahoo.com> <42664190.6010507@i.com.ua> <87vf6hlkix.fsf@wilson.rwth-aachen.de> Message-ID: <1114722147.505877.286950@o13g2000cwo.googlegroups.com> If you use ssh, then you must to learn 'scp'. Or buy books about programming ;) From donn at drizzle.com Sat Apr 30 12:18:49 2005 From: donn at drizzle.com (Donn Cave) Date: Sat, 30 Apr 2005 16:18:49 -0000 Subject: mbx repair script: Python vs perl References: None Message-ID: <1114877929.236697@yasure> Quoth "David Isaac" : | I'm looking for the Python equivalent of the perl script and module | described at | http://comments.gmane.org/gmane.mail.imap.uw.c-client/707 | | Any hope? Sure, should be doable, if for some reason you can't just use that. I personally wouldn't do it exactly that way, rather I would just read the file directly. At first you said you were only interested in fixing the header. This one operates on the rest of the file, and I guess I will assume that's what you really want. MBX structure is just a one line message header before each message, with a message size value among other things. Readers of this format will add that size value to the current file offset and expect another header line at that point. When the data there isn't a valid header line, they die. One does not need the c-client library to do this, but more to the point it isn't what you want to do, with a damaged file. Just read the file from one end to the other and find everything that looks like a header line, and then rewrite the file with adjusted header lines required so that - they are in ascending order by ID number - they have correct sizes. Donn Cave, donn at drizzle.com From tim at tt1lock.org Sat Apr 9 11:57:15 2005 From: tim at tt1lock.org (Tim Tyler) Date: Sat, 9 Apr 2005 15:57:15 GMT Subject: Are circular dependencies possible in Python? Message-ID: Like C, Python seems to insist I declare functions before calling them - rather than, say, scanning to the end of the current script when it can't immediately find what function I'm referring to. C lets you predeclare functions to allow for the existence of functions with circular dependencies. Does Python allow you to do something similar? If not how do you create functions with circular dependencies in Python - where function A could call function B; and function B could call function A - or is that not possible? -- __________ |im |yler http://timtyler.org/ tim at tt1lock.org Remove lock to reply. From irmen.NOSPAM at xs4all.nl Sun Apr 24 10:08:08 2005 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Sun, 24 Apr 2005 16:08:08 +0200 Subject: thread lock object. In-Reply-To: <1114347545.147038.265210@g14g2000cwa.googlegroups.com> References: <1114347545.147038.265210@g14g2000cwa.googlegroups.com> Message-ID: <426ba849$0$166$e4fe514c@news.xs4all.nl> ajikoe at gmail.com wrote: > Hello, > > I have multi thread program running together and each will increment > int i. > > How can we make only one thread at a time be able to access and > increment i ? > > Thanks in advance, > > Sincerely Yours, > pujo > Use a synchronization primitive such as a lock (threading.Lock, threading.RLock) But for simply incrementing a number (i+=1) this is not needed because that operation cannot be interrupted by another thread, as far as I know. --Irmen From kirk at jobsluder.net Sun Apr 24 14:05:30 2005 From: kirk at jobsluder.net (Kirk Job Sluder) Date: Sun, 24 Apr 2005 18:05:30 GMT Subject: Variables References: <426B0283.40602@cloudthunder.com> <426b255d.375304108@news.oz.net> Message-ID: <878y389hi1.fsf@debian.kirkjobsluder.is-a-geek.net> Richard Blackwood writes: > Bengt Richter wrote: > > >Tell him in Python foo is a member of one set and 5 is a member of another, > >and foo = 5 expresses the step of putting them into correspondence > >to define a mapping, not declaring them equal. > > > Could I honestly argue this to him? From what basis do I argue that it > is not an equation? In any event, he would likely (passionately) > disagree considering his notion that programming is an off-shoot of > math and thus at the fundamental level has identical concepts and > rules. Believe it or not, he used to be a programmer. Back in the day > (while I was getting my PhD in philosophy), he was a employed > programmer using Cobol, Fortran, and other languages like that. Did > his seemingly peculiar definition of variable exist at that time? Because, this is shorthand that operates at quite a bit of a higher level than the mathematical roots of a programming language. Here is a peek of what is going in when foo = 5 is evaluated. create an anonymous int object set the value of that object to 5 create a symbol foo bind the location the anonymous object to symbol foo > > >Even in math notation, ISTM important to distinguish between > >a finger and what it may for the moment be pointing at. > > > >Regards, > >Bengt Richter > > > -- Kirk Job-Sluder "The square-jawed homunculi of Tommy Hilfinger ads make every day an existential holocaust." --Scary Go Round From mauriceling at acm.org Fri Apr 29 20:17:21 2005 From: mauriceling at acm.org (Maurice LING) Date: Sat, 30 Apr 2005 10:17:21 +1000 Subject: New Python website References: <1114735502.510591.6360@f14g2000cwb.googlegroups.com> <42719DFF.5080504@acm.org> <1114781419.288939.30840@z14g2000cwz.googlegroups.com> Message-ID: <4272CE91.5080908@acm.org> lpe wrote: > Hi maurice > thanks for your interest, that surely looks interesting (and promising) > I had no experience with any of the packages you mentioned, but it may > well be usefull. > Please email me with more details of what you had in mind. > Hi, I've just read PEP 262 last night and finds that it does more or less describes what I have in mind. However, I am not sure if there is every need for such a descriptive database file or something slimmer, like Fink's .info files will suffice. An example of Fink's .info file is: ==================================================== Package: g77 Version: 3.4.1 Revision: 1 BuildDependsOnly: true Source: mirror:gnu:gcc/gcc-%v/gcc-%v.tar.bz2 Source-MD5: 31b459062499f9f68d451db9cbf3205c NoSourceDirectory: True ConfigureParams: --enable-languages=f77 --infodir='${prefix}/share/info' --libexecdir='${prefix}/lib' --disable-shared #BuildDepends: dejagnu PatchScript: << #!/bin/sh cd gcc-%v/gcc mv Makefile.in Makefile.in.orig sed 's|$(ALL_CPPFLAGS) $(INCLUDES)|$(INCLUDES) $(ALL_CPPFLAGS)|g' < Makefile.in.orig > Makefile.in << CompileScript: << #!/bin/sh mkdir darwin cd darwin ../gcc-%v/configure %c make CFLAGS='-O' LIBCFLAGS='-g -O2' LIBCXXFLAGS='-g -O2 -fno-implicit-templates' profiledbootstrap #cd gcc; make check-g77 << InstallScript: << #!/bin/sh cd darwin make install prefix=%i cd %i/bin /bin/rm -f gcc gccbug cpp gcov powerpc-apple* ln -s %p/bin/g77 f77 darwinvers=`/usr/bin/uname -v | cut -f1 -d":" | awk '{print $4}'` gccvers=`%i/bin/g77 -dumpversion | head -1 | cut -f4 -d" "` ln -s %p/lib/gcc/powerpc-apple-darwin${darwinvers}/${gccvers}/include/g2c.h %i/include/g2c.h /bin/rm -rf %i/share/locale %i/man /bin/rm -f %i/lib/charset.alias /bin/rm -f %i/share/info/gcc* %i/share/info/cpp* /bin/mv -f %i/lib/libiberty.a %i/lib/libiberty-g77.a << License: GPL DocFiles: gcc-%v/gcc/f/ChangeLog gcc-%v/COPYING gcc-%v/COPYING.LIB Description: GNU Fortran compiler DescDetail: << g77 consists of several components: 1) The g77 command itself. 2) The libg2c run-time library. This library contains the machine code needed to support capabilities of the Fortran language that are not directly provided by the machine code generated by the g77 compilation phase. 3) The compiler itself, internally named f771. f771 does not generate machine code directly -- it generates assembly code, leaving the conversion to actual machine code to an assembler, usually named as. g77 supports some fortran90 features, like automatic arrays, free source form, and DO WHILE. << DescPort: << Installs g77 from the FSF gcc distribution. This version does not install in /usr. It contains it's own cc1 and libgcc.a installed in %p. libiberty.a moved to libiberty-g77.a to avoid conflict with ddd. << DescUsage: << If you get unresolved symbol '_saveFP', add -lcc_dynamic when linking. Does not support -framework argument, to link frameworks use -Wl flag (for example, to link vecLib use "-Wl,-framework -Wl,vecLib"). No man page, use "info g77". << Homepage: http://gcc.gnu.org/onlinedocs/g77/ Maintainer: Jeffrey Whitaker ================================================================================ Implementing the API specified in PEP 262 is desirable. What I am thinking is this, 1. when user specify a package to install, the package's .info file will be looked up in 'pkginfo' directory (in PEP 262, it is the INSTALLDB directory that holds all these .info files). 2. to the system, only 3 things are crucial: where to get the package? what packages the package needs? how to install? These 3 things are the real critical parts of .info file, the rest are information and metadata. 3. from the dependencies, the system now creates a tree of dependencies. Can all dependencies be satisfied, i.e. are there any required packages that are not in standard library and there is no .info file for? 4. dependencies are satisfied (install the packages) from terminal leaf nodes on the dependency tree to the root node (which is the one the user wants to install) 5. appropriate entries are made in appropriate files (i.e. pkg-install.log) to signify which packages are installed. 6. satisfy the files needed for API requirements of PEP 262. Please tell me what you think... Cheers Maurice From bokr at oz.net Sun Apr 10 08:47:02 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 10 Apr 2005 12:47:02 GMT Subject: Puzzling OO design problem References: <1113003772.020556.69550@l41g2000cwc.googlegroups.com> <1113010854.638038.173460@g14g2000cwa.googlegroups.com> <1113018015.535852.53250@z14g2000cwz.googlegroups.com> <1113043759.765568.9920@o13g2000cwo.googlegroups.com> Message-ID: <425919b6.16894062@news.oz.net> On 9 Apr 2005 03:49:19 -0700, "George Sakkis" wrote: >"Michael Spencer" wrote: >> >> George, >> >> since you explicit allowed metaprogramming hacks :-), how about >something like >> this (not tested beyond what you see): >> >> [snipped] >> > >Nice try, but ideally all boilerplate classes would rather be avoided >(at least being written explicitly). Also, it is not obvious in your >solution why and which placeholder classes have to be written (like >World2.Movable) and which do not. By the way, my current working >solution involves copying and pasting verbatim these classes :-) Below >is an abstracted example; note that the 'declaration string' of each >original class is exactly the same across all different versions after >the first (e.g. "class B(PreviousNamespace.B, A)"). > > >#====================================================== ># version_1.py > >class Namespace: > class A(object): > def foo(self): return "version_1.foo()" > class B(A): > def bar(self): return "version_1.bar()" > class C(B): > def zen(self): return "version_1.zen()" >#====================================================== ># version_2.py > >from version_1 import Namespace as PreviousNamespace >class Namespace(PreviousNamespace): > class A(PreviousNamespace.A): > def foo(self): return "version_2.foo()" > class B(PreviousNamespace.B, A): > pass > class C(PreviousNamespace.C, B): > pass >#====================================================== ># version_3.py > >from version_2 import Namespace as PreviousNamespace >class Namespace(PreviousNamespace): > class A(PreviousNamespace.A): > pass > class B(PreviousNamespace.B, A): > def bar(self): return "version_3.bar()" > class C(PreviousNamespace.C, B): > pass > >#====================================================== ># test.py ># command: python test.py <#version> > >def NamespaceFactory(version): > return __import__("version_%d" % version).Namespace > >print NamespaceFactory(2).B().foo() # "version_2.foo()" >print NamespaceFactory(3).C().bar() # "version_3.bar()" > >import sys, inspect >namespace = NamespaceFactory(int(sys.argv[1])) ># print the __mro__ of each 'inner' class >for name,cls in inspect.getmembers(namespace, > inspect.isclass): > print cls > for ancestor in cls.__mro__: > print "\t", ancestor > >#====================================================== > See if this does what you want: (Note that vermeta.py preliminarily writes out the three version_?.py files, so you can just go to a temp directory and run python24 vermeta.py) It makes the version files look a little more cluttered with the open(..).write('''\ ... ''') wrapping. E.g., 2 & 3 are just ----< version_2.py >----------- from version_1 import Namespace as PreviousNamespace class Namespace(PreviousNamespace): __metaclass__ = vars(PreviousNamespace)['__metaclass__'] class A: def foo(self): return "version_2.foo()" ------------------------------- and ----< version_3.py >----------- from version_2 import Namespace as PreviousNamespace class Namespace(PreviousNamespace): __metaclass__ = vars(PreviousNamespace)['__metaclass__'] class B: def bar(self): return "version_3.bar()" ------------------------------- And you only have to change one digit in the 3-line boilerplate and your class definitions don't have to specify inheritance, but it could test for type classobj (classic class) and only redefine if so ;-) There are some limitations I think (;-) but the idea is you just have to specify three lines of boilerplate for a new version, and then just the classes and methods you are interested in overriding in the new version, and you don't have to specify the class inheritance in the new versions, as the lazystyle metaclass function takes care of that. I hope ;-) Version_1 has to be hand made, but after that, see what you think. ----< vermeta.py >--------------------------------------------------------------- #====================================================== # version_1.py open('version_1.py','w').write('''\ NAMESPACE_CLASSNAMES = ['A', 'B', 'C'] def metadeco(nsname, nsbases, nsdict): # print '--- metadeco ---', nsbases, nsdict['__module__'], __name__ # print 'nsname = %r\\nnsbases = %r\\nnsdict = %s' %( # nsname, nsbases, ',\\n '.join(str(nsdict).split(', '))) if nsdict['__module__'] != __name__: # exclude this first-version module # print '--- doing meta stuff for namespace of module %s ---'% nsdict['__module__'] for i, cname in enumerate(NAMESPACE_CLASSNAMES): cbases = (vars(nsbases[0])[cname],) + (i and (nsdict[NAMESPACE_CLASSNAMES[i-1]],) or ()) if object not in cbases: cbases += (object,) if cname in nsdict: cdict = nsdict[cname].__dict__.copy() #cdict['__module__'] = __name__ else: cdict = {'__doc__': '(Generated by version_1.metadeco)'} cdict['__module__'] = nsdict['__module__'] nsdict[cname] = type(cname, cbases, cdict) return type(nsname, nsbases, nsdict) class Namespace(object): __metaclass__ = metadeco class A(object): def foo(self): return "version_1.foo()" class B(A): def bar(self): return "version_1.bar()" class C(B): def zen(self): return "version_1.zen()" ''') #====================================================== # version_2.py open('version_2.py','w').write('''\ from version_1 import Namespace as PreviousNamespace class Namespace(PreviousNamespace): __metaclass__ = vars(PreviousNamespace)['__metaclass__'] class A: def foo(self): return "version_2.foo()" ''') #====================================================== # version_3.py open('version_3.py','w').write('''\ from version_2 import Namespace as PreviousNamespace class Namespace(PreviousNamespace): __metaclass__ = vars(PreviousNamespace)['__metaclass__'] class B: def bar(self): return "version_3.bar()" ''') #====================================================== # test.py # command: python test.py <#version> def NamespaceFactory(version): return __import__("version_%d" % version).Namespace print NamespaceFactory(2).B().foo() # "version_2.foo()" print NamespaceFactory(3).C().bar() # "version_3.bar()" import sys, inspect namespace = NamespaceFactory(int(sys.argv[1])) # print the __mro__ of each 'inner' class for name,cls in inspect.getmembers(namespace, inspect.isclass): #for name, cls in (t for t in namespace.__dict__.items() if isinstance(t[1], type)): print cls for ancestor in cls.__mro__: print "\t", ancestor #====================================================== --------------------------------------------------------------------------------- Run: [ 5:33] C:\pywk\clp\sakkis\meta>py24 vermeta.py 3 version_2.foo() version_3.bar() Regards, Bengt Richter From michele.simionato at gmail.com Thu Apr 28 09:29:25 2005 From: michele.simionato at gmail.com (Michele Simionato) Date: 28 Apr 2005 06:29:25 -0700 Subject: (PHP or Python) Developing something like www.tribe.net In-Reply-To: <1114686654.011511.306570@l41g2000cwc.googlegroups.com> References: <1113835147.364885.304290@l41g2000cwc.googlegroups.com> <1114503432.227799.52670@o13g2000cwo.googlegroups.com> <1114587592.260950.181990@l41g2000cwc.googlegroups.com> <1114587846.011299.125420@g14g2000cwa.googlegroups.com> <1114663336.926935.97910@f14g2000cwb.googlegroups.com> <1114665613.879362.75100@l41g2000cwc.googlegroups.com> <1114686654.011511.306570@l41g2000cwc.googlegroups.com> Message-ID: <1114694965.800390.101160@o13g2000cwo.googlegroups.com> Well, let me specialize my sentence > CherryPy and Quixote are for programming in the small in > CherryPy and Quixote are good for programming in the small meaning that these frameworks help you when programming in the small. This statement does NOT imply that they get in your way when you program in the large. I just lack the experience in programming in the large with CherryPy and/or Quixote. Also, let me specify what I mean by "programming in the large": if a single person can grasp the application, and the application can be implemented by a single team, then you are programming in the small. You are programming in the large only when you have many independent team of developers and you have coordination problems. In this situation a component architecture is supposed to help (and maybe it does, I lack the field experience to give an opinion), whereas when working in the small a component architecture can just get in your way. It is easy to evaluate a framework in the small: it is enough to ask to self the question "how much time did it take to me to write my first Web site in that framework starting from zero?". OTOH, to evaluate a framework for programming in the large takes years of experience and practice, and I will not hazard any opinion ;) Still, I believe it is possible to have a frameworks which is scalable both in the small and in the large. Look for instance at the programming language spectrum: Java was intended to program in the large and it is pretty bad when programming in the small; Perl, on the other hand, was meant to program in the small and does not scale at all in the large. However, Python works equally well both in the large and in the small. So, I think there is no contraddiction between large and small, in theory. But in practice there is, so I use Zope at work and Quixote at home ;) Michele Simionato From gandalf at geochemsource.com Thu Apr 7 15:11:53 2005 From: gandalf at geochemsource.com (Laszlo Zsolt Nagy) Date: Thu, 07 Apr 2005 21:11:53 +0200 Subject: import statement - package visibility problem In-Reply-To: <8cf2994e.0504071024.69de669f@posting.google.com> References: <8cf2994e.0504071024.69de669f@posting.google.com> Message-ID: <425585F9.8050806@geochemsource.com> Paul Clinch wrote: >> >> >I get: > > >>>>import Lib >>>> >>>> >Traceback (most recent call last): > File "", line 1, in ? >ImportError: No module named Lib > >I guess there's a Lib/__init__.py. > > You are totally right. I was trying to create an example but Python found something on my PYTHONPATH. Sorry for the confusion, I sent a bad example. Well, could not be so bad because you understood the point. I'll try to create a new good example today and make it available. >But onto the point you're making. I think its possibly a mis-viewing >of the package idea in Python. A package creates a name space. If you >create Lib/Server/Db with all the __init__.py files, its because you >want to import Lib.Server.Db, rather than a way of organising your >source files. > > I agree. Sometimes I need to import Lib.Server.Db but sometimes I need to import Lib.Server.Db.Adapters.PostgreSQLConnection. Importing from a not package related source code is not a problem, really. My problem is about importing inside a package. Lib/Server/Db/__init__.py __can__ import Lib/Server/Db/Adapters usign relative paths, but Lib/Server/Db/Adapters/PostgreSQLConnection.py __cannot__ import from Lib/Server/Db using relative paths Of course I can do the latter import using absolute paths but that is something I would like to avoid. In other words: it is possible to import using relative lib paths only in one direction. Why is that? Why can't I import something "from the containing package"? Why I would like to do that? Please see my reasons in my original e-mail. If you think that I want a programatically bad thing, please tell me what is the right way to do it. I'm sorry if I look demanding. I'm open to any suggestions. I can hardly find a design problem in the language itself, I believe these problems are just mine. I have a bug in my mind. :-) Please help me to catch it. >If you want to have a single name space, and keep the nested >arrangement of directories, you can add python code in Lib/__init__.py >to traverse directories and import packages that you find. > Ok, in the example, you will see that this is not possible. I'm going to upload it soon. >Or you can define any rules for mapping files and directories to the name space >you desire. > > How to do that? By hacking? -- _________________________________________________________________ Laszlo Nagy web: http://designasign.biz IT Consultant mail: gandalf at geochemsource.com Python forever! From jaywgraves at gmail.com Thu Apr 21 11:36:09 2005 From: jaywgraves at gmail.com (jay graves) Date: 21 Apr 2005 08:36:09 -0700 Subject: recording data between [ and ] References: Message-ID: <1114097769.446445.70210@g14g2000cwa.googlegroups.com> I haven't used either of these tools but they might help a little. http://lfw.org/python/rxb15.py http://pyparsing.sourceforge.net/ If you want to help building traditional regex patterns, I find programs like these to be invaluable. Tools/scripts/redemo.py in the python standard lib. http://kodos.sourceforge.net/home.html http://weitz.de/regex-coach/ HTH, jay graves From kay.schluehr at gmx.net Mon Apr 25 18:50:28 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 25 Apr 2005 15:50:28 -0700 Subject: Injecting code into a function In-Reply-To: <1114457804.600476.324860@o13g2000cwo.googlegroups.com> References: <1114425158.092697.99030@o13g2000cwo.googlegroups.com> <1114451147.737426.207980@z14g2000cwz.googlegroups.com> <1114457804.600476.324860@o13g2000cwo.googlegroups.com> Message-ID: <1114469428.476290.315110@f14g2000cwb.googlegroups.com> George Sakkis wrote: > Thanks, that's the closest to what I wanted. A minor point I didn't > quite get from the documentation is how to set a local trace instead of > a global (sys) trace. You never do. "Local" in this context only means that those local trace functions are called inside the one global trace-function and return the global trace function again. In Lonnies example there are no local-trace functions at all. > Also, there's no sys.gettrace() to return the > current tracer; is there a way around this ? The default tracer is None i.e. no debugging. The programmer has to control his tracer which might not be to hard: class Analyzer: def trace_returns(self, frame, event, arg): if event == 'return': self.func_locals = frame.f_locals return self.trace_returns def analyzeLocals(self, func,*args,**kw): sys.settrace(self.trace_returns) func(*args,**kw) sys.settrace(None) Ciao, Kay From nikolai.kirsebom.NOJUNK at siemens.no Mon Apr 4 10:58:40 2005 From: nikolai.kirsebom.NOJUNK at siemens.no (Nikolai Kirsebom) Date: Mon, 04 Apr 2005 16:58:40 +0200 Subject: adodbapi return value References: Message-ID: Found out what's wrong. The "Output Parameter Availablity" property of the connection has the value DBPROPVAL_OA_ATROWRELEASE. By closing the record set (reading out the result set first) the output parameters were correct. Made the modification directly in the executeHelper method of the Cursor object. Changed at the end of the method; if isStoredProcedureCall and parameters != None: return self._returnADOCommandParameters(self.cmd) to if isStoredProcedureCall and parameters != None: x = self.fetchall() rs.Close() return self._returnADOCommandParameters(self.cmd), x Guess this is not the right way. Any comments appreciated. Nikolai Kirsebom From peter at engcorp.com Fri Apr 1 16:14:53 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 01 Apr 2005 16:14:53 -0500 Subject: Who said that? (was Re: string goes away) In-Reply-To: References: <20050401113753.2hhq78s8z7nocwoo@mcherm.com> Message-ID: Ivan Van Laningham wrote: > Tim Peters sayeth, "Premature Optimization is the Root of All Evil." > And he is not kidding. And just to forestall another long thread about who actually said that originally, it was really Mark Twain, quoting Churchill. Tim just added a . -Peter From beliavsky at aol.com Mon Apr 4 14:40:31 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 4 Apr 2005 11:40:31 -0700 Subject: Symbol Referencing Error in Fortran 90 References: <1112635719.898929.108060@o13g2000cwo.googlegroups.com> Message-ID: <1112640031.432645.32970@l41g2000cwc.googlegroups.com> This message was also posted and replied to on comp.lang.fortran -- I think it's presence here is an accident. From tzot at sil-tec.gr Thu Apr 14 11:43:55 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Thu, 14 Apr 2005 18:43:55 +0300 Subject: Supercomputer and encryption and compression @ rate of 96% References: <1113470846.970773.4780@g14g2000cwa.googlegroups.com><425e47a9$0$26352$db0fefd9@news.zen.co.uk> Message-ID: On Thu, 14 Apr 2005 16:35:59 +0200, rumours say that "Fredrik Lundh" might have written: >> [0] -- btw, in your code, Fredrik: >> """file = open(keycode + ".out", "wb")""".replace("keycode", "filename") > >if you do that, decompression won't work. How obvious, now that you mention it... :) -- TZOTZIOY, I speak England very best. "Be strict when sending and tolerant when receiving." (from RFC1958) I really should keep that in mind when talking with people, actually... From vinay_sajip at yahoo.co.uk Fri Apr 29 13:39:11 2005 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Fri, 29 Apr 2005 17:39:11 +0000 (UTC) Subject: logging problems References: Message-ID: Simon Dahlbacka gmail.com> writes: This is a known problem, and a patch was put into CVS. I would suggest that you either check out the version from CVS, or move the "import traceback" to the top of the module. The problem is caused by a threading deadlock which occurs when an importer tries to log a message. Regards, Vinay Sajip From tiissa at nonfree.fr Tue Apr 26 16:19:12 2005 From: tiissa at nonfree.fr (tiissa) Date: Tue, 26 Apr 2005 22:19:12 +0200 Subject: Getting the sender widget's name in function (Tkinter) In-Reply-To: <1114545565.116766.157000@f14g2000cwb.googlegroups.com> References: <1114545565.116766.157000@f14g2000cwb.googlegroups.com> Message-ID: <426ea23e$0$12335$626a14ce@news.free.fr> Harlin Seritt wrote: > I have the following script. Two widgets call the same function. How > can I tell inside of the called function which button called it?: As far as I know you can't (but I can be proven wrong). You may try to define a class to solve this (not tested): #### class say_hello: def __init__(self, text): self.text=text def __call__(self) print 'Hello!' print self.text root = Tk() button1 = Button(root, text='Button 1', command=say_hello('Button 1')) button1.pack() button2 = Button(root, text='Button 2', command=say_hello('Button 2')) button2.pack() root.mainloop() #### From bill.mill at gmail.com Mon Apr 25 14:10:28 2005 From: bill.mill at gmail.com (Bill Mill) Date: Mon, 25 Apr 2005 14:10:28 -0400 Subject: What is situation with threads in Python In-Reply-To: <426D2D11.3020905@jpl.nasa.gov> References: <426D2D11.3020905@jpl.nasa.gov> Message-ID: <797fe3d4050425111074475da6@mail.gmail.com> On 4/25/05, Leonard J. Reder wrote: > Hello Mark, > > I took your three day course here at JPL and recall that you said > something was wrong with the implementation of threads within Python > but I cannot recall what. So what is wrong with threads in Python? I'm going to guess that he meant the Global Interpreter Lock is what's wrong with Python threads. You can read about it in the docs at http://docs.python.org/api/threads.html and get some good analysis from Ian Bicking (with some excellent, and some not so excellent, comments): http://blog.ianbicking.org/gil-of-doom.html . > > The other part of this question is, if there is something wrong with > the threads in Python has anyone wrapped the Posix threads C api using > swig to fix this problem? I work on Solaris/Linux systems and this > seems like a quick fix - maybe. > Nope, since the interpreter is not entirely thread-safe, I don't believe you can wrap pthreads. > Enjoyed the class a great deal. I am also sending this to the news > group in hopes of various interesting replies. Maybe there is a web > article on this topic already that someone could send the URL. > > Thanks for all replies, > > Len > -- > ____________________________________________________ > Leonard J. Reder > Jet Propulsion Laboratory > Interferometry Systems and Technology Section 383 > Email: reder at huey.jpl.nasa.gov > Phone (Voice): 818-354-3639 > Phone (FAX): 818-354-4357 > Mail Address: > Mail Stop: 171-113 > 4800 Oak Grove Dr. > Pasadena, CA. 91109 > --------------------------------------------------- > -- > http://mail.python.org/mailman/listinfo/python-list > From danb_83 at yahoo.com Thu Apr 21 14:47:01 2005 From: danb_83 at yahoo.com (Dan Bishop) Date: 21 Apr 2005 11:47:01 -0700 Subject: Why Python does *SLICING* the way it does?? References: <1113976729.450677.261130@o13g2000cwo.googlegroups.com> <_Lm9e.23143$Xm3.17864@trndny01> <1114003997.778676.144950@z14g2000cwz.googlegroups.com> Message-ID: <1114109221.149346.64850@z14g2000cwz.googlegroups.com> Antoon Pardon wrote: > Op 2005-04-21, Steve Holden schreef : > > beliavsky at aol.com wrote: ... > >> Along the same lines, I think the REQUIREMENT that x[0] rather than > >> x[1] be the first element of list x is a mistake. At least the > >> programmer should have a choice, as in Fortran or VBA. In C starting at > >> 0 may be justified because of the connection between array subscripting > >> and pointer arithmetic, but Python is a higher-level language where > >> such considerations are less relevant. > >> > > But Pythonicity required that there should be one obvious way to do > > something. How obvious is having two ways? > > How obvious is that lists can be any length? Do you consider it > an unbounded number of ways, that lists can be any length? > > Like users have a choice in how long they make a list, they > should have a choice where the indexes start. (And that > shouldn't be limited to 0 and 1). Suppose you could. Then what should ([3, 1, 4] indexbase 0) + ([1, 5, 9] indexbase 4) equal? > That you are forced to use zero-based structures, while the > problem space you are working on uses one-based structures > is a far bigger stumbling block where you continually have > to be aware that the indexes in your program are one off > from the indexes the problem is expressed in. Name a problem space that inherently requires arrays to be 1-based rather than 0-based. From deetsNOSPAM at web.de Tue Apr 12 07:54:07 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Tue, 12 Apr 2005 13:54:07 +0200 Subject: [perl-python] Python documentation moronicities (continued) References: <1113301533.054410.203710@z14g2000cwz.googlegroups.com> Message-ID: > Can we paypal you a hundred dollars to leave us alone? I'll pledge $10. > Are there another nine people here who'll do the same? Me, me. I'm good for ten, too. The current euro-dollar exchange course makes that the price of a normal size McDonalds Menu - so sparing that makes me healthier both mentally and physically. Great deal. -- Regards, Diez B. Roggisch From sjmachin at lexicon.net Wed Apr 6 18:44:01 2005 From: sjmachin at lexicon.net (John Machin) Date: Thu, 07 Apr 2005 08:44:01 +1000 Subject: number conversion References: <1112810997.893405.58560@g14g2000cwa.googlegroups.com> Message-ID: <31n851tsdqsul60ongetv7guqvu1aj7d69@4ax.com> On 6 Apr 2005 12:01:23 -0700, nicksjacobson at yahoo.com wrote: >I'm writing a program to read in raw data from a WAV file, and write it >to an IT file. I got this to work in C by reading the data into an >array of unsigned chars called "RawDataAry", then converted it to >signed chars by doing the following: It might help us help you if you explained why you think you need to do this. An example or two might help: "I have these bytes in a WAV file \xf0\x0b\xaa etc etc and I need to transform them into to write them to an IT file". Alternatively, "bytes in a WAV file represent integers in range(A,B); bytes in an IT file represent integers in range(C,D); I need to ...". > >signed char *CharAry = malloc(sizeof(signed char) * frames); >for (i = 0; i < input_frames; i++) > CharAry[i] = (signed char)(((signed short)WavDataAry[i]) - 128); WavDataAry or RawDataAry ??? Let's assume for the moment that they are synonyms :-) (1) raw is in an unsigned char, 0 <= raw <= 255 (2) casting that to a signed short gives you an I-don't-know-what without some thought & flicking through K&R -- let's assume still 0 to 255 (3) subtracting 128 gives you -128 to +127 (4) which then gets cast as a signed char .... Somehow I think your bit patterns have survived intact. May I ask a quick silly question: why don't you read it into an array of signed chars in the first place?? Without further information, it appears that you want to travel from New York City, NY to "The Big Apple", but you are diverting past Walla Walla, WA. > >It worked. > > >But when I tried to do this kind of conversion in Python, I got an >OverflowError exception. > >First I read the data into an array of unsigned chars: > >fmt = str(chunklen) + 'B' >fmtsize = struct.calcsize(fmt) >rawdata = struct.unpack(fmt, s[:fmtsize]) >rawdata = list(rawdata) > >Then I tried to convert it: > >charary = array.array('b') >charary.fromlist(rawdata) > >This last line threw the OverflowError exception, "OverflowError: >signed char is greater than maximum." That would be because you omitted one step in emulating your C antics: subtracting 128. > >Is there a way to do this?? We're still not sure what "this" is. > Thanks a lot in advance!! > >--Nick From martin at v.loewis.de Mon Apr 18 13:32:09 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 18 Apr 2005 19:32:09 +0200 Subject: compiling python 2.4.1 on Linux_X86_64 using PGI compiler fails In-Reply-To: References: Message-ID: <4263EF19.9090804@v.loewis.de> Berthold H?llmann wrote: > Has anyone compiled python successfully using PGI compilers under 64 > bit Linux. If yes, what are the neccesarry switches? As a starting point, I would try to compile without optimization. If the compiler has something similar to gcc's -fno-strict-aliasing, you should pass that as well. Regards, Martin From fouff at fouff.com Wed Apr 6 02:16:13 2005 From: fouff at fouff.com (Fouff) Date: Wed, 06 Apr 2005 08:16:13 +0200 Subject: Add System Path?!? In-Reply-To: References: Message-ID: <42537ed3$0$13914$636a15ce@news.free.fr> andrea_gavana at tin.it a ?crit : > Hello NG, > > I have a GUI (written in wxPython) that calls some external exe files. > Some of them requires that I add to the PATH variable 1 directory. Basically, > the exe are located in: > > /MyApp/Solvers/FirstExe > /MyApp/Solvers/SecondExe > > And so on, while the dll needed by these exe are located in: > > /MyApp/MyDll > > These exe files do not work if I don't set the PATH variable also to that > adress. I know I can do it by hand (and also my users can), but I wonder > if there is a way to do it in Python... > > Thank you for all suggestions/pointers. > > Andrea. > > Why not just adding in your app import os os.environ['PATH'] += ";the_new_adress_needed_by_exe" this will just modify locally to your app the environement variable PATH If you want to modify it for ever, just open a console DOS (cmd.exe) and type: set PATH=%PATH%;the_new_adress_needed_by_exe From grobinson at goombah.com Mon Apr 25 12:43:14 2005 From: grobinson at goombah.com (Gary Robinson) Date: Mon, 25 Apr 2005 12:43:14 -0400 Subject: Python consulting opportunity Message-ID: <20050425124314.551810.5d2da129@goombah.com> We'd like to find an experienced Python programmer for a full-time, three-month consulting contract to help us with our product, Goombah (http://www.goombah.com). Experience with wxPython and/or PyObjC would be a big plus. More importantly we're looking for someone who can get up to speed very quickly and who is used to working independently. A longer-term relationship is possible, but right now we're focused on adding a fixed set of features that we plan to add in the very near-term. It's a lot of work and we'll need help to get it done as quickly as we want. If this sounds like an opportunity you'd be interested in, or if you know of someone who might be a match, please let us know. Thanks, Gary -- Gary Robinson CTO Emergent Music, LLC grobinson at goombah.com 207-942-3463 Company: http://www.goombah.com Blog: http://www.garyrobinson.net From tmj at SPAMLESSjarmania.com Sat Apr 2 05:33:04 2005 From: tmj at SPAMLESSjarmania.com (Tim Jarman) Date: Sat, 02 Apr 2005 11:33:04 +0100 Subject: How to reload local namespace definitions in the python interpreter? References: <1112435996.697236.231800@l41g2000cwc.googlegroups.com> Message-ID: <3b7an1F6gf5b4U1@individual.net> test1dellboy3 at yahoo.co.uk wrote: > Hi, > > I am a beginner using the python interpreter. To reduce typing effort, > I created a module called "aliases.py" containing some aliases for > objects I commonly use like - > > aliases.py : > > > import filecmp, os, commands > > op = os.path > go = commands.getoutput > dc = filecmp.dircmp > p1 = '/mnt/usbkey/flash/' > p2 = '/mnt/fat32/myfiles/flash/' > > When I start up the interpreter, I can simply type - > > from aliases import * > > This works fine, but each time I change any of the definitions in > aliases.py, I > have to restart the interpreter and type "from aliases import *" > again. Is there any way to reload these definitions without restarting > the interpreter? > > -Slath reload(aliases) See: http://www.python.org/doc/2.4.1/lib/built-in-funcs.html By the way, are you aware of the import ... as ... idiom? e.g. import os.path as op -- Website: www DOT jarmania FULLSTOP com From rkern at ucsd.edu Sun Apr 24 06:52:54 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sun, 24 Apr 2005 03:52:54 -0700 Subject: Variables In-Reply-To: <86hdhwr5y3.fsf@guru.mired.org> References: <426B0283.40602@cloudthunder.com> <426b255d.375304108@news.oz.net> <426B27C1.4000907@cloudthunder.com> <86hdhwr5y3.fsf@guru.mired.org> Message-ID: Mike Meyer wrote: > Robert Kern writes: > >>>Could I honestly argue this to him? From what basis do I argue that >>>it is not an equation? >> >>It's his responsibility to show that it *is* an equation. >> >>x = x + 1 >> >>Equation? I think not. > > > I think it is. One equation in one unknown. The solution set for x is > {}. > > As a logical equation, it has the value false (just like 0 = 1). Okay, okay, fair enough. But that interpretation has no correspondence with the behavior of that statement in a Python program. x always has a value (presuming it had one before the statement and no exceptions were raised during the addition operation). -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From gnb at itga.com.au Thu Apr 21 03:26:43 2005 From: gnb at itga.com.au (Gregory Bond) Date: Thu, 21 Apr 2005 17:26:43 +1000 Subject: PyObject_New not running tp_new for iterators? In-Reply-To: <2r254d.moe.ln@lightning.itga.com.au> References: <2r254d.moe.ln@lightning.itga.com.au> Message-ID: I wrote: [snip] > What am I missing? The fundamental problem is that this: >> if (!(ro = PyObject_New(MyIter, &MyIterType))) >> return NULL; is really only a malloc() - it doesn't call the tp_new function at all. This is not really clear in the 2.3 version of the C API document that I was consulting - the 2.4 version is much clearer. I have no idea how to do in C all the things that calling a class constructor in Python does. Am I supposed to be calling tp_new & tp_init directly? In the end, this particular class really only needs to be created from a factory function, so I removed the tp_new member altogether and just wrote a C function to initialise the object, and called that from the C factory function. [The above is not particular to the fact that my class is an iterator - all C classes have the same behaviour. My test of a plain-old class probably looked like it worked due to lucky memory patterns.] From martijn at gamecreators.nl Thu Apr 14 11:19:19 2005 From: martijn at gamecreators.nl (martijn at gamecreators.nl) Date: 14 Apr 2005 08:19:19 -0700 Subject: Get the entire file in a variable - error In-Reply-To: References: <1113489431.686307.31840@f14g2000cwb.googlegroups.com> Message-ID: <1113491959.087887.170580@f14g2000cwb.googlegroups.com> I mean it like this. I must have a variable that includes a file (in this case a .gz file) for putting that in a database. (never null) Thanks, From peter at engcorp.com Thu Apr 14 21:23:01 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 14 Apr 2005 21:23:01 -0400 Subject: Supercomputer and encryption and compression @ rate of 96% In-Reply-To: References: <1113470846.970773.4780@g14g2000cwa.googlegroups.com> <425EDE12.3030208@transnorm.ch> <200504142221.41290.james@wrong.nu> Message-ID: R. C. James Harlow wrote: > On Thursday 14 April 2005 22:21, R. C. James Harlow wrote: > >>You have to do that before Fredrick's script works... > > > Damn - 'Fredrik's' - I accidentally decompressed his name. It actually *is* "Fredrick", but the c is both silent, and hidden... -seemed-silly-enough-for-this-thread-ly y'rs, Peter From james at wrong.nu Fri Apr 15 23:23:41 2005 From: james at wrong.nu (R. C. James Harlow) Date: Sat, 16 Apr 2005 04:23:41 +0100 Subject: Piping data into script under Win32 In-Reply-To: <1113619417.667245.148500@g14g2000cwa.googlegroups.com> References: <1113617504.067692.311950@o13g2000cwo.googlegroups.com> <1113619417.667245.148500@g14g2000cwa.googlegroups.com> Message-ID: <200504160423.51729.james@wrong.nu> On Saturday 16 April 2005 03:43, runes wrote: > type countlines.py | python countlines.py = Success > type countlines.py | countlines.py = Failure > > Why doesn't the latter work? Don't quote me on this, but I think it's because invoking countlines.py involves running some sort of wrapper that discards its stdin and stdout. If anyone has a more authorative answer, I'd like to know, because this caught me out too. james. -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From rbt at athop1.ath.vt.edu Fri Apr 15 09:37:25 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Fri, 15 Apr 2005 09:37:25 -0400 Subject: Determine ip address In-Reply-To: <1113570186.181016.249140@f14g2000cwb.googlegroups.com> References: <1113570186.181016.249140@f14g2000cwb.googlegroups.com> Message-ID: codecraig wrote: > hi, > how can i use python to figure the ip address of the machine which > the python script is running on? I dont mean like 127.0.0.1....but i > want the external IP address (such as ipconfig on windows displays). > > any ideas?? > > THanks > To get the public IP (like when you're behind a wirless router, etc) you may try doing something like this: import urllib import re import time ip_search = re.compile ('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}') try: f = urllib.urlopen("http://www.ipchicken.com") data = f.read() f.close() current_ip = ip_search.findall(data) if current_ip: print current_ip time.sleep(3) except Exception: pass HTH, rbt From mirnazim at gmail.com Mon Apr 18 10:45:45 2005 From: mirnazim at gmail.com (Mir Nazim) Date: 18 Apr 2005 07:45:45 -0700 Subject: Zope3 and Plone Message-ID: <1113835544.983163.202080@z14g2000cwz.googlegroups.com> Hi, I wanted to know what will happen to plone once Zope3 will be official version. Is plone being ported to Zope3. I googled it but did not come accross anything stating the plone's migration to zope3. I am thinking to take up a project. plone is a candidate for it. should i want to take benifit of zope3 features too. what should be done. Please comment thanks From bedouglas at earthlink.net Sun Apr 17 22:32:04 2005 From: bedouglas at earthlink.net (bruce) Date: Sun, 17 Apr 2005 19:32:04 -0700 Subject: trying to parse a file... Message-ID: <01f801c543be$cfc971e0$0301a8c0@Mesa.com> hi, i'm trying to modify an app (gforge) that uses python to do some file parsing/processing... i have the following shell file that uses python. if i understand it correctly, it's supposed to modify the 'viewcvs.conf' file, and replace/update the section with 'svn_roots'. it isn't working correctly... can anybody tell me what i need to do? basically, i'd like to continually add to the svn_root: block with an additional line as required. also, can someone tell me what i'd need to do, if i wanted to remove a line of text from the 'svn_root' block if i had a given 'test_x:' thanks bruce bedouglas at earthlink.net ----------------------------------------------------------- viewcvs.conf: . . . # # This setting specifies each of the Subversion roots (repositories) # on your system and assigns names to them. Each root should be given # by a "name: path" value. Multiple roots should be separated by # commas and can be placed on separate lines. # #svn_roots = test2: /svn-gforge/uploadsvn svn_roots = test5: /gforge-svn/test7/svn, test2: /gforge-svn/test7/svn, test3: /gforge-svn/test7/svn, # The 'root_parents' setting specifies a list of directories in which # any number of repositories may reside. Rather than force you to add . . . ----------------------------------------------------------- [root at lserver2 bin]# cat test.sh ----------------------------------------------------------- #! /bin/sh python < /var/lib/gforge/etc/viewcvs.py ----------------------------------------------------------- From benn at cenix-bioscience.com Mon Apr 25 12:24:51 2005 From: benn at cenix-bioscience.com (Neil Benn) Date: Mon, 25 Apr 2005 18:24:51 +0200 Subject: PyGTK vs. wxPython In-Reply-To: <116q56ie4vqtu04@corp.supernews.com> References: <1114444582.909431.245450@f14g2000cwb.googlegroups.com> <116q56ie4vqtu04@corp.supernews.com> Message-ID: <426D19D3.2060505@cenix-bioscience.com> Grant Edwards wrote: >On 2005-04-25, dcrespo wrote: > > >>Hi all... >> >>I think wxPython is much better than PyGTK. First of all, PyGTK needs >>the GTK runtime installed, whereas wxPython is entirely Python's >>modules, >> >> > >Huh? wxPythonGTK requires GTK runtimes as well: > > > > Hello, Guess he's talking about windows : http://www.dropline.net/gtk/ You will already have a windowing toolkit on windows - mfc/win32. BTW, I cheated and saw a windows related question from above also same poster ;-) Cheers, Neil -- Neil Benn Senior Automation Engineer Cenix BioScience BioInnovations Zentrum Tatzberg 46 D-01307 Dresden Germany Tel : +49 (0)351 4173 154 e-mail : benn at cenix-bioscience.com Cenix Website : http://www.cenix-bioscience.com From __peter__ at web.de Fri Apr 1 05:04:11 2005 From: __peter__ at web.de (Peter Otten) Date: Fri, 01 Apr 2005 12:04:11 +0200 Subject: StopIteration in the if clause of a generator expression Message-ID: To confuse a newbies and old hands alike, Bengt Richter wrote: > Need something more straightforward, e.g., a wrapped one-liner: > > >>> def guess(n=3): print ("You're right!", 'No more tries for > >>> you!!!')[n-1 in > ... (x for x in xrange(n) for t in [raw_input('Guess my name: > ')=='Ben'] > ... if not t or iter([]).next())] > ... > >>> guess() To make it a bit clearer, a StopIteration raised in a generator expression silently terminates that generator: >>> def stop(): raise StopIteration ... >>> list(i for i in range(10) if i < 5 or stop()) [0, 1, 2, 3, 4] In a list comprehension, on the other hand, it is propagated: >>> [i for i in range(10) if i < 5 or stop()] Traceback (most recent call last): File "", line 1, in ? File "", line 1, in stop StopIteration Is that an intentional difference? Peter From kay.schluehr at gmx.net Sun Apr 10 10:18:10 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 10 Apr 2005 07:18:10 -0700 Subject: Thoughts on some stdlib modules In-Reply-To: References: <1113139772.023037.153620@l41g2000cwc.googlegroups.com> Message-ID: <1113142690.674650.238460@o13g2000cwo.googlegroups.com> Fredrik Lundh wrote: > here are three alternatives: > > ltree (http://codespeak.net/lxml/) > libxml2 (http://xmlsoft.org/downloads.html) > celementtree (http://effbot.org/zone/celementtree.htm) Thanks, Fredrik, I will take a look. Ciao, Kay From spork at spork.narod.ru Sat Apr 30 18:29:15 2005 From: spork at spork.narod.ru (Alex) Date: 30 Apr 2005 15:29:15 -0700 Subject: array type casting problem in scipy.interpolate References: <42732655@news.ColoState.EDU> <1114889551.101190.312080@l41g2000cwc.googlegroups.com> Message-ID: <4273f8ab@news.ColoState.EDU> On 30 Apr 2005 12:32:31 -0700, bgs said: > The routine requires real arrays, and you are giving it one complex > one. It does not know what to do with the complex array. What are you > expecting it to do? If you need the real and imaginary parts to be > separately interpolated, then split the complex array into two real > arrays and use the routine twice. Hello, Thanks for the pointer. I will interpolate the real and imaginary parts separately then. Regards, Alex From martin.witte at gmail.com Sat Apr 30 07:28:30 2005 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 30 Apr 2005 04:28:30 -0700 Subject: How to run a program? In-Reply-To: References: Message-ID: <1114860510.681773.86450@z14g2000cwz.googlegroups.com> please read the documentation for subprocess, http://docs.python.org/lib/node230.html From le_cactus at msn.com Fri Apr 8 16:55:39 2005 From: le_cactus at msn.com (Cactus) Date: 8 Apr 2005 13:55:39 -0700 Subject: Declaring variables from a list Message-ID: <1163d88e.0504081255.438fbb96@posting.google.com> Hi, If I got a list is it possible to declare a variable from the items in that list? Code Sample: Blob = ['Var1', 'Var2', 'vAR3'] i = 5 for listitems in Blob: i += 1 listitems = i print Var1 6 print Var2 7 print vAR3 8 Something like that? This doesn't work (obviously) but is there a way to do this? TIA, Cacti From rockon02 at senet.com.au Thu Apr 28 07:39:55 2005 From: rockon02 at senet.com.au (Mike brown) Date: Thu, 28 Apr 2005 21:39:55 +1000 Subject: Ron Grossi: God is not a man References: <1114098221.580669.86300@g14g2000cwa.googlegroups.com> <1114127633.859113.292290@l41g2000cwc.googlegroups.com> <#2tJ0r3RFHA.3664@TK2MSFTNGP15.phx.gbl> <1114328806.147822.64660@z14g2000cwz.googlegroups.com> <1114329202.229148.82550@o13g2000cwo.googlegroups.com> <1114654290.690332.155200@f14g2000cwb.googlegroups.com> Message-ID: > 4) I doubt seriously whether God plays a guitar, since guitars are made by > men, for men. His Son could theoretically play a guitar. Perhaps He does. > Perhaps He doesn't. Only the Father and His Holy Angels know. Perleeeese. Do you really take this stuf seriously ? It's like the ancient discussion about how many angels can dance on the head of a pin, a lot of bullshit. Sorry in advance to the believers amongst us, but these God Botherers annoy the crap out of me. Believe what you want to, but leave me alone. MJRB From mcfletch at rogers.com Wed Apr 13 09:46:22 2005 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Wed, 13 Apr 2005 09:46:22 -0400 Subject: preallocate list In-Reply-To: References: Message-ID: <425D22AE.2050302@rogers.com> Jim wrote: > Thanks for the suggestions. I guess I must ensure that this is my > bottle neck. ... > for line in f: > factor = [] > tokens = line.split() > for i in tokens: > factor.append(float(i)) > factors.append(loadFactor) > ... You might try: factors = [ [float(item) for item in line.split()] for line in f ] avoiding the extra statements for appending to the lists. Also might try: factors = [ map(float, line.split()) for line in f ] though it uses the out-of-favour functional form for the mapping. Good luck, Mike ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From mefjr75 at hotmail.com Sat Apr 2 17:53:22 2005 From: mefjr75 at hotmail.com (M.E.Farmer) Date: 2 Apr 2005 14:53:22 -0800 Subject: Docorator Disected In-Reply-To: <4p9t419ockcg8578g6guse3a14t16orebf@4ax.com> References: <4p9t419ockcg8578g6guse3a14t16orebf@4ax.com> Message-ID: <1112482402.694276.228230@z14g2000cwz.googlegroups.com> Hello Ron , You have many good explanations already, but I thought that this __might__ help others. Like you I was confused by the decorator syntax. till I realized it was shorthand for ... def identity(f): return f def foo(): pass # this is the 'old way' foo = identity(foo) It just rebinds foo to the return value of the decorator function. With the new syntax it becomes. def identity(f): return f @identity def foo(self): pass This is the same as above but now the function is passed and rebound behind the scenes. Also note that decorators don't have to be a nested function, it really depends on what you are trying to achieve. hth, M.E.Farmer From abkhd at earth.co.jp Fri Apr 15 15:44:11 2005 From: abkhd at earth.co.jp (A.B., Khalid) Date: 15 Apr 2005 12:44:11 -0700 Subject: Get OS name References: <1113572595.889597.206690@g14g2000cwa.googlegroups.com> <1113574033.787739.318840@o13g2000cwo.googlegroups.com> <1113579720.273453.32480@g14g2000cwa.googlegroups.com> Message-ID: <1113594251.364696.52290@z14g2000cwz.googlegroups.com> codecraig wrote: > my requirements for getting the OS info havent changed. My first > message says "How can I get the OS Name, such as "Windows XP Pro"." > ....that's what I wanted all along. > > thanks for the information anyway, i believe platform is better than my > previous approach. > > thanks Please note that platform appears to require win32api to be in your system. The following is the code from \Lib\platform.py. The function that gets the data sets these values as default [Code from platform.py] def win32_ver(release='',version='',csd='',ptype=''): [/Code] And will return empty strings in case win32api is not found: [Code from platform.py] # Import the needed APIs try: import win32api except ImportError: return release,version,csd,ptype [/Code from platform.py] Accordingly, my Python 2.3.5 final which has win32api installed can get the platform answer right: $ /py23/python/dist/src/MinGW/python -i Python 2.3.5 (#62, Feb 12 2005, 02:56:20) [GCC 3.4.2 (mingw-special)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import platform >>> print platform.system(), platform.release() Windows 98 >>> But where I don't have win32api installed, my Python does not know that answer you seek: $ /py25/python/dist/src/MinGW/python -i Python 2.5a0 (#65, Apr 12 2005, 20:22:54) [GCC 3.4.2 (mingw-special)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import platform >>> print platform.system(), platform.release() Windows >>> Regards, Khalid From scmarsh at hotmail.com Mon Apr 18 13:25:54 2005 From: scmarsh at hotmail.com (scott) Date: Mon, 18 Apr 2005 17:25:54 GMT Subject: EasyDialogs module problem with python 2.4.1 Message-ID: First my setup: I'm using the framework build of Python 2.4.1 ( http://bob.pythonmac.org/archives/2005/03/31/macpython-241-installer/ ) on an ibook G4 running Mac OS 10.3.8. I installed wxPython 2.5.5.1 ( Unicode runtime 2.5.5.1 for the Panther version of Macpython-OSX 2.4 ) ( http://wxpython.org ) Now my problem: EasyDialogs module ( http://www.python.org/doc/2.4.1/mac/module-EasyDialogs.html ) works with pyshell (interactive python program included with wxPython) but not with python launched at the terminal: ie: ----------------------- PyShell 0.9.4 - The Flakiest Python Shell Sponsored by Orbtech - Your source for Python programming expertise. Python 2.4.1 (#2, Mar 31 2005, 00:05:10) [GCC 3.3 20030304 (Apple Computer, Inc. build 1666)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>>import EasyDialogs >>>EasyDialogs.Message('hi') From mauriceling at acm.org Fri Apr 29 20:38:30 2005 From: mauriceling at acm.org (Maurice LING) Date: Sat, 30 Apr 2005 10:38:30 +1000 Subject: Python site-packages and import References: Message-ID: Peter Saffrey wrote: > (apologies for starting a new thread - Google can't retrieve the other > message for some reason) > > Yes, /usr/lib/python/site-packages is in sys.path. This series of > commands should explain what I mean: I've put the Python ID3 module in > a sub-directory of site-packages as an illustration. > > pzs at bonnie:~$ ls /usr/lib/python2.3/site-packages/ > ID3.py ID3.pyc ID3.pyo README apt_inst.so apt_pkg.so apt_proxy > bsddb3 debconf.py debconf.pyc debconf.pyo id3 pj twisted > > pzs at bonnie:~$ ls /usr/lib/python2.3/site-packages/apt_proxy/ > __init__.py __init__.pyo apt_proxy.pyc apt_proxy_conf.py > apt_proxy_conf.pyo apt_proxytap.pyc memleak.py memleak.pyo > misc.pyc packages.py packages.pyo > __init__.pyc apt_proxy.py apt_proxy.pyo apt_proxy_conf.pyc > apt_proxytap.py apt_proxytap.pyo memleak.pyc misc.py > misc.pyo packages.pyc twisted_compat > > pzs at bonnie:~$ ls /usr/lib/python2.3/site-packages/id3 > ID3.py ID3.pyc ID3.pyo > > pzs at bonnie:~$ python > Python 2.3.5 (#2, Feb 9 2005, 00:38:15) > [GCC 3.3.5 (Debian 1:3.3.5-8)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>>>import sys >>>>sys.path > > ['', '/usr/lib/python23.zip', '/usr/lib/python2.3', > '/usr/lib/python2.3/plat-linux2', '/usr/lib/python2.3/lib-tk', > '/usr/lib/python2.3/lib-dynload', > '/usr/local/lib/python2.3/site-packages', > '/usr/lib/python2.3/site-packages'] > >>>>import apt_proxy.memleak >>>>import id3.ID3 > > Traceback (most recent call last): > File "", line 1, in ? > ImportError: No module named id3.ID3 > > > > > Peter your site-package/id3 lacks a __init__.py file. '__init__.py' file can be just an empty file but it needs to be there for python to be considered as a package. Alternatively, you can use 'from id3 import ID3' instead of 'import id3.ID3' Cheers Maurice From ishpeck at gmail.com Wed Apr 27 09:41:51 2005 From: ishpeck at gmail.com (Ishpeck) Date: 27 Apr 2005 06:41:51 -0700 Subject: Internet Explorer, COM+, Javascript and Python Message-ID: <1114609311.916761.272980@f14g2000cwb.googlegroups.com> I need to make IE execute javascript in a web page with COM+ and Python. Similarly to the way they do it in this article. . . http://www.codeproject.com/com/jscalls.asp From Please Sun Apr 24 19:28:03 2005 From: Please (Please) Date: 24 Apr 2005 18:28:03 -0500 Subject: =?iso-8859-1?q?Good_morning_or_good_evening_depending_upon_yo?= =?iso-8859-1?q?ur_location=2E_I_want_to_ask_you_the_most_important_questi?= =?iso-8859-1?q?on_of_your_life=2E_Your_joy_or_sorrow_for_all_eternity_dep?= =?iso-8859-1?q?ends_upon_your_answer=2E_The_question_is=3A_Are_you_saved?= =?iso-8859-1?q?=3F_It_is_not_a_question_of_how_good_you_are=2C_nor_if_you?= =?iso-8859-1?q?_are_a_church_member=2C_but_are_you_saved=3F_Are_you_sure_?= =?iso-8859-1?q?you_will_go_to_Heaven_when_you_die=3F_GOOGLE=B7NEWSGROUP?= =?iso-8859-1?q?=B7POST=B7149?= References: <1114384941.623433.251470@o13g2000cwo.googlegroups.com> Message-ID: Reports to groups-abuse at google.com, abuse at aol.net, domains at aol.net, abuse at yahoo.com, abuse at yahoo-inc.com And do not feed the troll! From mwm at mired.org Sun Apr 24 03:11:04 2005 From: mwm at mired.org (Mike Meyer) Date: Sun, 24 Apr 2005 02:11:04 -0500 Subject: Variables References: <426B0283.40602@cloudthunder.com> <86u0lwrfbw.fsf@guru.mired.org> Message-ID: <86pswkr6nr.fsf@guru.mired.org> Richard Blackwood writes: > Mike Meyer wrote: >>First, new disciplines often redefine words to mean something >>different than the disciplines they were derived from. Variable is a >>good example of that. In math, a variable is a placeholder in an (a >>system of) equation(s), and will have associated with it a (possibly >> empty) set of values that satisfy the equation(s). >> > Not merely a placeholder, right? A variable in math is a 'placeholder' > for a dynamic value, one which can or does change. If one can graph > the movement (change) of foo, foo is a variable within that scope. For > example: > > foo = 5 > foo = 6 > > I can graph foo's movement/change. It can thus be considered a > variable within mathematics. If I write: No. When I'm wearing my mathematicians hat, variables don't change values. What you are describing is a function, "foo", describing a mapping from time to numbers. You can graph that function. When doing calculus, we talk about the "rate of change" of a variable with respect to a second variable (dfoo/dt), but that's just shorthand for talking about the system foo = f(t). In this case, foo is a variable that has a solution set with many possible values. If you add an equation specifying t (i.e., t = 0) to the system, you'll change the solution set for foo to a single value: {f(t)}. Now, when I'm wearing my programmers hat, variables can be bound to different values (or, in other languages, change values) as the program progresses. In this case, the variable *is* changing. > foo = 5 > > I can graph this but it will merely be a static point, a > constant. Constants are not variables because they do not change, they > do not "vary" in content. Actually, the graph of foo = 5 is a straight line, passing through the point 5 on the foo axis, and parallel to any other axis in the system. It's a very simple system, with one equation in one variable with one possible solution. Ask your friend if foo is a variable if you write: foo = sqrt(1) In this case, the solution set for foo is {1, -1}. In Python, foo has the value 1.0 (if you do "import sqrt from math"). While there are programming languages that support multiple return values for functions, I'm not aware of any that define sqrt so that it will return both 1 and -1 (and I *have* to wonder if that's worth a PEP). >>In math, if you say "foo = 5", foo is a variable, with a single value >>(5) that satisfies the equation. In Python, if you say "foo = 5", foo >>is a variable, that currently references the value 5. >> >> > He would argue strongly against your notion of variable. In the > statement "foo = 5", foo is constant. He would thus argue that foo is > a constant and not a variable (regardless of whether you change foo's > value in subsequent statements). He's wrong. Foo is a variable in the single-equation system "foo = 5". The solution set for it is {5}. If the two equations are "foo = 5" and "foo = 6", then foo is a variable in a two-equation system with a solution set of {} (the empty set). I'd recommend your friend pick up an algebra textbook. It's been so long since I did any that I can't recommend one, though. Never forget: Constants aren't, variables won't. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From deetsNOSPAM at web.de Tue Apr 12 07:17:54 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Tue, 12 Apr 2005 13:17:54 +0200 Subject: workaround for generating gui tools References: <1113061810.530359.172720@g14g2000cwa.googlegroups.com> <3bqgh6F6larilU1@individual.net> Message-ID: Hi, > So, instead, with this new system (note I wasn't involved with the old > system), I do everything with metadata. (Credit where credit is due, the > other programmer was starting to do some of this, though he couldn't quite > take it down to the interface and there are some things I had to add > later.) Every "thing" (class) has a description of what it's made out of, > and what type each of those things are. When I go to edit an instance, the > Javascript pulls down that description, and a description of the instance > (and all of its associated sub-instances), and instead *generates* a form > to edit the object based on what it is made of. Ok. I can assure you that I've been doing that myself, and that this attitude describes my general approach to computers and programming: If the machine can be told to do tedious work for me, I'd rather tell her how to do it than do that work myself for the thousands time. I did this for a LDAP browser/editor once, nice thing. But - there is a big BUT here - if we're talking about GUIs, we inevitably enter the realm of taste and customization requirements. And that's the point where things get tricky: technically inclined people can be easily satisfied with simple and pureley functional interfaces. But even I as a strong FFF (form follows function) believer have to say: The form _does_ matter, once the function is in place. In my more complicated qt forms, I had to invest quite an amount of time to rearrange my controls in a way that (hopefully) communicated the purpose of the whole thing. These days the rollout will come and certainly some feedback will tell me that I still didn't do a perfect or even good job. But then I'll fire up my designer, and can rearrange things - without further bothering in the code. To me the importent lesson to learn is not to mingle layout with logic. And as layout follows its own rules (that techies sometimes have difficulties to grasp), one should be as flexible and powerful with layouting tools as it gets. > How do I decide the order to create the fields? Classes carry a metadata > field called "order" that lists the fields it wants in order, the > remainder will by default be tacked on the end. What if I don't want a > certain field to display? There's a metadata field that lists the ones we > want to display for editing, there's another I can use to just filter a > couple out if the first isn't present. What if I want a particular widget > to do something special like be a certain width? I've created a metadata > "escape hatch" that lets me pass parameters directly to the node; > it's "bad style", but sometimes useful. Everything I use is backed by a > database which has limited typing abilities, so I have a field called > "humantype" that declares the human type of the data, so I can then create > intelligent widgets for that, too. One of the things we can do, for > instance, is create an "image" widget that specifies a URL for an image, > and as validation, shows it there in the browser. We could also make it > accept uploads. Then, just by labelling a field as an "htmlImage", we get > the image editor, no form redesign, no muss, no fuss. I'm not convinced that this is really a superiour way to go. I'm all with you in terms of form-validation, constraint checking and mapping to the persistence layer. I do all of this based on meta-information (or reflection, which is the same). But what you propose is that you create a style-annotation which in the end will grow until it becomes a unmanagable beast. Instead, I prefer to have the designer (this time the person doing the html templates, not the tool) make the decision if a text-property of my object becomes a simple or a