From anton at vredegoor.doge.nl Sun Oct 13 15:23:57 2002 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Sun, 13 Oct 2002 21:23:57 +0200 Subject: Can a metaclass solve this? Message-ID: Hello All, in my quest to reinvent the wheel I am busy redefining list operations as long integer computations. Unwise as this may be this question is about something else that came up while I was writing a test script. I am using a global and a factory function to initialize my class and I would like to know if the global can be wrapped into a super, meta, mixin or whatever class that lends itself to it. Perhaps this can be done with a metaclass? It is important to me that the objects that are created are as small as possible and have self.index as their only property. I especially do not want to take in a separate copy of the list of initializing objects inside each of my instances. Anton. #longlist.py by Anton Vredegoor anton at vredegoor.doge.nl october 2002 """ Test script to turn list manipulations into computations involving long integers. For the moment the __add__ function inside longlist converts back and forth to sequencer but the objective is to do this directly with long integer computations. This script needs sequencer.py which can be found at: http://home.hccnet.nl/a.vredegoor/sequencer/sequencer.py """ from sequencer import sequencer class longlist: #list manipulations simulated by long integer computations def __init__(self, index): self.index = index def __add__(self,other): ss = seq[self.index] so = seq[other.index] return _longlist(seq.index(ss+so)) def __repr__(self): return '%s' %(seq[self.index]) def asstring(self): return '%s' %(''.join(seq[self.index])) _longlist = longlist def longlist(arg): if type(arg) not in [type(1), type(1L)]: i = seq.index(list(arg)) else: i = arg return _longlist(i) def test(): global seq seq = sequencer([chr(i) for i in range(256)]) a = longlist('Hello,') b = longlist(' world!') print 'index: %i, string: "%s"' %(a.index,a.asstring()) print 'index: %i, string: "%s"' %(b.index,b.asstring()) print 'index: %i, string: "%s"' %((a+b).index,(a+b).asstring()) seq = sequencer([(i,j) for i in range(10) for j in range (10)]) a = longlist(12345L) b = longlist(67890) print 'index: %i, list: %s' %(a.index,a) print 'index: %i, list: %s' %(b.index,b) print 'index: %i, list: %s' %((a+b).index,a+b) a = longlist([(2,3),(9,2)]) print 'index: %i, list: %s' %(a.index,a) if __name__=='__main__': test() From pinard at iro.umontreal.ca Thu Oct 17 19:36:11 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: Thu, 17 Oct 2002 19:36:11 -0400 Subject: Python daemon In-Reply-To: <20021017230255.GA15144@sentinelchicken.net> (Jason Morgan's message of "Thu, 17 Oct 2002 19:02:55 -0400") References: <20021017230255.GA15144@sentinelchicken.net> Message-ID: [Jason Morgan] > You may want to take a look at daemontools by Ban Burnstein. [...] You meant Daniel Burnstein? I'd rather not. You may choose the crowd you want to be with, and decide to stay away from others. It's your life! :-) -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From pj at engr.sgi.com Mon Oct 21 00:10:26 2002 From: pj at engr.sgi.com (Paul Jackson) Date: 21 Oct 2002 04:10:26 GMT Subject: How do I invoke IE browser from Python on Mac OS X? References: <3DB3583E.EF7B9750@alcyone.com> <3DB35D14.C014B0A9@alcyone.com> Message-ID: > That's what the ellipsis is for ... Ah - so you're operating under the long standing Unix etiquette that it's bad form to have any redundancy in a man page . More technically, the ellipsis says it takes more arguments, but it doesn't say that 'open' will open them. Perhaps 'open' passes args 2+ to the invoked command as args 1+. -- -- I won't rest till it's the best ... Programmer, Linux Scalability Paul Jackson 1.650.933.1373 From sholden at holdenweb.com Tue Oct 8 17:13:28 2002 From: sholden at holdenweb.com (Steve Holden) Date: Tue, 8 Oct 2002 17:13:28 -0400 Subject: [OT} How to un-GPL parts of a GPL'd module. References: Message-ID: wrote in message news:mailman.1034094252.7556.python-list at python.org... > > From: Chris Watson [mailto:opsys at voodooland.net] > > > > > Perhaps you should not be reading the GPL'd code in the > > > first place. The GPL is a quid-pro-quo agreement. You > > > get insight into others code, and in exchange you contine > > > to pass on the knowledge. If it seems unfair or burdensome > > > to benefit others in the same way you were benefited then > > > keep your eyes on your own paper. > > > > I love the GNU "Play by my rules or i'm taking my toys and > > going home" attitude. It's so beneficial to humanity. If it > > was about passing on knowledge it would be in the public domain > > commons for the benefit of man. As someone stated earlier the > > GPL is a political statement. And we all know where politics > > get us. > > > > Chris > > > > Well, there *is* the problem of corporations trying to take > technology which isn't theirs and gaining zillions off it, > and then burying said technology so other's won't benefit > from it. It's happened with plenty of BSD technology which > ended up in NT, and then became patented by M$ (IIRC). > Since the BSD technology was published, any patents issued to Microsoft which use the same technology are invalidated by the existence of "prior art". A lot of the problems with software patents seem to arise because the examiners simply aren't familiar enough with the existing state of software technologies. > Then you see plenty of other technologies which *were* public > domain, or at least didn't have any heavy licensing (or rather, > *formal* licensing) behind them, and then they were copied > by some opportunist and subsequently patented, resulting in > the net loss of said tech. Take a look at the IRC robot > fiasco going on. > But ultimately the current intellectual landgrab is making it clear that patents are unfair primarily because the system behind them now clearly operates to the benefit of wealthy organizations, such as corporations and research institutes. The individual inventor no longer sees a level playing field. > So there actually *is* a need for the GPL, to help keep things > fair; it's no fun to be inventing stuff and then setting it free, > if there's others with no notion of playing fairly taking all, > making zillions, and shutting others out. There's countless > evidence of it going on every day, you just need take a look > and read around. > > Good luck on your search. > The OP's real mistake, as has already been pointed out, was reading GPL'd code when he doesn't agree with, or want to abide by, the GPL. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- From tjw at omnigroup.com Fri Oct 18 21:49:14 2002 From: tjw at omnigroup.com (Timothy J. Wood) Date: Fri, 18 Oct 2002 18:49:14 -0700 Subject: Private variables In-Reply-To: Message-ID: On Thursday, October 17, 2002, at 08:41 PM, Delaney, Timothy wrote: > If your users must truly be considered as adversaries (i.e. you > *cannot* > trust them) then Python is not the correct language to use. My goal is to add scripting to a game engine that allows users to make their own game types in Python. Thus I want user to be able to package up their scripts and give them to other users with as few as possible (ideally zero) security concerns. > The simple fact is, if someone has the source to your code, or has the > bytecode, then it doesn't matter what you do to prevent maliciousness > - it > becomes a trivial matter to circumvent. I'm actually planning on making rather more substantial changes to Python. In particular, I haven't gotten warm fuzzies from the restricted exec stuff and I'd rather strip out everything that accesses dangerous system calls. Yes, this means that many packages won't work, but the only package I want to work in my embedded system is mine (some others might be useful, but I'm aiming for the minimal useful installation). So, for example, anything that would access the filesystem would instead get bridged to my filesystem APIs (for reading zip files as filesystems, as in nearly every other game made today :). All the native module loading, network support, process creation, and anything else that looks like it could be misused would be not included in the distribution. As part of this, I'll definitely disable loading of bytecode (for example, my filesystem API could just not return anything with a .pyc extension). > I would suggest you take a long hard look at your requirements and see > if > you truly do need this level of security, or if it would simply be > enough to > have a system which will prevent mistakes (such as a proxy class which > unconditionally throws an exception from __setattr__). I definitely want this level of security. Any system that allows novice users to easily download and execute code modules developed by some random unknown person needs this level of security. I suppose I could hack something into Python while I'm making all these other changes, but if there is an existing way to do this, I'd rather invent as little of this as possible :) Thanks! -tim From marklists at mceahern.com Thu Oct 10 12:23:09 2002 From: marklists at mceahern.com (Mark McEahern) Date: Thu, 10 Oct 2002 11:23:09 -0500 Subject: No tabs in post PLEASE!!! (was Re: partial list sort) In-Reply-To: <15781.35354.220462.463800@montanaro.dyndns.org> Message-ID: I no longer have the post from Alex Martelli, but I wanted to make an observation in light of his request. He's asking folks not to use tabs. I don't know how onerous that is. I have emacs set to untabify buffers on save, so it's not onerous for me. If you find it onerous for you, you may chose to disregard the request, but consider this: I'm just guessing, but I don't think Alex is making the request as someone who often posts questions and receives answers in the form of code. Alex, for those of you who don't know, is one of the most prolific and helpful posters to comp.lang.python. So there Alex is, helping people left and right with their code, dealing with tabs. And he's asking, as a general courtesy, so that he can continue to help people without having to deal with converting tabs/indentation himself, that you consider posting code snippets with spaces. (I don't pretend to speak for Alex--the above is just my impression.) Continue with the pointless holy war, but just think of that the next time you post code. Cheers, // mark p.s. I apologize for all the times I've cluelessly composed an anwser or a question in Outlook (instead of emacs) and used tab to indent. - From demonsly at hot.ee Thu Oct 31 08:09:43 2002 From: demonsly at hot.ee (Andrei Sosnin505999200) Date: Thu, 31 Oct 2002 15:09:43 +0200 Subject: New to python References: Message-ID: <3DC12B97.3010604@hot.ee> Andres Rosado wrote: > At 06:46 AM 10/22/2002 -0400, you wrote: > >> I'm a very experienced C++/Java programmer. Can anyone recommend >> papers or >> books that will help me avoid programming C++ using Python syntax and to >> learn to do things the "Python way". I'd recommend "Dive into Python". It's available online: http://www.diveintopython.org/ It's quite good for experienced programmers. It helped me a lot, too. -- Andrei Sosnin http://zzx.ath.cx http://www.hot.ee/tomatensaft --- From alanmk at hotmail.com Fri Oct 11 13:03:00 2002 From: alanmk at hotmail.com (Alan Kennedy) Date: Fri, 11 Oct 2002 18:03:00 +0100 Subject: Stringify object reference? References: <3DA6FB65.5D6A4AFE@hotmail.com> Message-ID: <3DA70444.14EE9E06@hotmail.com> > Alan Kennedy wrote: > >>>> o > > > > ^^^^^^^^^^ > > > > But being able to get at this number depends on the __repr__ and > > __str__ method implementations for the class in question. > Daniel Dittmar wrote: > You're looking for the id () builtin. Great, Thanks Daniel. That takes care of the object to ascii mapping. But is there a way to get from ascii back to object? TIA, alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From jb at cascade-sys.com Wed Oct 23 02:45:00 2002 From: jb at cascade-sys.com (James J. Besemer) Date: Tue, 22 Oct 2002 23:45:00 -0700 Subject: RTFM In-Reply-To: References: Message-ID: <3DB6456C.50006@cascade-sys.com> http://www.cascade-sys.com/~jb/Humor/userclue.gif Will Ganz wrote: >If you have the RTFM attitude, take it to a Perl list. You'll fit in much >better. > > > >:> -----Original Message----- >:> From: python-list-admin at python.org >:> [mailto:python-list-admin at python.org]On Behalf Of demian neidetcher >:> Sent: Tuesday, October 22, 2002 3:11 PM >:> To: python-list at python.org >:> Subject: RTFM >:> >:> >:> RTFM >:> >:> after you've done that go to... >:> http://www.tuxedo.org/~esr/faqs/smart-questions.html >:> -- >:> http://mail.python.org/mailman/listinfo/python-list >:> > > > > -- James J. Besemer 503-280-0838 voice 2727 NE Skidmore St. 503-280-0375 fax Portland, Oregon 97211-6557 mailto:jb at cascade-sys.com http://cascade-sys.com From jerf at 192.255.255.255 Thu Oct 3 00:29:49 2002 From: jerf at 192.255.255.255 (jerf at 192.255.255.255) Date: Thu, 03 Oct 2002 04:29:49 GMT Subject: Tkinter and no root window References: <%CMm9.14073$PP.15173@rwcrnsc53> Message-ID: <0JPm9.20984$xI5.4194@sccrnsc02> On Thu, 03 Oct 2002 01:48:48 +0000, Matthew Dixon Cowles wrote: > You can send the root window a withdraw() immediately after it's > created. Generally, it won't be displayed. Thanks, that works on my system. Now that I know what I'm looking for, of course, it's easy to find in the docs. From aahz at pythoncraft.com Sun Oct 6 16:58:03 2002 From: aahz at pythoncraft.com (Aahz) Date: 6 Oct 2002 16:58:03 -0400 Subject: Variables vs. names References: <3D7F8132.2D5CEC24@earthlink.net> Message-ID: In article <3D7F8132.2D5CEC24 at earthlink.net>, Joseph A. Knapka wrote: > >I understand that a Python "variable" is really just a dictionary key; >fine. In other languages, instead of "naming" a dictionary entry, a >variable might directly "name" a chunk of storage. So other than the >layer of indirection introduced by the dictionary mapping, what is >the practical significance of "names bound to values" vs "variables >with values"? Are there languages that achieve Python's semantics >using "real" variables? Java's semantics seem pretty much identical to >Python's in this respect, yet nobody in the Java community will object >if you call a thing-with-a-name-and-a-value a "variable". Python names don't have values. Names are always references to objects. I don't know Java well enough to have any clue how it handles references, but I know Java doesn't have pointers. Michael Hudson has claimed that Common Lisp "places" are similar to Python names, but I don't know Common Lisp at all, and I haven't yet had enough discussion with Michael to verify that places have the same semantics. Python immutables allow easy glossing over of the special semantics, but mutables are another story: a = [] b = a a.append('foo') print b -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From emile at fenx.com Sat Oct 12 03:29:22 2002 From: emile at fenx.com (Emile van Sebille) Date: Sat, 12 Oct 2002 00:29:22 -0700 Subject: Win32 and Excel ranges References: Message-ID: "L Whitley" asks > I've found examples of how to read data from Excel using range, but > haven't found an example of how to write data to Excel using range. Can > anyone help? This is snipped from a script I wrote a couple of years ago. Perhaps it helps. def setCell(row,col): cellref = "" colref = col if int((col-1)/26): cellref = chr(ord("A")-1+int((col-1)/26)) colref = colref - int((col-1)/26)*26 cellref = "%s%s%d" % (cellref, chr(ord("A")-1+colref),row) return cellref def SaveSrce(source,worksheet): ws,r = GetWorksheet(worksheet) ws.Activate() for row in source: cols = len(row) range = "R"+`r`+"C1:R"+`r`+"C"+`cols` cell1 = setCell(r,1) cell2 = setCell(r,cols) xl.Range(cell1+":"+cell2).Value = row r = r + 1 -- Emile van Sebille emile at fenx.com --------- From kalle at lysator.liu.se Sun Oct 27 18:47:19 2002 From: kalle at lysator.liu.se (Kalle Svensson) Date: Mon, 28 Oct 2002 00:47:19 +0100 Subject: How do I do a Rot13? In-Reply-To: References: Message-ID: <20021027234719.GA703@i92.ryd.student.liu.se> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 [John Draper] > How do I write a function to do a "rot13" to a string? > Do I have to do this character-by-character or is there a translate > function which will do this for me? A char-by-char approach might be the most clear, but using the functions translate and maketrans in the string module is an option. A bonus is that it's probably faster. Peace, Kalle - -- Kalle Svensson, http://www.juckapan.org/~kalle/ Student, root and saint in the Church of Emacs. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.7 (GNU/Linux) Comment: Processed by Mailcrypt 3.5.6 iD8DBQE9vHsDdNeA1787sd0RAvCdAKDOK1PkeRDheVjF77JG3r1wt7RKPACgxKxf K0Axe/p9xziRWtWy3YFxkbc= =xGV0 -----END PGP SIGNATURE----- From ykingma at accessforall.nl Fri Oct 4 16:52:06 2002 From: ykingma at accessforall.nl (Ype Kingma) Date: Fri, 04 Oct 2002 22:52:06 +0200 Subject: Simple lru cache? Message-ID: <3d9dfe86$0$124$e4fe514c@dreader6.news.xs4all.nl> Hello, Does anyone know of a good lru cache implementation in python? I tried google, and found some things in zope, but these are more complicated than what I need. I need a cache to avoid moving the disk head around in a large database. For this I'd like a dictionary with a maximum number of items in which the least recently used item is discared when the maximum size would be exceeded. I made one from a dictionary and a special purpose doubly linked list that allows moving any list element to the front. It works, but I'm not really happy with all the list elements in this list. The alternative is a normal python list, but it would probably take too much time for shifting the aging elements. Or is there a way to pick one element randomly from a list and move it to front or back and shift the rest to make place, all in a single python statement, ie. without using a for statement? Java 1.4 has a linked hash table that does much of what I need, but I can't take java/jython for granted all the time. See: http://java.sun.com/j2se/1.4.1/docs/api/java/util/LinkedHashMap.html which has a removeEldestEntry() method and allows to rejuvenate an entry by deletion and reinsertion. Regards, Ype -- email at xs4all.nl From tdelaney at avaya.com Mon Oct 14 00:56:48 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Mon, 14 Oct 2002 14:56:48 +1000 Subject: Safe Psyco Message-ID: > From: aahz at pythoncraft.com [mailto:aahz at pythoncraft.com] > > That only works if you do *ALL* your bindings for your application in > one spot. The problem is that you only get ImportError once per > application invocation. That would be completely broken behaviour IMO. try: import abc except ImportError: print 'Error 1' try: import abc except ImportError: print 'Error 2' Python 2.2.1, 2.1.1, 2.0.1, 1.5.2, Jython 2.1.2 ---------- Run ---------- Error 1 Error 2 Nope - looks like it works as expected. Tim Delaney From "gkrohnXvolucris.8m.com".replace Mon Oct 14 23:31:40 2002 From: "gkrohnXvolucris.8m.com".replace (Greg Krohn ("X", "@")) Date: Mon, 14 Oct 2002 22:31:40 -0500 Subject: newbie: constructor question References: <3DAAF148.3060509@stacom-software.de> Message-ID: "Alexander Eisenhuth" wrote in message news:3DAAF148.3060509 at stacom-software.de... > Hallo everybody, > > is it possible to implement multiple constructors with different no. of arguments for one class ? > > >>> class A: > def __init__(self, a): > self._a = a > def __init__(self,a,b): > self._b = b > def __init__(self,a,b,c): > self._c =c > > >>>obj = A(12) > > Traceback (most recent call last): > File "", line 1, in ? > obj = A(12) > TypeError: __init__() takes exactly 4 arguments (2 given) > >>> > > -------------------------------- > That doesn't work. Any suggestions ? > > Thanks in forward > > Alexander Depending on what you are actually trying to accomplish, this might work: class ClassA: def __init__(self, **kwargs): for kw in kwargs: setattr(self, kw, kwargs[kw]) Use it like this: >>> objA = ClassA(a=12) >>> print objA.a 12 >>> objB = ClassA(a=12, b='Python') >>> print objB.a, objB.b 12 Python Disclaimer: If you are simply wondering about method overloading, than ignore this post. If you are wondering about creating attributes dynamically on initialization, than this post might help. From JXSternChangeX2R at gte.net Thu Oct 10 00:03:39 2002 From: JXSternChangeX2R at gte.net (JXStern) Date: Thu, 10 Oct 2002 04:03:39 GMT Subject: traceback and mySQL References: Message-ID: Cuz that's the error message, dummy, not the walkback. It's available in ss.exc_info()[0:1] J. On Wed, 09 Oct 2002 02:32:32 GMT, JXStern wrote: >Why does > > traceback.print_exc() > >capture the excellent mySQL error message: > > ProgrammingError: (1064, "You have an error in your SQL syntax >near 'eat my shorts' at line 1") > >but > traceback.extract_tb(sys.exc_info()[2]) > >does not list it? > >I want to capture all into a list for processing. > >I've tried some other variations without success. > >Thanks! > >Still a Python newbie, > (or I guess I would dive into the source) >Joshua Stern > > > >--------- source ----------- > >import os, sys >import traceback >import MySQLdb > >db = MySQLdb.connect(host="localhost", user="root", db="HMon") >cx = db.cursor() > >print "connected to database, got cursor, try exception" > >try: > cx.execute("eat my shorts") >except: > print "***in exception handler" > print sys.exc_info() > s = raw_input("->") > > tb = traceback.extract_tb(sys.exc_info()[2]) > > traceback.print_exc() > > s = raw_input("->") > print tb > >cx.close() >cx = None >db.close() >db = None > >--------- output follows ----------- > >connected to database, got cursor, try exception >***in exception handler >(, ><_mysql_exceptions.ProgrammingError instance at 0x0163C068>, >) >-> >Traceback (most recent call last): > File "C:/Hax/HMon/dbclasses/foo3.py", line 40, in ? > cx.execute("eat my shorts") > File "C:\PROGRA~1\Python22\Lib\site-packages\MySQLdb\cursors.py", >line 95, in execute > return self._execute(query, args) > File "C:\PROGRA~1\Python22\Lib\site-packages\MySQLdb\cursors.py", >line 114, in _execute > self.errorhandler(self, exc, value) > File >"C:\PROGRA~1\Python22\Lib\site-packages\MySQLdb\connections.py", line >33, in defaulterrorhandler > raise errorclass, errorvalue >ProgrammingError: (1064, "You have an error in your SQL syntax near >'eat my shorts' at line 1") >-> >[('C:/Hax/HMon/dbclasses/foo3.py', 40, '?', 'cx.execute("eat my >shorts")'), >('C:\\PROGRA~1\\Python22\\Lib\\site-packages\\MySQLdb\\cursors.py', >95, 'execute', 'return self._execute(query, args)'), >('C:\\PROGRA~1\\Python22\\Lib\\site-packages\\MySQLdb\\cursors.py', >114, '_execute', 'self.errorhandler(self, exc, value)'), >('C:\\PROGRA~1\\Python22\\Lib\\site-packages\\MySQLdb\\connections.py', >33, 'defaulterrorhandler', 'raise errorclass, errorvalue')] From mwh at python.net Tue Oct 22 07:09:35 2002 From: mwh at python.net (Michael Hudson) Date: Tue, 22 Oct 2002 11:09:35 GMT Subject: Changing completion key References: <3db45e23_1@news.arcor-ip.de> Message-ID: "Dave Richards" writes: > I recently discovered that idle and the python shell support name > completion with the combination Alt+/. As I use a German keyboard, that > means I have to press Alt+Shift+7 (/ is Shift+7), which is a little > unwieldy for my tastes. Is it possible to change this combo? I had a look > at the keydefs file in idle, but it's not in their. As far as I can see, > it's in readline.so. Um, I can't answer your question completely, but readline.so has nothing to do with completion in idle. If you're running python in a terminal readline.parse_and_bind("tab: complete") should do the obvious (once you've installed a completer). I'm sure there's a way to do it in idle, but I don't know it. Cheers, M. -- Slim Shady is fed up with your shit, and he's going to kill you. -- Eminem, "Public Service Announcement 2000" From ianb at colorstudy.com Tue Oct 8 16:38:06 2002 From: ianb at colorstudy.com (Ian Bicking) Date: 08 Oct 2002 15:38:06 -0500 Subject: [OT} How to un-GPL parts of a GPL'd module. In-Reply-To: References: Message-ID: <1034109487.2963.151.camel@dsl-65-184-205-5.telocity.com> There's a lot of crap in this discussion. From my understanding of the GPL, this is my opinion of what you can do: On Tue, 2002-10-08 at 07:33, Anton Vredegoor wrote: > how can I use a class or a function from a GLP'd module (cut-and-paste > style) in a module with BSD or public domain style release? You can cut and paste it in. This means that the *over-all* work falls under the requirements of the GPL, but you can apply a GPL-compatible license to the portions of the code you wrote (BSD, public domain, etc). At a later time if someone has a problem with the GPL, they can rewrite just the portion that's under the GPL. You should make clear that there are GPL components, and what those are, keeping copyright messages in tact, etc. You can also use a dual-license for your code, if you want to make it more explicit -- you own the copyright to the code you write, and you can license it however you choose, under multiple licenses if you choose. > I guess I could e-mail the author for permission but if I would have > to wait for them to answer, it would slow my coding process down to a > snail's pace, and there's always the possibility of the author being > unwilling. It's unlikely this would be a problem, but sometimes people are hard to contact or otherwise unwilling. If your ultimate intention were to integrate this into a proprietary piece of code, the author would probably not cooperate. If a permissive license is a sneaky way to achieve this, you could probably defraud the author into thinking otherwise, and then all you'd lose is your soul. But I don't think that's your intention -- lots of people change to permissive licenses to facilitate integration. > So that's not an option for me. I would rather rethink the problem and > start writing a new script. > > But here's where the problem begins. Having seen the algorithm it's > almost impossible for me to forget it and write code as if I had never > seen it. On the other hand, is it enough to just cut and paste, change > maybe a few variable names, credit the author for the original concept > in the sourcode, send some email to inform the author and go on with > life? Well, if you want to do it right, rewrite the module with no cutting and pasting, and without looking at the original module side-by-side with yours (though you don't have to try to forget what you saw). It's fine if you are using algorithms and ideas you got from reading the original module. You signed no NDA or other contract, and the GPL does not assert any rights over the algorithms used. It is entirely okay to get ideas from GPL code, and use them in whatever way you want. Ideas are not copyrighted -- implementations are. Also, no copyright is asserted over the API, and copying the module's API should be fine. I don't know where people are getting ideas that you are somehow tainted by having read this module. I like the GPL, I use the GPL, I agree with GNU philosophy, and that sort of coercion does not fit into its philosophy. They are projecting the sorts of coercions that proprietary companies use onto the GPL and the software in question, and that's simply not correct. > I know a lot of people rely on writing sourcecode for a living but I > have been unemployed as a programmer for so long know that the concept > of owning sourcecode or getting payed for producing it is completely > alien to me. I think I'll be writing free sourcecode till I die just > hoping some pieces of my code will survive into eternity. If someone > has a problem with that, hire me. Well, then I don't see any particular reason why you couldn't just use the GPL yourself, but that's up to you. Ian From anthony at interlink.com.au Tue Oct 15 02:43:06 2002 From: anthony at interlink.com.au (Anthony Baxter) Date: Tue, 15 Oct 2002 16:43:06 +1000 Subject: Problem with DNS resolver library -- pydns In-Reply-To: <3DAAFF95.7010502@verio.net> Message-ID: <200210150643.g9F6h6411086@localhost.localdomain> >>> VanL wrote > Hello, > > Has anyone used the pynds resolver libraries? I think I must be missing > something, because I'm just not getting out what I think that I should get. > > I'm trying to get a call getIP(domain, nameserver) that will return the > IP of domain, (or at least what that nameserver thinks the IP is). > > However, I'm instead getting nothing in the answers, just a bunch of > authority records. This means that the nameserver you asked isn't authoritative for the answer, and it's not willing to do the lookup for you. It's saying "I don't know, but these people do". -- Anthony Baxter It's never too late to have a happy childhood. From gumuz at looze.net Mon Oct 14 11:09:10 2002 From: gumuz at looze.net (Gumuz) Date: Mon, 14 Oct 2002 17:09:10 +0200 Subject: Python live CD with Tk References: Message-ID: <3daadc80$0$223$4d4ebb8e@news.nl.uu.net> > Yep. You should be able to just copy your Python installation + python22.dll + > maybe your favourite editor to CD. That's also how I distribute python apps > myself. ho ho, wait a minute! : D can you explain this process for me? thanx, gumuz From JXSternChangeX2R at gte.net Tue Oct 8 22:32:32 2002 From: JXSternChangeX2R at gte.net (JXStern) Date: Wed, 09 Oct 2002 02:32:32 GMT Subject: traceback and mySQL Message-ID: Why does traceback.print_exc() capture the excellent mySQL error message: ProgrammingError: (1064, "You have an error in your SQL syntax near 'eat my shorts' at line 1") but traceback.extract_tb(sys.exc_info()[2]) does not list it? I want to capture all into a list for processing. I've tried some other variations without success. Thanks! Still a Python newbie, (or I guess I would dive into the source) Joshua Stern --------- source ----------- import os, sys import traceback import MySQLdb db = MySQLdb.connect(host="localhost", user="root", db="HMon") cx = db.cursor() print "connected to database, got cursor, try exception" try: cx.execute("eat my shorts") except: print "***in exception handler" print sys.exc_info() s = raw_input("->") tb = traceback.extract_tb(sys.exc_info()[2]) traceback.print_exc() s = raw_input("->") print tb cx.close() cx = None db.close() db = None --------- output follows ----------- connected to database, got cursor, try exception ***in exception handler (, <_mysql_exceptions.ProgrammingError instance at 0x0163C068>, ) -> Traceback (most recent call last): File "C:/Hax/HMon/dbclasses/foo3.py", line 40, in ? cx.execute("eat my shorts") File "C:\PROGRA~1\Python22\Lib\site-packages\MySQLdb\cursors.py", line 95, in execute return self._execute(query, args) File "C:\PROGRA~1\Python22\Lib\site-packages\MySQLdb\cursors.py", line 114, in _execute self.errorhandler(self, exc, value) File "C:\PROGRA~1\Python22\Lib\site-packages\MySQLdb\connections.py", line 33, in defaulterrorhandler raise errorclass, errorvalue ProgrammingError: (1064, "You have an error in your SQL syntax near 'eat my shorts' at line 1") -> [('C:/Hax/HMon/dbclasses/foo3.py', 40, '?', 'cx.execute("eat my shorts")'), ('C:\\PROGRA~1\\Python22\\Lib\\site-packages\\MySQLdb\\cursors.py', 95, 'execute', 'return self._execute(query, args)'), ('C:\\PROGRA~1\\Python22\\Lib\\site-packages\\MySQLdb\\cursors.py', 114, '_execute', 'self.errorhandler(self, exc, value)'), ('C:\\PROGRA~1\\Python22\\Lib\\site-packages\\MySQLdb\\connections.py', 33, 'defaulterrorhandler', 'raise errorclass, errorvalue')] From dlloyd1104 at rogers.com Thu Oct 3 12:26:28 2002 From: dlloyd1104 at rogers.com (David Lloyd-Jones) Date: Thu, 03 Oct 2002 16:26:28 GMT Subject: Is the word "Python" copyrighted/trademarked? References: Message-ID: <3D9C6F57.5020801@rogers.com> Michael Stenner wrote: > > For example, "Windows" is trademarked by Microsoft. That is in more > common usage than "python" and also refers to a common object. > I'm not sure whether that has become true today. The original situation was that Microsoft were forced to take out their trade mark on "Microsoft Windows" because "Windows" was already taken by some other piece of software. I don't know whether Microsoft eventually succeeded in buying the other guys out. -dlj. From martin at v.loewis.de Thu Oct 3 03:58:38 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 03 Oct 2002 09:58:38 +0200 Subject: s.startswith(unicode) bug??? References: Message-ID: ewestra at wave.co.nz (Erik Westra) writes: > I'm running Python 2.2 (not 2.2.1) under Windows 2K, and have come > across the following bug. I was wondering if someone with 2.2.1 could > please check if it still happens -- if so, I'll post a bug report to > the Python SourceForce site. You'll get the same in 2.2.1. In 2.3a0, you get >>> "a".startswith(u"a") True Regards, Martin From loewis at informatik.hu-berlin.de Fri Oct 18 05:15:02 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 18 Oct 2002 11:15:02 +0200 Subject: Non-ascii characters in an MSDOS window References: <60Nr9.7295$Dr2.654838@news.ono.com> Message-ID: "Bartolom? Sintes Marco" writes: > I understand that Python is not to "blame", but Windows. So, > is it not possible to have the same output in a command line windows > and in a GUI window? Difficult. http://python.org/sf/612627 is a patch that makes sys.stdout accept Unicode strings on printing, and converts it into the encoding of the terminal. At the moment, you have the following options: A. Change the code page in the console with the chcp.exe. This requires to set the console font to Lucida Console (or another Unicode font). B. Always use Unicode to represent strings with accented characters. On printing them, determine the encoding of the output stream yourself: if sys.stdout.isatty() and isinstance(sys.stdout,file): # console. Unfortunately, there is no way to find out the encoding of # the console. You could try to parse the output of chcp. encoding = "cp850" else: encoding = "mbcs" Then encode the string with encoding, and put it onto sys.stdout. HTH, Martin From aahz at pythoncraft.com Thu Oct 10 12:30:11 2002 From: aahz at pythoncraft.com (Aahz) Date: 10 Oct 2002 12:30:11 -0400 Subject: Concrete classes -- stylistic question References: Message-ID: In article , Andrew Koenig wrote: > >On a few occasions I've wanted to define ``concrete classes'' -- >classes that are so simple that their structure is their interface. >For example, I might want a little class to hold (x, y) pairs. > >Of course, I can use a tuple, but then I have to remember the meaning >of each element. Moreover, if I want to have (x, y) pairs and (r, theta) >pairs, I don't have an easy way of checking which one is which in case >I use the wrong one by accident. > >Of course, I could define little classes like this: > > class xy(object): > def __init__(self, x, y): > self.x, self.y = x, y > > class rtheta(object): > def __init__(self, r, theta): > self.r, self.theta = r, theta You can also do the dirt-simple: class xy: pass class rtheta: pass foo = xy(); foo.x,foo.y = 1,2 I'm not recommending this, of course. You can also do the even more dirt-simple: class Record: pass foo = Record(); foo.x,foo.y = 1,2 It all depends on where you want your complexity to lie. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From amk at amk.ca Tue Oct 22 16:20:23 2002 From: amk at amk.ca (A.M. Kuchling) Date: Tue, 22 Oct 2002 15:20:23 -0500 Subject: How to use xmlrpc properly with Korean (non-ascii characters) References: <926d3924.0210211925.611dafe6@posting.google.com> <15797.38556.992131.538927@montanaro.dyndns.org> Message-ID: In article , Martin v. Loewis wrote: > I know. But would he actually enforce a copyright on "XML-RPC", on the > grounds that some implementation provides an extension? IOW: let him > follow his opinion, and follow your own technical views. Apparently not. See the extension at http://ontosys.com/xml-rpc/extensions.html, which points to a message from Winer on the XML-RPC mailing list. I've wanted for a long time, too, and would suggest adding it as an optional feature, enabled by a keyword argument to dumps(), and always accepted by loads() (following the guideline of being liberal in what you accept and conservative in what you send). --amk From jef.mangelschots at iname.com Wed Oct 2 23:35:37 2002 From: jef.mangelschots at iname.com (Jef Mangelschots) Date: Thu, 03 Oct 2002 03:35:37 GMT Subject: problem with nested dictionaries Message-ID: <3d9bbb01.40818890@news.genuity.net> Hi, in the below example, I want to create a dictionary of C2-objects. Each C2-object has a member-dictionary of C1-objects. In the sample code, I only insert values in the dictionary from object '3'. However, when I print out the list, the objects which I inserted under C2-object '3', appear to have been inserted in the other objects as well. What am I doing wrong (just started with python) I am using Python 2.2 #<< begin snip class C1: class_C1_name = "" def __init__(self, n): self.class_C1_name = n class C2: class_C2_name = "" a_list = {} def __init__(self, n): self.class_C2_name = n C2_LIST = {} C2_LIST['1'] = C2("C2_1") C2_LIST['2'] = C2("C2_2") C2_LIST['3'] = C2("C2_3") C2_LIST['4'] = C2("C2_4") C2_LIST['3'].a_list['5'] = C1("C1_5") C2_LIST['3'].a_list['6'] = C1("C1_6") C2_LIST['3'].a_list['7'] = C1("C1_7") for c2_name in C2_LIST: print "name: " + c2_name for c1_name in C2_LIST[c2_name].a_list: print " name: " + c1_name # >> end snip output: name: 1 name: 5 name: 7 name: 6 name: 3 name: 5 name: 7 name: 6 name: 2 name: 5 name: 7 name: 6 name: 4 name: 5 name: 7 name: 6 From nhodgson at bigpond.net.au Fri Oct 4 20:22:35 2002 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Sat, 05 Oct 2002 00:22:35 GMT Subject: Boa Constructor and CVS question References: Message-ID: Conrad Schneiker: > I've done some groups.google searching around and have seen recommendations > that the CVS version of Boa Constructor be used (since the .zip and > win32.exe downloads are way out of date). After some further searching, I > haven't found any concise documentation about how to go about doing this, > although there is a considerable abundance of marginally related information > to sift through. Is your problem with downloading from CVS or with the code once downloaded? CVS is something that you will just have to learn about as it is part of the assumed background knowledge for many open source projects. It is not sensible for every project to maintain their own CVS documentation. SourceForge hosts some articles about setting up CVS on various platforms: https://sourceforge.net/docman/?group_id=1 - section 6, CVS Instructions. > PPS: I've also run across questions (but not much in the way of answers) to > how PythonCard and Boa Constructor compare to each other. Have I missed a > thread somewhere? PythonCard is simple. It contains a simplified library for developing wxPython applications. Boa Constructor is complex and ambitious but uses the basic wxPython library. Neither is mature enough to have released a 1.0 version. Neil From pearu at cens.ioc.ee Thu Oct 31 12:48:20 2002 From: pearu at cens.ioc.ee (Pearu Peterson) Date: Thu, 31 Oct 2002 19:48:20 +0200 (EET) Subject: time (was Re: lists, performance..) In-Reply-To: Message-ID: On 31 Oct 2002, Alex Martelli wrote: > > > gabor wrote: > ... > > btw. is there a timing function in python? > > like 'time' in unix.. > > Module time in the Python standard library supplies a slightly > different functionality from Unix's time command. In particular > time.clock() returns "what time it is right now" -- CPU time on > Unix-ish systems, very accurate elapsed-time on Windows. So, to > time how long some operation takes, the standard idiom is: > > import time > > start = time.clock() > # the operations you want to time > stend = time.clock() > > print "It took %.2f seconds" % (stend-start) While measuring time for operations, it is possible that some other independent system/user process triggers swapping, for example, so that the measuring process gets less CPU, and therefore using "time.clock()" may give unrealistic timing results. To get more reliable timings, one has to run the measuring programs several times. And that may be time consuming. Another approach, at least under linux, would be to use "user time" that gives how much the measuring process acctually used CPU. This avoids the need to run the measuring programs several times as the result does not depend (too much) on how OS gives CPU time to different processes. Here follows a simple function for linux OSes that returns "user time" in jiffies: import os def jiffies(_proc_pid_stat = '/proc/%s/stat'%(os.getpid())): """ Return number of jiffies (1/100ths of a second) that this process has been scheduled in user mode. See man 5 proc. """ f=open(_proc_pid_stat,'r') l = f.readline().split(' ') f.close() return int(l[13]) so that the linux compatible idiom for timing would be: start = jiffies() # the operations you want to time stend = jiffies() print "It took %.2f seconds" % (100*(stend-start)) Thoughts? Pearu From hwlgw at hotmail.com Wed Oct 16 03:28:35 2002 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 16 Oct 2002 00:28:35 -0700 Subject: realtime design References: <013goa.m8c.ln@boundary.tundraware.com> <3DAC94DD.9070609@something.invalid> Message-ID: > [Greg Ewing] > > Will Stuyvesant wrote: > > > > But if the > > function call winds up doing cpu intensive stuff (for example > > pow()) at the C level then the Python threading timeout fails > > > > ... > > > > Performance is no issue, the > > simulation is allowed to be very slow, as long as it does > > implement the primitive correctly. > > In that case, just don't do anything intensive in C! > Keep it all in pure Python. I did hope that would be a reliable solution. But alas it is not: doing something like ``x = 2L * 2L * 32'' will send control to the C level for too long. For ordinary purposes it may not be much of a problem. But for a realtime simulator... ''' Magic is always the best solution -- especially reliable magic. ''' From owen at nospam.invalid Fri Oct 18 16:27:11 2002 From: owen at nospam.invalid (Russell E. Owen) Date: Fri, 18 Oct 2002 13:27:11 -0700 Subject: Idiom for 'the lesser of the two'? References: Message-ID: In article , Gordon Airport wrote: >There's got to be something simple I'm missing... >You obviously can't do >a < b ? a : b >and this >a if a < b else b >is a syntax error. I started playing with lambda functions >but I didn't have any luck there either. min(a,b,c...) works great. The "min" function is very flexible: - it works with any # of arguments - if there's just one argument and it is a list or tuple (or perhaps other kinds of collection) it will return the minimum value from the collection. If you really want to have the < in there somewhere, you could try taking advantage of the fact that x < y is either 0 or 1 and x or y is either x or y, thus: ((a < b) * a) or b probably does the job (yecch!). -- Russell From bfordham at socialistsushi.com Thu Oct 24 15:46:28 2002 From: bfordham at socialistsushi.com (Bryan L. Fordham) Date: Thu, 24 Oct 2002 15:46:28 -0400 Subject: IE events in win32com Message-ID: <3DB84E14.50908@socialistsushi.com> I know I'm missing something simple here, but I can't get this to work. Can someone give me a quick rundown on how I can write a class that will receive events from IE? Speficially, I'd like something that can tell when a link is clicked or a form submitted. I'm wanting to make something that can be used in testing: you navigate through some pages and record what you do, to be played back later in various forms to test that it all still works. I have the control part done, and it works great! That, combined with pyunit, has made my testing a breeze. But the creation of the tests is a bit time-consuming, and I certainly can't ask someone not familiar with coding to create their own. Sample code would be nice, but just a simple walkthru (or pointer to the appropriate doc page) should suffice. I've searched a bit but haven't found anything that I can get to work like I want. Thanks, --B From post at ironcitadel.com Thu Oct 31 00:27:45 2002 From: post at ironcitadel.com (ICWeb) Date: 30 Oct 2002 21:27:45 -0800 Subject: Share source code securely, inexpensively Message-ID: <99c3d303.0210302127.15dee024@posting.google.com> When doing source code development using offshore resources, or when team members are geographically distributed, this site offers a very inexpensive and secure approach. It can be used as an adjunct to a source code control system (manually) when a small team does not have access to a secure web based source code control repository. For professional and client relationship purposes this can be preferable to emailing code around or using a "free" document repository which is insecure. There is a good site, www.ironcitadel.com, which permits the secure storage and communication of documents. Unlike most "free" sites, this site is: (a) Securely encrypted - all document uploads/downloads are 128bit SSL encrypted; all documents stored are encrypted using the new Rinjdael algorithm which has replaced Triple-DES as the US government high security standard. (b) Has a fax feature - if you just have a hardcopy of a document, say a handwritten note, you can fax it in and the document is received by a fax server, converted to TIFF format, and stored encrypted. (c) All documents can be downloaded (also uploaded) just via a standard web browser - no special software required. (d) Cost is dirt cheap - $5/month and you don't even pay until the end of your first 30 days. Considering what you get, that is CHEAP! If you want to communicate securely with someone, just set up an account and give the login/password to a single other person. All communications are now highly secure. If you want to store secure information remotely, where all the information is at a remote facility that is encrypted, then www.ironcitadel.com is the place. From mwh at python.net Tue Oct 1 10:17:07 2002 From: mwh at python.net (Michael Hudson) Date: Tue, 1 Oct 2002 14:17:07 GMT Subject: How do we explain clp to newcomers? References: Message-ID: claird at lairds.org (Cameron Laird) writes: > Is there a canonical page, presumably at www.python.org, or, more > specifically, the Wiki, that answers the question, "What do you > mean, 'post my question to the Usenet comp.lang.python newsgroup'?"? > If there isn't one already, I'll make one for the Wiki. I'd like > to avoid the labor, of course. http://www.python.org/psa/MailingLists.html#clp ? Not the most obvious location, to be sure. Cheers, M. -- Programming languages should be designed not by piling feature on top of feature, but by removing the weaknesses and restrictions that make the additional features appear necessary. -- Revised(5) Report on the Algorithmic Language Scheme From max at alcyone.com Sun Oct 20 23:20:04 2002 From: max at alcyone.com (Erik Max Francis) Date: Sun, 20 Oct 2002 20:20:04 -0700 Subject: How to get the minor and major device numbers with os.stat ? References: Message-ID: <3DB37264.2B94F6A@alcyone.com> Alain Tesio wrote: > map(lambda h: eval("0x%s" % h) ... As an aside, a much better way of converting a string representing a hexadecimal number to an int is simply with the int function/type: int(h, 16) The version you use above is potentially exploitable by a third party, particularly since you don't specify an absolute path to stat, so potentially some third-party version could be executed which might do something you wouldn't expect. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ A good indignation brings out all one's powers. \__/ Ralph Waldo Emerson Church / http://www.alcyone.com/pyos/church/ A lambda calculus explorer in Python. From gerhard.haering at gmx.de Sat Oct 5 20:31:30 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 6 Oct 2002 00:31:30 GMT Subject: Quick question on mysql-python References: <3d9f74b2$1_7@goliath.newsgroups.com> Message-ID: mongo57a at comcast.net wrote in comp.lang.python: > Just finished downloading Python 2.2.1. Appears to be working fine. To > complete the installation, I downloaded and executed > MySQL-python-0.9.2-1.i386.rpm. MySQLdb shows up in > /usr/lib/python2.2/site-packages (as it should). When I attempt to import > MySQLdb I get the following error: > > libmysqlclient.so.9: cannot open shared object file: no such file or You didn't install the MySQL client libraries or got a version with a different library number installed. Check if you have any libmysqlclient*: $ ls /usr/lib/libmysqlclient* If there is none, install the relevant RPM from your distribution or from mysql.com. If there is such a library, but with a different library number, such as 8, you can try to to symlink to it, so that you have a libmysqlclient.so.9 that points to libmysqlclient.so.{whatever} HTH, -- Gerhard From aleax at aleax.it Thu Oct 31 15:15:17 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 31 Oct 2002 20:15:17 GMT Subject: AW: The rules of reference References: Message-ID: Gerson Kurz wrote: ... > from a import * ... > reimport a. That should work, right? Wrong. Rule of thumb: wnenever you see a statement of the form: from import * the smart bet is that things WON'T work. If all Pythonistas forgot suddenly about the existence of statement 'from', and by the same magic all existing Python sources (including those in printed form) were changed to use statement 'import' instead, I think the average quality of Python code now existing and still to be written in the future would be enhanced. With that wretched from statement you did the equivalent of: import a as temporarynameotherwisenonexisting num = temporarynameotherwisenonexisting.num print_num = temporarynameotherwisenonexisting.print_num del temporarynameotherwisenonexisting When you later bind something else to your num (__main__.num), that binding has no effect whatsoever on the attribute similarly named 'num' in other modules. And the print_num's reference to its own global 'num' is to the entry in print_num.func_globals['a'], of course. I.e., it's in another module, and any binding you may make or unmake to names in module __main__ will not affect it. Alex From wilk-spamout at flibuste.net Sun Oct 20 04:57:54 2002 From: wilk-spamout at flibuste.net (William) Date: 20 Oct 2002 10:57:54 +0200 Subject: Speeding up a script -- looking for ideas References: Message-ID: <87fzv15vxp.fsf@flibuste.net> Richard Bow writes: > I'm hoping to get some hints for significantly speeding up the below > script. I've found 43 integers between 1 and 1,000,000 that satisfy the > condition, and would like to push on toward 10,000,000 in hopes of finding > an integer for which there are 3 pairs. Of course, another reason for > asking is to learn more Python from you guys. hi, without looking at your algorithme, it's typical think where psyco will help you : without psyco : [(13832, 2, 24), (13832, 18, 20)] Time's up! 16.6103349924 seconds have elapsed EEEEEEEEEnnnnnnnnnnddddddddd with psyco : [(13832, 2, 24), (13832, 18, 20)] Time's up! 2.99753201008 seconds have elapsed EEEEEEEEEnnnnnnnnnnddddddddd http://psyco.sourceforge.net/ i try with python2.2 and last psyco CVS on my pII350 import psyco start = 10000 end = 20000 def f(): for n in range(start, end + 1): crn = int(n**(1/3.0)) + 2 # because of float probs, add 2 to be sure list = [] # crn is large enough for a in range(1,crn): a3 = a ** 3 for b in range(a,crn): b3 = b ** 3 if a3 + b3 == n: list = list + [(n,a,b)] if len(list) >= 2: # e.g. [(1729, 1, 12), (1729, 9, 10)] and # [(994688, 29, 99), (994688, 60, 92)] print list print psyco.bind(f) import time t1= time.time() f() t2 = time.time() print "Time's up!", t2 - t1, "seconds have elapsed" print "EEEEEEEEEnnnnnnnnnnddddddddd" -- William Dod? - flibuste.net http://wikipython.tuxfamily.org From mark.charsley at REMOVE_THIS.radioscape.com Tue Oct 1 06:32:00 2002 From: mark.charsley at REMOVE_THIS.radioscape.com (Mark Charsley) Date: Tue, 1 Oct 2002 11:32 +0100 (BST) Subject: Decimal arithmatic, was Re: Python GUI app to impress the boss? References: Message-ID: In article , chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) wrote: > Usually, in the "canned" systems I've seen, those 3 for a > buck deals are supported by allowing three to five decimal > places rather than just two for amounts. Results come out > much as you are expecting there. The system a previous company wrote said that "if they've bought 3 40p items these give them a discount of 20p". All nice integers: which, given a) the checkouts had a slow CPU, limited memory and no FPU b) the FP software library was huge and slow was a good thing. -- Mark - personal opinion only, could well be wrong, not representing company, don't sue us etc. etc. From martin at v.loewis.de Mon Oct 7 00:47:47 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 07 Oct 2002 06:47:47 +0200 Subject: Windows NT remote registry import References: <3D9DF683.1080905@nospam.org> Message-ID: logistix at zworg.com (logistix) writes: > Yeah, believe it or not, there is no "default" way to remotely import > .reg files to remote machines. I believe that not. On Windows NT+, it is possible to programmatically access a remote registry: notice, not the .reg file, but the registry; this requires the Remote Registry Service to run. On the API level, this is done through RegConnectRegistry. With Python's _winreg module, you get that as _winreg.ConnectRegistry. Regards, Martin From aleax at aleax.it Wed Oct 2 04:53:29 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 02 Oct 2002 08:53:29 GMT Subject: patch in Python? References: <7xit0l3koi.fsf@ruckus.brouhaha.com> Message-ID: Gerhard H?ring wrote: ... >> Looking at the docs I don't see any features that gmpy doesn't have. >> I think it would be better to use gmpy, which is widely used, has >> assembly language optimizations for many cpu's, etc. > > Probably, except one of the requirements is a BSD-ish license, as in the > end this will be used for the NUMERIC type of pyPgSQL. If it's going to > be useful for other purposes, that's a nice side-effect. Both the "assembly language optimizations" and the LGPL license, of course, are due to the underlying GMP library (which my gmpy just wraps for Python consumption). I'm not 100% sure I'm _required_ to apply LGPL to gmpy (i.e., I'm not sure whether it's a derived work of GMP, thus needing LGPL, or just an application that links with GMP, in which case I could license gmpy any which way), but I _am_ quite sure I don't need the hassle and aggravation of fighting against the folks who provided GMP (folks to which I feel quite grateful) should they decide to disagree with my interpretation. In other words, were it just for me, I'd love to license gmpy in some more Pythonic wise, but I'm not prepared to handle any legal and/or political clash that might possibly ensue (color me yellow...). Besides, even if gmpy were to be BSD-licensed, the underlying GMP would no doubt remain LGPL, so, changing gmpy's license would be rather useless per se (trying to rationalize my cowardice here...:-). Alex From TOGLIMIcuni at programmazione.it Fri Oct 18 20:30:25 2002 From: TOGLIMIcuni at programmazione.it (Antonio Cuni) Date: Sat, 19 Oct 2002 00:30:25 +0000 Subject: Automatic constructors Message-ID: <239qoa.v93.ln@anto.cuni.lan> In writing my code I often need to write __init__ methods like this: def __init__(self, x,y,z): self._x = x self._y = y self._z = z The number of fields and their names vary from class to class, of course; I'd like to find a way for automatize this process: by now I have write this: def constructor(*fields): numFields = len(fields) def __init__(self, *args): if len(args) != numFields: raise TypeError( '__init__ takes exactly %d arguments (%d given)' % (numFields + 1, len(args)) ) for field, arg in zip(fields, args): setattr(self, '_%s' % field, arg) return __init__ So I can write: class foo: __init__ = constructor('x', 'y', 'z') It works, but I don't like to use strings to specify fields name: is there any way to use "plain" names? Eg: __init__ = constructor(x,y,z) ciao Anto -- "Computer science is not about computers any more than astronomy is about telescopes." -- EW Dijkstra From tundra at tundraware.com Wed Oct 30 17:20:07 2002 From: tundra at tundraware.com (Tim Daneliuk) Date: 30 Oct 2002 22:20:07 GMT Subject: anygui Question Message-ID: <6nlppa.5pg.ln@boundary.tundraware.com> I'm new to GUI programming under Python so forgive me if this is a dumb question, but I cannot seem to find anything on Google or the project site which answers... How does one go about changing fonts or getting font metrics from within an 'anygui' object? I want to be able to set the default font in a platform independed way. Is this possible? -- ------------------------------------------------------------------------------ Tim Daneliuk tundra at tundraware.com From vtail at yandex.ru Wed Oct 2 04:33:53 2002 From: vtail at yandex.ru (vtail) Date: 2 Oct 2002 01:33:53 -0700 Subject: mx.ODBC.Windows - execute() parameters substitution strange behaviour. Message-ID: <9ff6b66.0210020033.4a746ae@posting.google.com> Greetings again, Could someone please explain me why the following simple script failes on 4th execute? Or is there any simple way to find which sql string execute() really send to sql server after receiving two parameters. I'm running: mx.ODBC.Windows 2.0.5 Python 2.2.1c2 (#33, Mar 26 2002, 13:04:18) [MSC 32 bit (Intel)] on win32 Microsoft SQL Server 2000 Windows 2000 Any help will be appreciated. Victor. ===>test_sql.py import mx.ODBC.Windows DB = mx.ODBC.Windows.Connect('db-companies') C = DB.cursor() sql = """select newsid from news where newsid between 1 and 2""" C.execute(sql) print 'ok' sql = """select newsid from news where newsid between ? and ?""" C.execute(sql, (1, 100)) print 'ok' sql = """select newsid from news where newsid in (select newsid from news where newsid between 1 and 100)""" C.execute(sql) print 'ok' sql = """select newsid from news where newsid in (select newsid from news where newsid between ? and ?)""" C.execute(sql, (1, 100)) print 'ok' <=== end of test_sql.py ===> result ok ok ok Traceback (most recent call last): File "", line 21, in ? mxODBC.ProgrammingError: ('37000', 0, '[Microsoft][ODBC SQL Server Driver]Syntax error or access violation', 4469) <=== end of result From marklists at mceahern.com Thu Oct 3 18:37:17 2002 From: marklists at mceahern.com (Mark McEahern) Date: Thu, 3 Oct 2002 17:37:17 -0500 Subject: how to get rid of html tags In-Reply-To: Message-ID: > Thanks a lot. It worked well if the tags are on the same line. > But if the tag is broked to a few lines, it will not work. > eg. > > > otherCOMServer := COMServer.returnOtherCOMServer(); > > > IF ISCLEAR(otherCOMServer) THEN MESSAGE('otherCOMServer is clear'); > > > <---- > > > > > > Definition of ISCLEAR (extracted from MS Navision help): > > > The return value is TRUE if: > > > -the automation variable has not been created. See CREATE. > > > -the automation variable has been cleared. See CLEAR. > > > -the automation variable has been assigned NULL by an automation > > > server. > > > > > > I thing that in this case I must assign NULL to the otherCOMServer > > > variable in order to keep the otherCOMServer variable CLEARED. > > > What must I return from "COMServer.returnOtherCOMServer()" method to > > > assign NULL? > > > I have tried: > > > return None > > > return wrap(None) > > > return 1==0 > > > return > > > > > > but without success. The environment responds "data type not > > > supported". > > > > None is the way to do this. What responds "data type not supported"? > > Have you registered your object for debugging and seen the output? > > There may be a traceback printed. > > > > Mark. > > After executing "return None" Navision responds "This data type is not > supported by C/SIDE". > > The debugging output is correct: > > OutMessage created 0x02406260> > Object with win32trace dispatcher created > (object=) > Returning wrapped > in _Invoke_ with 1000 1024 1 ( 0x1caad68>,) > in _Invoke_ with 1002 1024 1 (1000,) > returning None > > The invoke with 1002 is the call to the method that returns NULL or an > object after 1000 ms of timeout. In order to discover the problem I created a simplistic method in Visual Basic and the same in python. Here is the method in VB: Public Function AMethod() as Object Set AMethod = Nothing End Function Here is the method in Python: def AMethod(self): return # I also test with return None The type library look identical for the both methods. And the result if I invoke the methods from python is "None" in both cases, but if I invoke the methods from C/SIDE (Navision) the behaviour of the VB method is as expected, but the python object returns an error message saying that this type of data is not supported by C/SIDE. Since I don't know the internals of python COM implementation, can anyone help me to discover the problem? Mark, I suspect there must be a bug in the python COM implementation, because of the different behaviour of the VB and the python method. From donkan7 at yahoo.com Sun Oct 20 06:50:22 2002 From: donkan7 at yahoo.com (Richard Bow) Date: Sun, 20 Oct 2002 03:50:22 -0700 Subject: Speeding up a script -- looking for ideas References: <3DB26BA3.DEB4722E@alcyone.com> Message-ID: Erik Max Francis wrote in news:3DB26BA3.DEB4722E at alcyone.com: > One obvious optimization is that you're using range with huge values, > which is going to be expensive -- range returns a list, so calling it > with large values will create an enormous list, which is wasteful if all > you plan on doing is enumerating it. Try using xrange, or iterating > manually instead. Well, range does return a list, but the list is reinitialized to [] for each n, so it never has more than 2 (and hoping for 3) objects (so far, i.e, up to n = 1,200,000). Could you explain what you mean by "iterating manually"? I'll take a look at xrange. Thanks, Richard Bow From martin at v.loewis.de Fri Oct 4 17:52:57 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 04 Oct 2002 23:52:57 +0200 Subject: sys.settrace for all threads References: <8a6ba1da.0210041339.323e22e3@posting.google.com> Message-ID: richie at entrian.com (Richie Hindle) writes: > Is there a cleaner and more future-proof way of doing this? No. Your approach won't work very well, either, since threads can come out nowhere: A C module may create threads, and just temporarily enter Python from the thread. If you want to hook into all threads, you need to hook into PyThreadState_New and friends. If you want a future-proof way, I recommend to create a per-interpreter state global, and hook into all places that use the trace function. You might want to try writing a PEP to generalize this feature. Regards, Martin From anandpillai6 at yahoo.com Wed Oct 9 04:20:50 2002 From: anandpillai6 at yahoo.com (Anand) Date: 9 Oct 2002 01:20:50 -0700 Subject: Function GetData() in wxImage References: <41c203e.0210070707.15595d94@posting.google.com> Message-ID: <41c203e.0210090020.2bc13985@posting.google.com> Hi Mike, Thanks for help Could you kindly point me to resources where I can learn about python multithreading ? Anand "Mike C. Fletcher" wrote in message news:... > http://wiki.wxpython.org/index.cgi/WorkingWithImages > > BTW: It's generally more efficient to use the wxPython users mailing > list for these kinds of questions. > > Enjoy, > Mike > > Anand wrote: > > >Hi > > > > I am writing an image viewer in wxPython using the wxImage class. > >I want to manipulate the image data for effects. I tried to use the > >GetData() method of the wxImage class which returns a const char *(wxWindows > >documentation). > > > > How do I manipulate this object. Is it a python object or a C unsigned char * > >stream ? Can i apply std 'C' calls on it or do I need to use methods of > >python ? > > > >Concerned code... > > > > def myfunc: > > > > ... > > self.img = wxImage(fileName) > > chunk = self.img.GetData() # What is this chunk ? > > pass > > > > > >Thanks > > > >Anand > > > > From list-python at ccraig.org Sat Oct 19 12:50:59 2002 From: list-python at ccraig.org (Christopher A. Craig) Date: 19 Oct 2002 12:50:59 -0400 Subject: repr(x) == repr(y) <=> x == y AND eval(repr(x)) == x In-Reply-To: <200210182021.NAA27717@mail.arc.nasa.gov> References: <3DB06146.EB1BFA8F@alcyone.com> <200210181956.MAA22503@mail.arc.nasa.gov> <200210182021.NAA27717@mail.arc.nasa.gov> Message-ID: Chad Netzer writes: > On Friday 18 October 2002 12:56, Chad Netzer wrote: > > > Furthermore, a straightforward trick is to wrap your object in a single > > element tuple, and use that as the key. It is a much *MUCH* better > > solution than monkeying with 'eval( repr( x ) )'. > > Well, upon further investigation, it appears this trick's main fault is > that it is bollocks. It won't work: > > a = {} > b = {} > a[ (b,) ] = 1 > > I thought the above would work, but it seems not to. Anyone care to explain > why (I'm off to look in the reference manual, in the meantime.) I don't think it's there explicitly, but it is sort of hinted at. First off, the spec does not require all immutable objects to be hashable (and tuples containing mutable objects are an examle of some that aren't). But this passage is more important: "The only required property [for hashing] is that objects which compare equal have the same hash value; it is advised to somehow mix together (e.g., using exclusive or) the hash values for the components of the object that also play a part in comparison of objects." Tuple hash is defined (in tupleobject.c) as def hash(t): x = 0x345678 for ob in t: y = hash(ob) # note this line in particular if y==-1: return -1 x = (1000003*x) ^ y x ^= len(t) if (x == -1): return -2 return x which is, of course, recursive on the elements of the tuple. As such, tuples containing mutable objects are not hashable. -- Christopher A. Craig "Tragedy is when I cut my finger. Comedy is when you fall in an open sewer and die." Mel Brooks. From aahz at pythoncraft.com Mon Oct 14 20:08:16 2002 From: aahz at pythoncraft.com (Aahz) Date: 14 Oct 2002 20:08:16 -0400 Subject: realtime design References: Message-ID: In article , Will Stuyvesant wrote: > >I am trying to come up with a method to run a function in such a >way that the whole thing will take at most x milliseconds, with x a >reasonable value like 200. If the function is not finished by that >time, a default value should be used. If the function *does* finish in >time, the return value of the function should be used. The main point >is that the calling program should be able to continue with the next >statement after x milliseconds. And it would be nice if the called >function is interrupted or something if it has not finished, so it will >not eat CPU resources. That last part isn't really possible, not if there are statements that depend on external connectivity like I/O. But it's certainly possible to make your main loop work the way you want: have your function put its result on a Queue.Queue. In your main function, time.sleep() for however long it's supposed to, then do a non-blocking get() on the queue. If the get() fails, do whatever's appropriate. This gets trickier if your main program needs to be responsive during the 200ms, but it's not impossible. If your function is running in a loop, have it check the time at the top or bottom of the loop and exit early if it takes too long. That's not perfect, but it should keep your program from consuming endless resources. >and-now-I-am-thinking-about-how-to-kill-a-Windows-process-ly y'rs Not cleanly. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From markw at markwatson.com Sat Oct 5 13:11:08 2002 From: markw at markwatson.com (Mark Watson) Date: Sat, 05 Oct 2002 17:11:08 GMT Subject: Commercial: Python part of speech tagger, text categorization Message-ID: Greetings, I have released my NLP tools in Python versions (originally written in Common LISP). If you are interested, check out the commercial products page at: http://www.markwatson.com Thanks, Mark -- Mark Watson, consultant and author: www.markwatson.com -- Open Source and free web books -- Commercial products with live web demos From tdelaney at avaya.com Sun Oct 13 21:50:01 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Mon, 14 Oct 2002 11:50:01 +1000 Subject: Monitor module imports? Message-ID: > From: Avery Andrews [mailto:andrews at pcug.org.au] > > Does anyone know an easy way to record the modules that a > Python program > is loading - the profiler records the Python ones but not extension > modules. What I'm interested is the possibility of producing > 'MiniPy's > that contain only the stuff needed to run a given application. Have a look at the __import__ builtin. Tim Delaney From wweexxsseessssaa at telusplanet.net Sat Oct 12 19:57:07 2002 From: wweexxsseessssaa at telusplanet.net (John Hall) Date: Sat, 12 Oct 2002 23:57:07 GMT Subject: Mendelbrot Fractal Generation References: Message-ID: On Sun, 13 Oct 2002 01:35:08 +0200, Conatic wrote: >I want to study a mendelbrot fractal with python. You might do better searching for Mandelbrot rather than Mendelbrot but if using Google you probably know that already. Oh for a great slice of Almond Bread in a Viennese cafe! -- John W Hall Calgary, Alberta, Canada. "Helping People Prosper in the Information Age" From donkan7 at yahoo.com Wed Oct 16 10:37:48 2002 From: donkan7 at yahoo.com (Richard Bow) Date: Wed, 16 Oct 2002 07:37:48 -0700 Subject: How to print an integer with commas; E.g., 3,056,789 References: <20021016120633.22956.56736.Mailman@mail.python.org> Message-ID: John Arundel wrote in news:mailman.1034773342.23488.python-list at python.org: > How about: > > def commaise(seq): > if len(seq) <= 3: > return seq > else: > return "".join(commaise(seq[:-3]) + ',' + seq[-3:]) > >>>> commaise("3056789") > '3,056,789' I see that this works well, but I don't understand it. I _think_ I understand join(), but how is the looping accomplished? I suspect the "" in the same line is what does this, but could you or someone explain a bit? Thanks, Richard Bow From peter at engcorp.com Wed Oct 2 08:45:04 2002 From: peter at engcorp.com (Peter Hansen) Date: Wed, 02 Oct 2002 08:45:04 -0400 Subject: [ANN] screensaver References: Message-ID: <3d9aea4b$1@news.sentex.net> Anton Vredegoor wrote: > On Wed, 2 Oct 2002 00:06:34 -0500, "Chris Gonnerman" > wrote: > >>Tried it (Win98, Python 2.1), didn't work: > > Someone else posted a few fixes. I can't test if it works with Python > 2.1 but I have made some modifications and uploaded a new version. > > Taking just a very short look at your posting history I find it hard > to believe you couldn't make it work. So what did you do, throw it > away, disgusted with it? Or did you make it work? But then again why > didn't you post the fix? Maybe there's some other problem with it, > please inform me. I also would like to know if it works now. Wow... *great* attitude! Makes _me_ want to download the program and try it out right away... Take a chill pill, Anton. Or better yet, download a recent release (it's not hard) and test out the stuff before you post it. -Peter From cnetzer at mail.arc.nasa.gov Tue Oct 1 17:11:38 2002 From: cnetzer at mail.arc.nasa.gov (Chad Netzer) Date: Tue, 1 Oct 2002 14:11:38 -0700 Subject: Tkinter problem In-Reply-To: References: Message-ID: <200210012111.OAA07417@mail.arc.nasa.gov> On Tuesday 01 October 2002 13:23, Newt wrote: > Hi, > > Can anyone explain why the following code runs strangely. When I run > it, it seems as if the setrace routine is called regardless, even > before the main form has been displayed. That is because it does exactly what you told it to do. You are calling the setrace function, rather than asking that it be used as a callback. "setrace" is the function object, and can be used as a callback binding; setrace() is the called function, which returns the results of the call (in this case, the None object) So, change this line: listr.bind('',setrace(root, listr, lblr )) to this: listr.bind('',setrace_callback ) and introduce this new function which is called when the button is pressed, and then calls your function with the proper arguments: def setrace_callback( *crap ): setrace( root, listr, lblr ) return Now, pressing Button-1 calls the 'setrace_callback' function (with some event handling arguments that you don't use; See Tk manual for more info), which then calls your 'setrace' function to do the work. NOTE!!! This only works as is because you are using globals (since your program is supplied is written outside of a class or function), and so 'setrace' can see these globals. This is really bad form. Often, people would use a "lamda" anonymous function to bind up the arguments to 'setrace' at declaration time, or use a method called 'currying' (which I prefer). And if this all took place inside a class, your arguments could then be state variables. See the ASPN Python Cookbook to learn more about how to "curry" in Python. Or better yet, make this all a class, and bind a class method to the Button-1 press. -- Chad Netzer cnetzer at mail.arc.nasa.gov From cerdil at ttnet.net.tr Tue Oct 29 12:38:05 2002 From: cerdil at ttnet.net.tr (shawn Erdil) Date: Tue, 29 Oct 2002 19:38:05 +0200 Subject: how to point to right version of python? Message-ID: <005801c27f71$f0d10f60$6501a8c0@coco> i want to install the new mailman 2.1b4 version, but the configure command cannot find the required 2.1 python interpreter, i have installed the 2.1 version of python from an rpm, it s there in usr/bin/python but my systems sees the version 1.5 as the default interpreter .the older version of ma,ilman works fine with python 1.5 what can i do ? should i uninstall the python 1.5 version? rename the 2.1 version? show the correct path on the configure script? thank you shawn Erdil. ?agan Erdil. Digitiy web solutions e-z banner internet media company Techifirm Retail solutions www.anketx.com www.digitiy.com www.e-zbanner.com www.techifirm.com www.e-zbanner.com/bannerspace Digitiy e-zbanner live webcam http://www.anketx.com/cam/webcam.htm Mobile: +90 532 2637999 Direct: +90 212 3515656 Fax: +90 212 3513150 Address:?evre sitesi 15- D/9 Akatlar,Istanbul- Turkey 80630 -------------------------------------------------------- Digitiy/ E-zbanner hakkinda: Digitiy/ e-zbanner , web projeleri ve internet reklamciliginda ??z?m saglayan teknoloji markalaridir.Digitiy, sirketinizin internet stratejisi, marka imaji ve e-ticaret konusunda ??z?mler saglar. E-zbanner, internet reklamciligi ve interaktif pazarlama konusunda ??z?m saglar.E-zbanner, web banner network, e-mail network,web promosyonlari ve e-zbanner site ?lc?mleme, kreatif tasarim guruplarindan olusur. -------------- next part -------------- An HTML attachment was scrubbed... URL: From aleax at aleax.it Mon Oct 7 11:22:28 2002 From: aleax at aleax.it (Alex Martelli) Date: Mon, 07 Oct 2002 15:22:28 GMT Subject: Merging lists has made my brain hurt. References: <3D9B1953.3030109@moving-picture.com> Message-ID: Thorsten Kampe wrote: ... > I meant this: in a real world scenario it's often not practical to > say: use this program, but beware, it's relies on an input without > duplicates or relies on all items to be hashable, because you can't > tell in advance whether the conditions will be met. Right, but you can at least check whether they're met, and fall back to less-efficient means if they aren't. >> If you don't care about duplicates you're much better off >> normalizing first, and if you care about COUNT of duplicates but not >> ordering (i.e., a bag) you're generally still better off normalizing >> first. > > What do you mean exactly by "normalizing"? Sorry, I was sloppy here -- I mean "moving to a better way to represent sets" (dicts, or Sets in Python 2.3). Even for bags, there are more usable representations than "sequences with repetitions in random order", btw -- see further. > Sorry, I wrote quite imprecisely. My interpretation of 'tuple' was > contradictory to the traditional mathematical meaning 'order and > repetition counts' but it meant "repetition counts, order doesn't". So what you want are 'bags'. OK by me, but "you can't tell in advance whether the conditions will be met" (your words!) ALSO applies -- and here it's quite a bit worse than wrt duplicates or hashability, because you CAN'T check whether this "condition" matters... if you're fed lists, there's no way to know whether those lists' items' ordering are considered meaningful within the given application program, or no. >> What you mean by "corresponding" there is rather mysterious to me, >> but wouldn't it mean "same item in the SAME position"? > > I was asking myself: what would be a sensible generalization for the > common set operations (intersection, union, etc.) for tuples? For BAGS (order meaningless), the natural representation is as a mapping item-># of occurrences, and the natural generalization of intersection and union use min and max (the natural gener. to integers of and and or on booleans!) of course equating the mapping to 0 with absence from the bag. > Precisely: what is (or should be) the intersection of [2, 2] and [2, > 2, 2]? Treat them as sets? Then the result is '[2]'. > > Treat them as tuples? The most common algorithm is: for each item in > first seq: if it is in second seq, then add it to the intersection. > > But then: > intersect([2, 2], [2, 2, 2]) = [2, 2] > intersect([2, 2, 2], [2, 2]) = [2, 2, 2] > > You "connect" the "corresponding" items (the first '2' in seq1 with > the first in seq2, the second '2' in seq1 with the second '2' in seq2, > the third '2' in seq1 with the third '2' in seq2 ... *ooops*) > [1, 2, 2, 2, 3] > | | | | <- "non proportional font required" > [0, 1, 2, 2, 3, 4] > > So the intersection should contain all the items that can be > "paired"/"connected". The last '2' of seq2 has no 'partner' so it > shouldn't be part of the intersection. If order doesn't matter, then it does matter WHICH '2's of seq2 are or aren't part of the intersection, of course -- which is part of why representing bags by mappings is so much more natural than representing them by sequences with repetitions in random order. If you ARE constrained to use sequences (because mappings are forbidden, e.g. by the non-hashable nature of items in a context where you're only allowed to use dicts for mappings) I think you're still better off simulating a mapping than fighting with the in-natural representation of bags as sequences with repetitions in random order -- when you don't care about the order, it just gets in the way! So, if I had to support non-hashables, I would fall back to a representation as a list of two-items lists, meaning item/count. I would actually wrap that up in all the trappings of a mapping, and use dicts normally, falling back to the inefficient linear representation only for non-hashable items. In many cases, I could have a dict for most stuff, with a small "look-aside list of pairs" just for those few items that are non-hashable. Another usable alternative is sometimes to make non-hashables into hashables, e.g. via pickle (costly, to be sure, but it can make the differene between O(N) and O(N squared) work). But I'm getting sidetracked here, sorry. >> But it's NOT -- [1, 2, 3, 2] != [2, 1, 2, 3]. You're losing >> information, specifically order information. A correct definition >> should be: >> >> def intersect(seq1, seq2): >> return [ x for x, y in zip(seq1, seq2) if x == y ] > > This is correct for "if first item of seq1 = first item of seq2" but I > had never use for such an "intersection". I could not see any "real > use" for intersect([1, 2, 3], [3, 1, 2]) = []. "What songs are in the same position in our hit list as they were last week?" is an often-answered question on radio programs that give "hit parades", for example. "none of them" is a valid answer. If order is meaningful (and if you're using sequences it should normally be), then throwing order-information away is a very suspect design decision. >> If what you want is to treat sequences as BAGS, then they're better >> represented by dicts again -- order is the only information present >> in a list and not in a dict, [...] > > Well, usually not: >>>> {1: 2, 1: 2} == {1:2} > 1 > >>>> [2, 2] == [2] > 0 Not sure what you mean here. If you're representing bags by dicts in this way, sequence [2, 2] is represented by dict {2: 2}, i.e., "item 2 is present twice". Here you don't lose information just because you consider the two occurrences indistinguishable. More often you do, e.g. there are three different ways to represent baf {1:2, 2:1} as a sequence: [1,1,2], [1,2,1], [2,1,1]. Having many ways to represent what is to be considered the "same" thing to all intent and purposes should raise suspicion off the bat. It doesn't matter that you can write dict {1:2} (representing the same bag as [1,1] in sequence-representation) with many different dictionary-display strings -- that's just an artifact of the parser, not inherent in the in-memory representation of the abstract datum "bag" as a concrete Python object. That you can write {1:2,1:2} with the same meaning as {1:2} is almost as irrelevant as the fact that you can add spaces, or a trailing comma, at your pleasure -- it doesn't change the dictionary object we're getting from the parser. >> and for example "intersection" of bags then becomes, e.g: >> >> def intersectBags(bag1, bag2): >> result = {} >> for item in bag1: >> count = min(bag1[item], bag2.get(item, 0)) >> if count>0: result[item] = count > ^^^^^^^^^^^ <- this is superfluous IMO I prefer to avoid redundant storing of "mapping to 0", since to all intents and purposes they're equivalent to absence from the bag. Once again, instinctively I prefer to find a CANONICAL representation -- where each abstract object is represented in ONE way as a concrete object. Maybe it's an artefact of having worked too much in combinatorics (where double-counting is a perennial worry:-), or maybe it's an application of Python's motto "there should be one way, and ideally only one way". Sometimes, for efficiency, I have to make do with non-canonical implementations during computation, and normalize them back to canonical form at the end (e.g., computing with rationals, go back to the canonical representation with mutually prime numerator and denominator only after a series of computations), but I'm always somewhat uncomfortable when such needs arise -- as I consider them an optimization, I'm VERY loath to perform them prematurely:-). >> return result > > Yes, definitely better than my "append to result, remove from original > list to prevent item being counted twice" version. And a lot faster > (except for the abnormal "very large seq0, very small seq1" case). Yes, you can check lengths and swap the bags if you want to ensure O(min(len(bag1), len(bag2))) performance -- again this seems to me to be more of an optimization than a "deep" issue, but of course it may have practical importance. > This is what I made of your code (it's a little optimized compared to > my previous version so that the loop goes always through the smaller > sequence.) I didn't change the 'union' and "symmetric difference" part > because you have to loop through count0 *and* count1. Given that you delegate some of the implementation of your 'or' to your 'not', which goes to the trouble of converting back and forth, I'd bet you would be somewhat better off by simplifyind -- rather than: > if boolean_modus == 'and': # intersection > count0 = tocount(seq0) > count1 = tocount(seq1) > > if count0 > count1: # loop through the shorter list that's NOT what you're testing for here -- use len(count0) etc to test the lengths. > count0, count1 = count1, count0 > for item in count0: > count0[item] = min(count0[item], count1.get(item, 0)) > return toseq(count0) have another auxiliary function: def binop(seq0, seq1, op): count0 = tocount(seq0) count1 = tocount(seq1) if len(count0) > len(count1): count1, count0 = count0, count1 for item in count0: count0[item] = op(count0[item], count1.get(item, 0)) and implement your 'and' by returning binop(seq0, seq1, min) and your 'or' by returning binop(seq0, seq1, max) -- I think this also clarifies the parallelism between the two cases. A few more points: > def boolean(seq0, seq1, boolean_modus): > """" perform 'and', 'not', 'or', or 'xor' operation on sequences """ > ## auxiliary functions > def tocount(seq): # convert to dict where key is the hashable > representation > count = {} # of the object and value is the object count > for item in seq: > count[repr(item)] = count.get(repr(item), 0) + 1 > return count > > def toseq(count): # convert back to sequence > return [item for key in count for item in [eval(key)] * > count[key]] You're FAR more likely to meet objects where you can't count on eval(repr(x)) == x, than non-hashable objects. > elif boolean_modus == 'not': # set difference > count0 = tocount(seq0) > count1 = tocount(seq1) > > if count0 < count1: # loop through the shorter list > for item in count0: > count0[item] = count0[item] - count1.get(item, 0) > else: > for item in count1: > count0[item] = count0.get(item, 0) - count1[item] I don't understand this. This way you can end up with negative values for several items in count0 -- what do they MEAN? You may luck out in that [blah]*N for ANY N<=0 is [], but it seems quite peculiar to me to COUNT on this (particularly w/o a comment!-). > elif boolean_modus == 'xor': # symmetric difference > return boolean(boolean(seq0, seq1, 'or'), boolean(seq0, seq1, > 'and'), 'not') This one could also be more speedily implemented with the already presented binop and another little auxiliary function: def maxminusmin(onecount, anothercount): return max(onecount, anothercount) - min(onecount, anothercount) and your 'xor' is implementable as return binop(seq0, seq1, maxminusmin) Alex From jsaul at gmx.de Wed Oct 9 05:41:41 2002 From: jsaul at gmx.de (jsaul) Date: Wed, 9 Oct 2002 11:41:41 +0200 Subject: partial list sort Message-ID: <20021009094141.GA852@jsaul.de> Hi there, I am looking for the proper way to sort a list range-wise. The scenario is as follows: I am reading a list of data elements triple-wise component A, B and C, then the next triple A, B, C and so on. Each list element has a component identifier which takes the values "A", "B", or "C". What I want is to sort the components within each *triple*, but *not* the while list, so that I can assure an order of A-B-C no matter what the original order in the data was, which can as well be B-C-A or whatever. Here is a simplified version of my script illustrating the problem: list=[ [1,'C'], [2,'B'], [3,'A'], [4,'C'], [5,'B'], [6,'A'] ] print list def sort_components (list): def cmp_comp (data1, data2): if data1[1] == data2[1]: return 0 elif data1[1] < data2[1]: return -1 return 1 print list list.sort(cmp_comp) print list return for k in range(0, len(list), 3): # sort over ranges: sort_components(list[k:k+3]) print list The resulting output is: [[1, 'C'], [2, 'B'], [3, 'A'], [4, 'C'], [5, 'B'], [6, 'A']] [[1, 'C'], [2, 'B'], [3, 'A']] [[3, 'A'], [2, 'B'], [1, 'C']] [[4, 'C'], [5, 'B'], [6, 'A']] [[6, 'A'], [5, 'B'], [4, 'C']] [[1, 'C'], [2, 'B'], [3, 'A'], [4, 'C'], [5, 'B'], [6, 'A']] What I want is [[3, 'A'], [2, 'B'], [1, 'C'], [6, 'A'], [5, 'B'], [4, 'C']] You see that *within* the function 'sort_components' each triple is sorted properly, but after leaving that function, the sorting is not retained. I want to sort the list triple-wise preferably *without* restructuring the list. Can anybody give me a hint about what I have overlooked? Cheers, jsaul -- Que le gusta rrrodarrr la errre. From tdelaney at avaya.com Wed Oct 2 01:23:36 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Wed, 2 Oct 2002 15:23:36 +1000 Subject: Decimal arithmatic, was Re: Python GUI app to impress the bos s? Message-ID: > From: Dennis Lee Bieber [mailto:wlfraed at ix.netcom.com] > > When I took science classes, I'd have been dinged a > few points if I > turned in 0.035 -- the rule was to report results to the same > significance as the inputs. Yes - but the point there is that there is error in the inputs. The point of all this is that we are dealing with *exact* inputs ... and ending up with error. Tim Delaney From krissepu at vip.fi Mon Oct 21 15:23:53 2002 From: krissepu at vip.fi (Pekka Niiranen) Date: Mon, 21 Oct 2002 22:23:53 +0300 Subject: Threads and GUI question Message-ID: <3db4544c@news.vip.fi> Hi, I am using wxWindows in win2000 to start a loop that writes to a COM -port: runOK = 1 while runOK != -1: -- write data to COM -port-- My original idea was to have a Stop -selection in menubar, that would set runOK = -1 and cause the while loop above to stop. The problem is that menubar does not response while the while -loop is running. Should I use threads or am I missing some simple trick ? If using threads, how many do I need ? Only two ? -pekka- From gerhard.haering at gmx.de Sun Oct 27 01:28:56 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Sun, 27 Oct 2002 07:28:56 +0100 Subject: [ANN] pyPgSQL 2.3 beta 1 released Message-ID: <20021027062856.GA4787@lilith.ghaering.test> Announce: pyPgSQL - Version 2.3 beta 1 is released. =========================================================================== pyPgSQL v2.3 beta 1 has been released. It is available at http://pypgsql.sourceforge.net. pyPgSQL is a package of two (2) modules that provide a Python DB-API 2.0 compliant interface to PostgreSQL databases. The first module, libpq, is written in C and exports the PostgreSQL C API to Python. The second module, PgSQL, provides the DB-API 2.0 compliant interface and support for various PostgreSQL data types, such as INT8, NUMERIC, MONEY, BOOL, ARRAYS, etc. This module is written in Python and works with PostgreSQL 7.0 or later and Python 2.0 or later. It was tested with PostgreSQL 7.0.3, 7.1.3, 7.2.2, 7.3 beta 2, Python 2.0.1, 2.1.3 and 2.2.2. Note: It is highly recommended that you use PostgreSQL 7.1 or later and Python 2.1 or later. If you want to use PostgreSQL Large Objects under Python 2.2.x, you *must* use Python 2.2.2, because of a bug in earlier 2.2 versions. Project homepages: pyPgSQL: http://pypgsql.sourceforge.net/ PostgreSQL: http://www.postgresql.org/ Python: http://www.python.org/ This is the first time we release a beta of pyPgSQL. While there didn't change much under the hood, the build process was completely rewritten, so pyPgSQL should now build out of the box on most popular platforms. For you, this means that a "python setup.py build" will now hopefully just work. And for us, this means we'll have to answer less boring support questions :-) These platforms were tested and will build out of the box (of course, more testing won't hurt): UnixWare 7/OpenUNIX 8, Windows native, Cgwin, FreeBSD 4.7, Redhat Linux 7.3, SuSE Linux 7.3, Debian Linux 3.0. The build process is also designed to work with these platforms, but they could not be tested in real life (please do so, if you can!): Mandrake Linux, NetBSD, OpenBSD, MacOS X. If your platform isn't supported out of the box, you can edit a setup.config file to configure the build process. Patches for supporting additional platforms are more than welcome. Look into setup.py for how to do it. The other big change is that Gerhard finally gave up on getting more feedback on his Unicode patch and merged it into the pyPgSQL 2.x line. Hey, if it did work for Linux 2.4, it can work for us, too <0.7 wink>. Using Unicode works like this: from pyPgSQL import PgSQL con = PgSQL.connect(client_encoding=("utf-8", "ignore"), unicode_results=1) # where client_encoding are the parameters you normally give to the encode # method of a Unicode string. unicode_results=1 means pyPgSQL will return # VARCHAR/CHAR/TEXT fields as Unicode strings instead of byte strings. # As I refuse to do any magic, you'll also have to set the client encoding # for the database manually: cursor = con.cursor() cursor.execute("SET CLIENT_ENCODING TO UNICODE") # There are other ways to set the client encoding, including setting a # special environment variable (see PostgreSQL manual), but I recommend # doing it in code. --------------------------------------------------------------------------- ChangeLog: =========================================================================== Changes since pyPgSQL Version 2.2 ================================= The following source code files were added to Version 2.3 beta 1 of pyPgSQL: setup.config - Part of the changed distutils-based build process. If you want to customize the build process (change include and library directories, for example, you only need to edit this file; setup.py should not be edited directly any longer) unicode_tests.py - Test suite for the new Unicode support. Merged from the Unicode patch. Changes to setup.py ------------------- * This file was rewritten entirely so that pyPgSQL now builds out of the box on Windows, Cygwin, Debian Linux, Redhat Linux, SuSE Linux, FreeBSD, UnixWare 7 and OpenUNIX 8. These are the platforms the new build process has been tested on. Untested support is available for Mandrake Linux, NetBSD, OpenBSD and MacOS X. Changes to README ----------------- * Updates for 2.3b1. * Converted the whole document into reStructuredText, so we can easily built a HTML version using docutils (http://docutils.sf.net/). Changes to README.win32 ----------------------- * Remove out of date warning about PostgreSQL on win32 * Reflected change from windows/ to ports/ Changes to PgSQL.py ------------------- * Merged the Unicode patch. pyPgSQL now has full Unicode support. * Added support for the INTERVAL type. * mxDateTime 1.x is no longer supported. Require mxDateTime 2.x and give useful error message if import fails. * Cosmetic changes: use cmp builtin where appropriate. * Fixed typo where PgTypes.__str__ was spelled incorrectly; compare to None using "is" operator. * Take into account that libpq.PgInt8Type might not be available. * Convert ROWID to PgInt8 instead of PgInt4 (the original behaviour led to overflow errors.) * Always set the displaysize field of cursor.description to -1. PostgreSQL 7.3 doesn't provide this information any more and it's pretty useless nowadays that we've mostly left line printers beyond us. Changes to pyPgSQL/__init__.py ------------------------------ * Register libpq.PgInt8 with copy_reg only if available. Changes to pglargeobject.c -------------------------- * Made the 'closed' attribute of PgLargeObject an int instead of a long. Changes to libpqmodule.c: ------------------------- * Fixed the format string of ParseTuple in libPQbool_FromInt. This closes a bug that appeared on Linux/Alpha (#625121). Changes to PgSQLTestcases: -------------------------- * Don't check for the obsolete displaysize field in cursor.description. Also don't check the backend encoding. Multiple files -------------- The windows/ directory has been moved to a port/ directory. Now we *always* use our own version of various string versions instead of special casing for a dozen different Windows and Unix platforms. In order to get the C version of PgInt8Type, it is now required that the constants LLONG_MAX, LLONG_MIN, ULLONG_MAX and ULLONG_MIN are defined when including limits.h and that including Python.h defines HAVE_LONG_LONG. Otherwise, a Python class is used instead. From edcjones at erols.com Wed Oct 16 12:26:47 2002 From: edcjones at erols.com (Edward C. Jones) Date: Wed, 16 Oct 2002 12:26:47 -0400 Subject: Solved MySQL, MySQLdb problems Message-ID: I have solved my problem with MySQL and MySQLdb. The problem was: > I have installed mysql-3.23.52 as part of the Gentoo Linux > distribution. I am accessing MySQL via mysql-python AKA MySQLdb > which calls the MySQL C API. During testing I start MySQL using > "safe_mysqld" and shutdown MySQL using "mysqladmin -u root > --password=xxxxxxxx shutdown". > When I do a "LOAD DATA LOCAL INFILE" via MySQLdb, I get the > well-known error message 1148: "The used command is not allowed > with this MySQL version". 1. Add to mysql-3.23.52.ebuild the line myconf="${myconf} --enable-local-infile" It goes in the src_compile() section. Do an "emerge dev-db/mysql" to rebuild MySQL. This is the same as running config with the "--enable-local-infile" option. 2. Recompile mysql-python (which contains MySQLdb). I suspect the segfaults I was having were due to library mismatches. Therefore build MySQLdb after MySQL. 3. Add "local-infile" to "/etc/mysql/my.cnf" in the groups [safe_mysql], [mysqld], and [mysql]. Do not add it to the group [client]. 4. At some point the MySQL GRANT system was changed. Now GRANT FILE ON my_database.* TO abcdefgh at localhost IDENTIFIED BY xxxxxxxx'; does not work. One must use: GRANT FILE ON *.* TO abcdefgh at localhost IDENTIFIED BY 'xxxxxxxx'; Note that now abcdefgh can access any file on any database. I wish I could use "LOAD DATA LOCAL INFILE" is a more secure manner. From tundra at tundraware.com Sat Oct 5 15:50:07 2002 From: tundra at tundraware.com (Tim Daneliuk) Date: 05 Oct 2002 19:50:07 GMT Subject: Python + Win32: Cut/Paste w/o GUI References: <5dukna.oh1.ln@boundary.tundraware.com> Message-ID: Matt Gerrans wrote: > At first you said "paste from an arbitrary Windows app" and I was not sure > what you were trying to do, but if what you really meant was drag-and-drop > from Explorer to a shortcut, for instance, then there is hope. Try the > following; if you run it with no parameters, it will create a shortcut to > itself on the desktop. After that, if you drag-and-drop another icon onto > that shorcut, it will pop up a message (I know, this is not entirely console > stuff, but I wanted the results to be clear and anyway, you just wanted to > get the parameters). > > import os,sys,win32com.client,win32ui > > if len(sys.argv) == 1: > shell = win32com.client.Dispatch("WScript.Shell") > desktop = shell.SpecialFolders("Desktop") > > # Might want to get python location from registry, but I'm > # being lazy. > python = 'c:\\Python22\\Python.exe' > target = os.path.join(desktop,'Shorty.lnk') > link = shell.CreateShortcut( python + ' ' + target ) > link.TargetPath = sys.argv[0] > try: > link.Save() > except: > print 'Failed to save "%s", maybe it already exists.'%target > else: > win32ui.MessageBox( "Quit dropping your %s's on me!" % sys.argv[1] ) > My apologies for lack of clarity. This isn't quite what I had in mind, but it is interesting code nonetheless which is going into my "Things That Could Save Your Life" pile for later use. Many thanks... -- ------------------------------------------------------------------------------ Tim Daneliuk tundra at tundraware.com From JXSternChangeX2R at gte.net Mon Oct 7 10:19:50 2002 From: JXSternChangeX2R at gte.net (JXSternChangeX2R) Date: Mon, 07 Oct 2002 14:19:50 GMT Subject: Quick question on mysql-python References: <3d9f74b2$1_7@goliath.newsgroups.com> Message-ID: On Sun, 6 Oct 2002 00:38:52 GMT, mongo57a at comcast.net wrote: >Just finished downloading Python 2.2.1. Appears to be working fine. To >complete the installation, I downloaded and executed >MySQL-python-0.9.2-1.i386.rpm. MySQLdb shows up in >/usr/lib/python2.2/site-packages (as it should). When I attempt to import >MySQLdb I get the following error: MySQL-python-0.9.2.win32-py2.2.exe Worked fine. Of course, the import statement is case sensitive, that had me stumped, for about six seconds. J. From senux at senux.com Tue Oct 15 02:46:09 2002 From: senux at senux.com (Brian Lee) Date: Tue, 15 Oct 2002 15:46:09 +0900 Subject: hahahttpd Message-ID: <20021015064609.GA13550@mercury.senux.com> HahaHTTPd is very experimental HTTP server by Python language. I made this as my hobby. If you're interested in it, visit follow site. Advice is always welcome. http://www.senux.com/python/software/hahahttpd/ PS> haha is sound of laughing alound in Korean langauge. -- Brian Lee - http://www.senux.com/en/ From bokr at oz.net Thu Oct 3 14:16:55 2002 From: bokr at oz.net (Bengt Richter) Date: 3 Oct 2002 18:16:55 GMT Subject: Decimal arithmetic, with example code References: Message-ID: On 3 Oct 2002 07:08:38 GMT, bokr at oz.net (Bengt Richter) wrote: [...] > >BTW, you probably noticed I wasn't really rounding in my evenround function -- >I was just noodging the value so the subsequent round inside %.f looked like it >was doing decimal bankers round. I just played a hunch with the BIAS multiply. >Using FixedPoint as a final formatter for floating point should work better than >bias-kludging the ordinary round. It's probably about as good an estimate of the >nearest decimal of a given precision to a given fp number as you can get. > [...] > >BTW, FWIW, since the denominator is 1L << -e where you round the conversion, >the following should hold (I think, not very tested): > > exactHalf = 1L << (-e-1) > n = top + exactHalf # ok round except banker's tie with odd no > wasTie = not (n & ((exactHalf<<2)-1L)) # odd => even and no 1's below > n = (n >> -e) - wasTie # readjust for bad tie result > > assert n == _roundquotient(top, 1L << -e) > >Whether it's worth doing depends on speeds which I haven't tested. Depends on divmod and cmp... >Out of steam for tonight... > Not enough steam to get it right ;-/ -- this should work better and faster: exactHalf = 1L << (-e-1) wasTie = not (top & (exactHalf-1L)) # no 1's below n = top + exactHalf # ok round except banker's tie => odd n = (n >> -e) n -= n & wasTie # readjust for bad tie result assert n == _roundquotient(top, 1L << -e) >BTW2, I wonder if it would be worth while to do a banker's round like round, but guaranteeing >that the result's magnitude will be the first fp state >= the true decimal value. It would >be biased minisculely, but it might be helpful for printing non-surprising decimals. str(f) >seems to be solving part of the problem, but an alternate %f (%F?) to control bankers round >at a given precision might be nice. A few bits from fixedpoint could be cannibalized. > Regards, Bengt Richter From parker at gol.com Wed Oct 16 05:36:08 2002 From: parker at gol.com (Ian Parker) Date: Wed, 16 Oct 2002 18:36:08 +0900 Subject: force variable declaration? References: <6Dbp9.69869$X9.12557473@twister.socal.rr.com> Message-ID: In article , Peter Rams writes >Hi Jeff, > >thanks for your answer, I meant something like this: > >counter = 0 >while counter < 100: > conuter = counter + 1 > >leads to an endless-loop because of typing error of counter. In other >languages I have to declare all variables, it would look for example like >this: > >int counter >counter = 0 >while counter < 100: > conuter = counter + 1 > >Then the syntax check says: no variable "conuter" declared. In Perl, for >example, there is a statement (I forgot how it's like), where you can force >the programmer to declare his variables. Is there something similar in >python? > >Thanks, >Peter > > >"Jeff Davis" wrote in message >news:6Dbp9.69869$X9.12557473 at twister.socal.rr.com... >> >> what do you mean force variable declaration? you mean type checking? >> >> You can't really force python to limit you like that. That type of >checking >> is better served by a tool independent of the interpreter. For example, >> pychecker is great for spotting probable errors in your code, even when >> the interpreter doesn't complain. See if pychecker is able to help spot >> your error. >> >> That way, we have the flexibility of python's dynamic typing, but we can >> spot our errors quickly as well. >> >> Regards, >> Jeff >> >> > Hi, >> > >> > is it possible to force variable declaration in python (like it is for >> > example in perl)? A few days ago I had an anoying error because of a >> > typing error of a variable... >> > >> > Regards, >> > Peter >> > > Peter But the wonderful pychecker would also catch this, at least reporting that " Local variable (conuter) not used". Interestingly, pychecker didn't identify this in a file consisting only of the code above, although it worked correctly with: def co(): counter = 0 while counter < 100: conuter = counter + 1 print counter if __name__ == '__main__': co() So that's probably a bug, or simply me. -- Ian Parker From maschio_77 at hotmail.com Mon Oct 21 03:31:37 2002 From: maschio_77 at hotmail.com (Maschio_77) Date: Mon, 21 Oct 2002 07:31:37 GMT Subject: data from a web page References: <8RDs9.14810$TD1.676374@news2.tin.it> <3DB321E6.4020508@gazeta.pl> <5IFs9.15414$TD1.699474@news2.tin.it> Message-ID: Ok , I understand how to use htplib or urllib,now I'm just courios to know if I can use socket too, I think something like this: s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.connect(www.somesite.com, 80) s.send("XXX") data=s.recv(1024) s.close() wich XXX I've to send to receiv the html code from the web server? thanks "Gerhard H?ring" ha scritto nel messaggio news:mailman.1035153205.27567.python-list at python.org... > * Maschio_77 [2002-10-20 22:00 +0000]: > > "bromden" wrote: > > > what do you exactly mean? > > > [...] > > > - you just want to read a webpage? look here: > > > http://www.python.org/doc/current/lib/module-httplib.html > > > > > > The first: I want to read the web page content from my little > > > program to take some data > > gerhard at gargamel:~$ python > Python 2.2.2 (#1, Oct 18 2002, 03:24:30) > [GCC 2.95.4 20020320 [FreeBSD]] on freebsd4 > Type "help", "copyright", "credits" or "license" for more information. > >>> import urllib > >>> print urllib.urlopen("http://www.python.org/").read() > > > > [...] > > More in the docs about the urllib module. > > HTH, > > -- Gerhard > From gmcm at hypernet.com Thu Oct 3 09:09:08 2002 From: gmcm at hypernet.com (Gordon McMillan) Date: 03 Oct 2002 13:09:08 GMT Subject: MetaKit issues with Python 2.2.1 CGI script References: <2a897f11.0210021903.29cf80d1@posting.google.com> Message-ID: [posted and mailed] Wayne Pierce wrote: > I have been working on a CGI script that is supposed store data into a > MetaKit database, but is only storing one character per 'field.' [...] > import metakit > db = metakit.storage("officer.mk",1) > ovw = db.view("officer") > > data = > "reportingAgency='%s',firstName='%s',lastName='%s',email='%s',number > ='%s'" > % (reportingAgency,firstName,lastName,email,number) > > /* > The above data is parsed from a CGI form. > */ > > ovw.append(data) You are passing one argument (a string) to append. As a desperate fallback, it's treating it as a sequence. ovw.append(reportingAgency=reportingAgency, firstName=firstName, lastName=lastName, email=email, number=number) is what you want. There's no need for any string substition. If you don't know what fields will be present at runtime, then construct a dictionary: d = {'reportingAgency':reportingAgency, .... } ovw.append(d) -- Gordon http://www.mcmillan-inc.com/ From jepler at unpythonic.net Thu Oct 17 22:54:15 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 17 Oct 2002 21:54:15 -0500 Subject: Python GTK JPEG Images In-Reply-To: References: Message-ID: <20021017215414.C5043@unpythonic.net> On Thu, Oct 17, 2002 at 07:02:33PM -0700, Murray Blakeman wrote: > It appears that it will do most things that I want it to but I have > found it difficult finding information on how to display JPEG images > (from the HDD) in a GTK window with Python. There is an example using the "imlib" library. On my system, this is in /usr/share/doc/pygtk-0.6.8/examples/imlib/view.py I recall that imlib can resize & rotate jpeg images. (in fact, view.py seems to scale images if they are larger than the screen resolution) Jeff From bebert at worldonline.dk Mon Oct 14 16:09:19 2002 From: bebert at worldonline.dk (Bjarke Dahl Ebert) Date: Mon, 14 Oct 2002 22:09:19 +0200 Subject: string to float, putting in list/tuple References: <3DAB179F.6070200@me-barie.de> Message-ID: "Daniel Bari?" wrote in message news:3DAB179F.6070200 at me-barie.de... > Now I want to convert these to float, using the builtin float() > function. The results are quite as expected: float(Sl) = 0.03169, > float(SS31) = -3.01, float(SS41) = -3.01. > > But when stuffing a list with these floats the result is not as I > expect it to be: > [0.031690000000000003, -3.0099999999999998, -3.0099999999999998] This must be a FAQ. It is not true that float(SS41)=-3.01, it just looks that way ;-) >>> a = 3.1 >>> a 3.1000000000000001 >>> print a 3.1 >>> str(a), repr(a) ('3.1', '3.1000000000000001') You are seeing the rounding errors coming from the fact that 31/10 cannot be expressed precisely with binary numbers. The reason why you see a difference between 'a' and '[a]', is that the string representation of '[a]' is the same as repr([a]), which uses 'repr' on all the list entries. 'repr' on a number uses maximum precision. 'str' on a number does some rounding to avoid all these decimals. Bjarke From tjreedy at udel.edu Sat Oct 5 23:22:34 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 5 Oct 2002 23:22:34 -0400 Subject: are these operations on list valid? References: Message-ID: "Ken" wrote in message news:ano9fi$fo0ko$1 at ID-49758.news.dfncis.de... > Hi, just like to know if these are valid: Start up interactive interpreter and try them out. Best way to learn. Same answer to next post. TJR From gumuz at looze.net Wed Oct 2 10:48:20 2002 From: gumuz at looze.net (Gumuz) Date: Wed, 2 Oct 2002 16:48:20 +0200 Subject: Love "Python Cookbook" References: Message-ID: <3d9b05b5$0$220$4d4ebb8e@news.nl.uu.net> is this a printed version of the Activestate Python Cookbook or is this something different? "Robert Oschler" wrote in message news:ajDm9.17019$Lg2.4725880 at news2.news.adelphia.net... > Got the book 2 weeks ago, what a treasure trove. If you are serious about > Python then get this book. > > thx > > > From hwlgw at hotmail.com Tue Oct 15 15:43:02 2002 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 15 Oct 2002 12:43:02 -0700 Subject: Python and UML Message-ID: With respect to Python: what are your experiences using UML? What do you think of the UML 2.0 proposals? http://www.u2-partners.org/outgoing/uml2/specs/U2P-UML-Super-v2bR1-PDF-ad020902.zip If you see those specifications... If you join bigger sofware projects you will meet UML. You know that is going to happen. As it looks now you are almost forced to use Java or C++. As Python gets more and more popular and used in the ``real'' world, we have to be able to face the day they confront us with UML. It happened to me. How about the new 2.0? Take for example how you are supposed to design Components according to u2-partners: Use: EncapsulatedClassifier (from Port), PackagingNamespace, MemberImport, ElementImport, ComponentImport to get to: Component, with attribute isIndirectlyInstantiated: Boolean Is such a UML 2.0 even useful for modeling Python software? The problem is, if you say **no** to a UML design, you often stand to lose a lot of money. Perhaps unless you can give really good arguments why not to use UML. Maybe reactions to this posting can give some of those arguments. Maybe we can even have some influence on how UML evolves. ''' QOTD, about UML There are useful diagrams in UML, (eg, the state and transition diagrams). Unfortunately, the one most tools use to generate code (and draw from reverse engineering) has everything to do with language structure, and nothing to do with what actually happens at runtime. To put it bluntly: people spend most of their time designing the wrong thing. Worse, they get it wrong, but it's carved in stone now; so the final system is either needlessly complex and marginally functional, or bears no resemblance to the "design". -- Gordon McMillan, 15 Dec 1999 ''' From edgebruce at yahoo.com Tue Oct 1 14:31:45 2002 From: edgebruce at yahoo.com (Bruce Edge) Date: Tue, 01 Oct 2002 11:31:45 -0700 Subject: Id, or stinky primo? References: <7A4m9.25416$V64.5149538@newsfeed.slurp.net> <3d98dcdc$0$23174$afc38c87@news.optusnet.com.au> Message-ID: Steven wrote: > > "Bruce Edge" wrote in message > news:7A4m9.25416$V64.5149538 at newsfeed.slurp.net... >> Is the Id it really worth the $$$$? >> I've been looking at a kona stinky primo, and it seems like a comparable >> bike for less dough. >> What's the general opinion out there? >> Why is the Id better? > > I think you posted to the wrong group > > who makes the Id? what are you intending on doing with the bike? the the > Kona doesn't look like something you'd want to take on a downhill run. > > Steven Cripes, oops. Id's made by ellsworth. The kona _is_ a freeride/light DH bike. From david at no.westcontrol.spam.com Thu Oct 31 06:27:37 2002 From: david at no.westcontrol.spam.com (David Brown) Date: Thu, 31 Oct 2002 12:27:37 +0100 Subject: Iterating through multiple sequences References: Message-ID: "Mark Charsley" wrote in message news:memo.20021031104532.116B at a.radioscape.com... > In several cases recently I've wanted to iterate through two sequences at > the same time. The way I've been doing it so far is > > assert(len(myList1) == len(myList2)) > for i in range(len(myList1)): > doSomethingWith(myList1[i],myList2[i]) > > which is a little ugly. Is there some clever idiom I'm missing that would > simplify things? Something like > > for elem1,elem2 in myList1,myList2: > doSomethingWith(elem1,elem2) > > which, while valid python, doesn't do what I hoped for > Try either zip(..., ..) or map(None, ..., ...). The difference is how they treat unequal lengths: >>> as = [1, 2, 3] >>> bs = ['a', 'b'] >>> zip(as, bs) [(1, 'a'), (2, 'b')] >>> map(None, as, bs) [(1, 'a'), (2, 'b'), (3, None)] >>> From paoloinvernizzi at dmsware.com Thu Oct 31 03:57:10 2002 From: paoloinvernizzi at dmsware.com (Paolo Invernizzi) Date: Thu, 31 Oct 2002 08:57:10 GMT Subject: pyQt - opinions In-Reply-To: <3dc01a1c$0$3342@echo-01.iinet.net.au> References: <3dc01a1c$0$3342@echo-01.iinet.net.au> <_YVv9.2522$5z.446787832@hebe.telenet-ops.be> Message-ID: Axel Vandevenne wrote: > Rob Hall wrote: > > Make a small program (hello world or something) for wxwindows and qt > -> qt is a lot faster... I've done this test a LOT of time ago... with the last open-source usable PyQT under Windows... A PyQT simple application was a lot slower and bigger versus a wxPython app under windows.... really too slow! Someone has some more recent comparison? Paolo Invernizzi DMSWare.com From martin at v.loewis.de Sun Oct 6 03:45:16 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 06 Oct 2002 09:45:16 +0200 Subject: Is multifile fixed or broken in 2.2? References: Message-ID: "Stuart D. Gathman" writes: > In the small test program below, python-2.1 reads one more newline than > python-2.2 on the multipart section. Which one is right? That's difficult to say. Python 2.2.2 will restore the 2.1 behaviour, for compatibility. This may not be strictly in compliance with all applicable RFCs, but the 2.2 multifile fixes were causing other problems. So it has been decided that multifile stays as it is; users wishing to process MIME properly should use the email package. Regards, Martin From cliechti at gmx.net Tue Oct 1 19:02:17 2002 From: cliechti at gmx.net (Chris Liechti) Date: 2 Oct 2002 01:02:17 +0200 Subject: Override a method in another module References: Message-ID: Bruce Edge wrote in news:Fppm9.30728$V64.5796737 at newsfeed.slurp.net: > What's the basic syntax to override (redefine) a function in another > module at runtime? > > Say, I have module M, class C, method F, and I want to redifine method > F. > > setattr( M.C.F, eval("def F(self): pass")) doesn't exactly work..... and how does: >>> def F(self): pass >>> M.C.F = F #or setattr(M.C, 'F', F) ? hints: 1) setattr needs 3 args 2) eval works only for expressions and "def" is a keyword chris -- Chris From dave at boost-consulting.com Fri Oct 11 16:53:31 2002 From: dave at boost-consulting.com (David Abrahams) Date: 11 Oct 2002 16:53:31 -0400 Subject: ANN: Boost.Python v2 Message-ID: I'm pleased to announce that v. 1.29.0 of the Boost C++ libraries (http://www.boost.org) has been released! This marks the first release of v2 of the Boost.Python library (http://www.boost.org/libs/python), a C++ library enabling seamless interoperability between C++ and the Python programming language. The new version has been rewritten from the ground up, with a more convenient and flexible interface, and many new capabilities, including support for: - References and Pointers - Globally Registered Type Coercions - Automatic Cross-Module Type Conversions - Efficient Function Overloading - C++ to Python Exception Translation - Default Arguments - Keyword Arguments - Manipulating Python objects in C++ - Exporting C++ Iterators as Python Iterators - Documentation Strings Of course, the old abilities to wrap classes and functions are still there. Thanks to all Boost.Python's contributors and users for their patience and their support. -- David Abrahams * Boost Consulting dave at boost-consulting.com * http://www.boost-consulting.com From bloke at ii.net Tue Oct 15 23:09:04 2002 From: bloke at ii.net (Rob Hall) Date: Wed, 16 Oct 2002 11:09:04 +0800 Subject: yielding control References: Message-ID: <3dacd826$0$2001@echo-01.iinet.net.au> That works perfectly. Thanks all. > > Better do a sleep(0.0001), the OS get's a hold of the cpu, > and the actual sleep time is so small as to be almost zero. > > -gus > From newsfroups at jerf.org Sat Oct 5 21:01:34 2002 From: newsfroups at jerf.org (Jeremy Bowers) Date: Sun, 06 Oct 2002 01:01:34 GMT Subject: Boa Constructor and CVS question References: Message-ID: On Sat, 05 Oct 2002 18:55:27 +0000, Conrad Schneiker wrote: > You can argue (correctly) that in my case I shouldn't be so lazy, but my > ultimate aim is to lower the access barriers (as it were) to good Python > stuff, as much as possible, for everyone. Without speaking for anybody, certainly not the Boa project in particular, you may find that many people are not *interested* in lowering the barrier to access cvs repositories. There's a certain danger in checking things out from the latest version, both in the sense it might not work and in the machine-breaking sense. The current difficulty level of cvs checkout filters out a lot of people who would just be trouble. ;-), but I'm serious too. What you really need to do is either A: Convince them to release a real release, or B: Do it yourself, as a stop-gap until they release an "official" version. If you're willing to stand behind the release and possibly update it a bit to get rid of the outrageous bugs, they may even *make* it official. Often developers just haven't made a release because they're too busy making new stuff. (Again, I'm not speaking on behalf of any particular project here.) From sismex01 at hebmex.com Mon Oct 7 16:29:17 2002 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Mon, 7 Oct 2002 15:29:17 -0500 Subject: exec(threads) Message-ID: > From: JS [mailto:scjuonline at web.de] > > > So when you said "no processes are created" you meant "I don't get > > threads"? > > "No Processes" means, I get threads. (as expected) > > >I'm not sure what the problem is yet, so can't yet do much to > > help you solve it! Although you posted the code you didn't > > say how it failed to run on which platforms. Your original > > post said you saw five new processes created on Linux, and > > you then imply that the problem lies with Linux. Is this > > actually the case or am I misunderstanding? > > The code I posted was just a dirty testing hack. > This code shows, that 5 processes are created under linux. > Or at least I think so. But if a 'ps' gives me > > PID TTY TIME CMD > ... > 2543 pts/9 00:00:00 go.py > 2544 pts/9 00:00:00 go.py > 2545 pts/9 00:00:00 go.py > 2546 pts/9 00:00:00 go.py > 2547 pts/9 00:00:00 go.py > > they should be processes, right? > > What is used if I call start_new_thread()? > Is it a user-level library? If yes, which one? > > thx, J > OK, LinuxKernel 101. Yes, they're "processes", and they're "threads" also. In other OSs, threads and processes are completely different beasts, created in differring manner, and sometimes (remember AmigaOS y'all?) incompatible with each other. Sux. On linux, threads and processes are the same beasty with a different flavor and color. Both are created with syscall clone() only with differring options, to create either what effectively is a process (with it's accompanying semantics) or a thread (with *it's* respective semantics). The "downside" is that both appear in ps's output as the same thing; a threading program appears the same as a forking program. Hope this helps. -gustavo From hellprout at yahoo.com Fri Oct 11 03:59:54 2002 From: hellprout at yahoo.com (hellprout) Date: 11 Oct 2002 00:59:54 -0700 Subject: wxbutton Message-ID: <5b8834c2.0210102359.78954086@posting.google.com> hi i just want to know what can i do to have a wxbutton disabled and after you can have a wxbutton enabled thanks From mrroach at okmaybe.com Wed Oct 16 00:06:10 2002 From: mrroach at okmaybe.com (Mark Roach) Date: Tue, 15 Oct 2002 23:06:10 -0500 Subject: scripting ximian evolution References: Message-ID: On Tue, 15 Oct 2002 22:42:37 +0200, Alex Polite wrote: > According to ledgend it's possible to interact with ximian evolution's > addressbook and calendar (wombat?) via python. Has anyone actually > tried this? If so please post some code. the addressbook part is pretty simple, it is just vcards stored in a berkeley db. Get the bsddb3 module and do something like this to show all the items in the contacts db (unverified code) import bsddb3 addressbook = '/home/username/evolution/local/contacts/addressbook.db' contacts = bsddb3.hashopen(addressbook) for key in contacts.db.keys(): print contacts.db.get(key) also check out zesync which is a sync tool for the sharp zaurus and evolution written in python http://sourceforge.net/projects/zesync/ -Mark From loewis at informatik.hu-berlin.de Thu Oct 31 05:15:23 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 31 Oct 2002 11:15:23 +0100 Subject: Python documentation in DocBook References: <3dbc45dc$0$63807$e4fe514c@dreader1.news.xs4all.nl> <3dbc51df@news.sentex.net> <87y98f566d.fsf@zamazal.org> Message-ID: Milan Zamazal writes: > Much less painful conversion to the other very useful formats, like > Info? Not if it is DocBook. You would need a custom processor for that. Regards, Martin From MarkA at sundance.com Thu Oct 3 10:34:40 2002 From: MarkA at sundance.com (Mark Ainsworth) Date: Thu, 3 Oct 2002 15:34:40 +0100 Subject: ASP and ADO AGAIN! Message-ID: OK. So I may have not read all the right books, but I've read a lot of them. Maybe just not the one with the right answer in? I've been using python quite happily as an ASP scripting language for about 6 months now. We use it to pull data out of a Microsoft Access database the is declared as an on ODBC source on the server. I can sort it, print it, in fact do pretty much anything I want except... One of the field values is declared as a date/time. This is returned and printed on the HTML page correctly (apart from it will insist on the American rather than UK format) Now I want to do some comparison calculations everything starts to go wrong. objEquip = Server.CreateObject("ADODB.RecordSet") objEquip.Open("Select * from Equipment", objCalib) stDate = objEquip("dateinfo").value This gets the correct information, and it prints ok. If I now do: StString = "date %s" % stDate I get an empty string. Or StString = "date " + stDate I get an error message telling me it can't concenate string and time objects. But if stDate is a time object, why does IdValue = stDate.ctime() Tell me that ctime() isn't an method associated with the object because StDate = time LdValue = stDate.ctime() Does work! Anyway, what exactly is returned for a date/time object from the ADO libraries? I can do anything I want with strings and numbers. It's just date and time values that are confusing me. I need to convert the info to find out which data value was stored before a predetermined date. Any help would be greatly appreciated. Mark Ainsworth Quality Manager Sundance Multiprocessor Technology Ltd. Chiltern House, Waterside, Chesham, Bucks HP5 1PS Tel. +44 1494 793167 Fax. +44 1494 793168 MarkA at sundance.com http://www.sundance.com From dave at pythonapocrypha.com Thu Oct 17 15:30:06 2002 From: dave at pythonapocrypha.com (Dave Brueck) Date: Thu, 17 Oct 2002 12:30:06 -0700 (PDT) Subject: win32 and javascript alerts In-Reply-To: <869dc0d1.0210170953.5bb7c283@posting.google.com> Message-ID: On 17 Oct 2002, Bryan L. Fordham wrote: > I'm using those nifty win32com extensions to do some unit testing. > I'm able to control IE with no problems, fill out forms and push the > pretty buttons to make things go. > > The one issue I've run into is this: Say there's an input box called > Spam, that requires a value. If you click the Go button and Spam is > empty, a little javascript alert box pops up and says "Hey, fill in > Spam!" > > well, if I load the page using python and click the Go button with > Spam empty, the javascript alert pops up... and I don't know how to > get rid of it. Python hangs until I manually clear the alert. > > Any ways around this? Well, the way I get around this feels like a horrible, horrible hack, but it works pretty well. Below is some code from a class I made called WebSerf. Use the code in CaptureWindowEvents to install new window.alert and window.open functions (I call this method after I click a Submit button, click a link, or navigate to a whole new page - be sure the new document has fully loaded first!). The code in GetLatestAlertMessage and GetLatestOpenString let you see what actions the page tried to take. You'll have to modify the code somewhat to work with your approach, but I hope it at least helps in some way. -Dave The code: CAPTURE_JSCRIPT = '''var serfcapturedevents = 1; var serfalertmsg=""; var serfopenwin=null; function serfalert(arg) { serfalertmsg=arg; } var serfcapturedevents = 1; var serfalertmsg=""; var serfopenwin=null; function serfalert(arg) { serfalertmsg=arg; } function serfopen() { var args = new Array(null, null, null, null); fargs = serfopen.arguments; for (i=0; i < fargs.length; i++) args[i] = fargs[i]; serfopenwin = serfoldwindowopen(args[0], args[1], args[2], args[3]); return serfopenwin; } function serfclosepopup() { if (serfopenwin != null) serfopenwin.close(); } window.attachEvent('onunload', serfclosepopup); window.alert=serfalert; serfoldwindowopen = window.open; window.open=serfopen; var serfpromptvalue = ''; function serfprompt() { return serfpromptvalue; } window.prompt = serfprompt; var serfconfirmvalue = true; function serfconfirm() { return serfconfirmvalue; } window.confirm = serfconfirm;''' Now a few methods from the WebSerf class: def CaptureWindowEvents(self): 'Installs a Javascript routine to reroute any window.alert/.open calls' pw = self.doc.parentWindow try: pw.serfcapturedevents return # Already captured except AttributeError: pass # Ok, now go capture them try: pw.execScript(CAPTURE_JSCRIPT) except: traceback.print_exc() def GetLatestAlertMsg(self): 'Returns and clears the most recent window.alert message' try: pw = self.doc.parentWindow msg = pw.serfalertmsg if msg: pw.serfalertmsg = '' except: msg = '' traceback.print_exc() return msg def GetLatestOpenString(self): 'Returns and clears the most recent window.open string or None' try: pw = self.doc.parentWindow win = pw.serfopenwin if win: pw.serfopenwin = None except: win = None traceback.print_exc() return win From bondpaper at earthlink.net Mon Oct 14 17:16:05 2002 From: bondpaper at earthlink.net (Tom) Date: Mon, 14 Oct 2002 21:16:05 GMT Subject: Help compiling shared .so on Redhat Message-ID: I'm attempting to install Python 1.5 from a source tarball, and I need to compile into a shared library (.so instead of, or in addition to, the .a file produced by default). I've looked through the configure script and Makefile, and discovered that there are variables containing the correct compile options (-fpic, -shared), but I have been unable to figure out how to get the configure/make process to use them. Thanks. Tom From martin at v.loewis.de Mon Oct 21 12:17:27 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 21 Oct 2002 18:17:27 +0200 Subject: error in httplibs References: Message-ID: St?phane KLEIN writes: > I would like resolve this problem So please investigate it further: Which of the "in" operations cause the trouble? What are the values of the various variables: print headers (AFAICT, this is the only variable that is an input into this line of code). About the only way in which you could get an error is if headers was a string and not a dictionary. If that is the case, where does headers come from?: raise "HERE" I must admit that the code looks bogus to me, wouldn't it be better if it was if ('Host' in headers) or [k for k in headers.iterkeys() if k.lower() == "host"]: instead? Regards, Martin From rfc822 at polspam.info Sat Oct 12 17:34:57 2002 From: rfc822 at polspam.info (WER3w0LF) Date: Sat, 12 Oct 2002 23:34:57 +0200 Subject: [Zope] parameters do not pass from form? Message-ID: I installed ZOPE 2.5.1 for Win32 and I cannot receive parameters from my form file as the following. file testForm: -------------
file testAction: ------------- blah Whatever I write down as parametr in my form I receive only "blah". Why my testAction cannot see variables from testForm? -- Wer3W0lf werewolf at nospamxl.wp.pl delete word nospam From sismex01 at hebmex.com Tue Oct 8 10:50:07 2002 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Tue, 8 Oct 2002 09:50:07 -0500 Subject: Code marshalling question. Message-ID: Hello all. I've had this question for a while. Is there a way to marshal a segment of code into a string, which can then be transported (via whatever method), such that the code segment can be unmarshalled later and executed? The reason for this is to create my own (I know, "It's already been done", but this is a learning experience) marshalling and unmarshalling module which will work with an HTTP server, so do some kind of object or code repository. The idea is not to have locally the definitions of classes or functions I can request, but to simply get a string, unmarshal and use. Kinda like this: >>> class SomeNiceObject: >>> ... >>> ... >>> >>> store(SomeNiceClass) -> marshals and sends to repository. Elsewhere... >>> sno = fetch("SomeNiceObject") >>> instance = sno("some","arguments","maybe?") Is this doable? If so, how? Thanks :-) -gustavo From pedro_rodriguez at club-internet.fr Fri Oct 18 02:59:19 2002 From: pedro_rodriguez at club-internet.fr (Pedro RODRIGUEZ) Date: Fri, 18 Oct 2002 08:59:19 +0200 Subject: Python's driving me mad. Invalid token? References: <5f30c71b.0210172237.28a4f847@posting.google.com> Message-ID: On Fri, 18 Oct 2002 08:37:17 +0200, Jim wrote: > def CopyFiles(dirname,fnamelist): > for name in fnamelist: > destFile = open((dirname+"""\"""+name),'w') ^^ You have a quoting problem here, this could be "\\", but what you actually need is : > destFile = open(os.path.join(dirname,name),'w') This is the portable way to build paths. For the quoting problem can be spotted if you use a text editor with syntax highlighting since the string wasn't closed. Pedro From schitz0boy at hotmail.com Wed Oct 9 22:55:00 2002 From: schitz0boy at hotmail.com (Corey Woodworth) Date: 9 Oct 2002 19:55:00 -0700 Subject: [Newbie] Need help with quick text proggy. Message-ID: <24d8090a.0210091854.725f4c9f@posting.google.com> I havn't programmed in python in a while (not since 2.0) but I just found myself in a predicament where I really need to write a program and write it fast. Python still seems to be the best choice even though I'm very rusty and wasn't to good to start with. Here is my problem. I've got a text file that is a list of elements. a time followed by a number on each line. Like this for example: 1:46p 65 5:45a 99 2:36p 88 10:53a 79 5:10a 86 2:43p 169 10:14a 55 I just found out that all my times are 6 hours off. (AARGH!) and I need some help writing a program that will update all those timestamps for me. Any help at all is appreciated, wheter it be links, some source, or whatever. Thank a bunch. Corey From dave at boost-consulting.com Fri Oct 11 18:23:38 2002 From: dave at boost-consulting.com (David Abrahams) Date: 11 Oct 2002 18:23:38 -0400 Subject: SWIG and XML and Python References: Message-ID: Dave Kuhlman writes: > David Abrahams wrote: > > > Dave Kuhlman writes: > > > >> SWIG 1.3 can now generate XML documents. These XML documents describe > >> the interface fed into SWIG. > > > > Interesting. How does this compare with projects like GCC_XML and > > I am not well-educated on GCC_XML, however from a quick read at the GCC_XML > Web site (http://www.gccxml.org/HTML/Index.html), GCC_XML produces XML that > describes your *code*. That includes the interface, of course... > SWIG 1.3 with the "-xml" option produces XML that > describes the *interface* to your code. This is a bit over-simplified, > but you can use SWIG 1.3 with "-xml" to produce an XML description of your > C/C++ .h header files, whereas you can use GCC_XML to produce an XML > description of your .c and .cpp/.cxx source code files. ...which might be just what I need. How much of C++ can it handle? Every time I try to throw advanced C++ code at one of these tools, it chokes and dies. > Or, for those of you who want information that you can use, GCC_XML could be > used as a front-end to a compiler, whereas SWIG 1.3 with "-xml" could be > used as a front-end to a tool that makes interfaces (code libraries, etc) > and descriptions of them available to programming tools. > > And for those of you who are not familiar with SWIG, this XML stuff is not > its primary use. SWIG is normally used to produce scripting language > extensions from C/C++ code. For example, and importantly, you can > (sometimes) feed a C or C++ header file to SWIG, and it will produce > wrappers that enable you to use the functions and classes described in that > header from Python. It's in the same ecological niche as Boost. Just in the same niche roughly as the Boost Python library (though I tend to think of SWIG as being in a different broad class of tools which parse C++ code for purposes other than generating object code). Boost as a whole is a much broader community and collection of C++ libraries and has nothing particularly to do with Python. > Yes? No? Maybe? > David, I see "Boost" in your Sig. Could you give us a quick > comparison of SWIG and Boost, please. Last time I did that I ticked off David Beazley (the lead SWIG developer) ;-) OK, here goes an attempt at an unbiased description. I've never used SWIG so what I'm writing here is based on documentation and hearsay (what's that Mark Twain said? "There's lies, damn lies, and documentation?"): SWIG is a multi-language interoperability tool. It attempts to parse the declarative parts of C and C++ (and Fortran?) code and automatically generate wrappers for the functions and classes appropriate for a variety of scripting languages, including Python, Perl, and Tcl. For really simple jobs SWIG may be able to read your header file and generate wrappers with no extra help. For real-world jobs you usually end up writing SWIG-ized versions of your header files which include some extra directives aimed at helping SWIG with the wrapping job. Boost.Python is a C++ library which allows you to write some simple C++ expressions which end up building an extension module for you. This ends up looking like a kind of IDL (Interface Definition Language). So, given: struct World { void set(std::string msg) { this->msg = msg; } std::string greet() { return msg; } std::string msg; }; You can generate a corresponding extension module with: #include using namespace boost::python; BOOST_PYTHON_MODULE(hello) { class_("World") .def("greet", &World::greet) .def("set", &World::set) ; } That's the capsule summary, but there's a lot more to it. See http://www.boost.org/libs/python for more details. > > Synopsis? > > > > Don't know about this one. "Synopsis" is too common a term, so a Google > search did not give me anything useful. Do you have a link? Now, you have > *me* interested. http://synopsis.sf.net It uses a "real" C++ front-end to parse the input and generates a Python AST. -- David Abrahams * Boost Consulting dave at boost-consulting.com * http://www.boost-consulting.com From aahz at pythoncraft.com Thu Oct 10 14:05:22 2002 From: aahz at pythoncraft.com (Aahz) Date: 10 Oct 2002 14:05:22 -0400 Subject: Concrete classes -- stylistic question References: Message-ID: In article , Michael Hudson wrote: > >Not sure it's useful, but it was fun :) You're sick. Go sit over by the Martellibot. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From donkan7 at yahoo.com Wed Oct 16 10:17:41 2002 From: donkan7 at yahoo.com (Richard Bow) Date: Wed, 16 Oct 2002 07:17:41 -0700 Subject: How to print an integer with commas; E.g., 3,056,789 References: Message-ID: "Paul Simmonds" wrote in news:mailman.1034770761.2768.python-list at python.org: > def comma(bigint): > strint=str(bigint) > i=0 #increment counter > j=len(strint)%3 #number of chars @ beginning > newstr=strint[0:j] > while i newstr=newstr+','+strint[(3*i)+j:(3*(i+1))+j] > i=i+1 > return newstr Thanks very much to all for the advice. Before I got back here to read it, and instead of going to bed, I remembered slices and came up with this script, which I want to turn into a function, but don't know how yet. ====================================== n = raw_input("Enter a non-negative integer: ") n = long(n) print "n = ", n s = str(n) sub = "" if n < 1000: print "No commas needed" else: for k in range(len(s)): if k > 0 and k % 3 == 0: char = "," sub = char + sub char = s[-k - 1] sub = char + sub print "n with commas is", sub ============================== Seems to work, but can the code be improved? Thanks again, Richard Bow From mchermside at ingdirect.com Wed Oct 30 10:50:53 2002 From: mchermside at ingdirect.com (Chermside, Michael) Date: Wed, 30 Oct 2002 10:50:53 -0500 Subject: difficult regular expression Message-ID: <902A1E710FEAB740966EC991C3A38A8903C35AFF@INGDEXCHANGEC1.ingdirect.com> > It's easy to grab the section containing the text "Cats ... foods." (not > including the Chickens section.) However, I need to get just the items: > mice, rats, rabbits, marmots. Not all regular expression parsers are equivalent. Actually, that's not true... mathematically, they ARE equivalent in important ways (and some aren't), but for practical purposes, RE engines fall into two categories: those that support basic grep features (plus-or-minus a few features) and those that support perl 5 features (plus-or-minus a few features). Python supports the perl 5 features (give-or-take a few features). Two of those features are "look-ahead" and "look-behind" assertions. these are zero-width assertions that make the RE match (or not match) based on whether some (subsidiary) RE matches the string starting/ending at that point... but the text matched by the subsidiary RE does NOT become part of the match of the main RE. If you find this description confusing, check out the docs: http://python.org/doc/current/lib/re-syntax.html So I'm going to try to use these to create a RE that solves your problem. (The following is a transcript of my python session, but with the typos and mistakes taken out.) >>> text = """ ... Here is a list of foods and consumers: Dogs eat , , ... , and other foods. Cats eat , , , , ... and other foods. Chickens eat , , , and other ... foods. Wow, that's a lot of eating! ... """ >>> # The text is really all one long line >>> text = text.replace('\n',' ') >>> re_1 = re.compile(r'Cats eat ((<.*?>, )+)and other foods.') >>> matchObj = re_1.search(text) >>> matchObj.groups()[0] ', , , , ' >>> # Okay, that worked. In fact, it might be enough to >>> # solve the whole problem. But we'll try it with the >>> # look-ahead/behind assertions anyway. >>> re_2 = re.compile(r'(?<=Cats eat )((<.*?>, )+)(?=and other foods.)') >>> matchObj = re_2.search(text) >>> # now let's see what the entire pattern matched >>> matchObj.group(0) ', , , , ' >>> # Yep... it works. Does that help? -- Michael Chermside From t_therkelsen at hotmail.com Tue Oct 1 15:03:31 2002 From: t_therkelsen at hotmail.com (Troels Therkelsen) Date: 01 Oct 2002 19:03:31 GMT Subject: Is the word "Python" copyrighted/trademarked? Message-ID: Hey everybody, I tried figuring out the answer to the question in the subject by reading the Python 2.2 license in the end of the library reference. "This License Agreement does not grant permission to use PSF trademarks or trade name in a trademark sense to endorse or promote products or services of Licensee, or any third party." My question is whether the word "Python" classifies as a PSF trademark or trade name? Eg., if I wanted to create a web server in Python (not that I want to), could I call it "Python Web Server" without breaking any rules? Regards, Troels Therkelsen From gerhard.haering at gmx.de Sun Oct 20 10:53:18 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 20 Oct 2002 14:53:18 GMT Subject: cgi integration question 2 References: Message-ID: Ken wrote in comp.lang.python: > Hello, I have this problem which I don't know what it means or how > to fix, can someone help me? > > Traceback (most recent call last): File "chessboard.cgi", line 143, in ? > outf.close() IOError: [Errno 32] Broken pipe Dunno why, but I have a few remarks nonetheless. > Python frontend program: > lines = [] > outf, inf = os.popen2("knight") > print >>outf, size #size > print >>outf, startX #start X position > print >>outf, startY #start Y position > outf.close() #<<========= Refer to this line 143 > time.sleep(1) Frankly, sleeping in the context of synchronous IO doesn't make any sense. > maxSize = string.atoi(size) * string.atoi(size) > while len(lines)< maxSize: > lines = inf.readlines() #Output produce by back end program ["34", "35", > ...etc] readlines() reads the *whole* output, so if after that you read again, it will block forever. If you want to read line by line, use readline() instead. But read the docs about read() and readline(), as you'll find important info there, for example that if it returns an empty string it means that you've reached EOF :-) > if len(lines)==maxSize: > inf.close() > break > time.sleep(1) You could rewrite this as: outf, inf = os.popen2("night") print >>outf, ... ... outf.close() lines = inf.readlines() inf.close() -- Gerhard From max at alcyone.com Sun Oct 13 01:10:54 2002 From: max at alcyone.com (Erik Max Francis) Date: Sat, 12 Oct 2002 22:10:54 -0700 Subject: A simple generator application References: Message-ID: <3DA9005E.B2C8B5D9@alcyone.com> Doug Fort wrote: > __copyright__ = "Copyright (C) Doug Fort -- Released to the public > domain" Note that placing a work in the public domain explicitly waives all copyrights, so this notice is faulty and could be the subject of further confusion. Either it's copyrighted by you or it's public domain, but not both. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ A good indignation brings out all one's powers. \__/ Ralph Waldo Emerson Church / http://www.alcyone.com/pyos/church/ A lambda calculus explorer in Python. From anton at vredegoor.doge.nl Mon Oct 21 15:23:43 2002 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Mon, 21 Oct 2002 21:23:43 +0200 Subject: ANNOUNCE: Building C/C++ Extensions for Python References: <3dae493f@duster.adelaide.on.net> <3db3462b$1@duster.adelaide.on.net> Message-ID: On Mon, 21 Oct 2002 11:09:53 +1000, "Gerald Squelart" wrote: >I wrote in message: >> "eric [Idle?][Terry?] jones" wrote >> [...] Enthought is [...] intense [...] to benefit from [...] Users [...] $2400.00 >> US. >> And now, for something completely different: >> Well, there's egg and bacon; egg, sausage and bacon; egg and spam [...]. >> [:-)] > >After a couple of email exchanges with Eric, it seems I was wrong to assume that >commercial posts were unwelcome in this newsgroup. >Please accept my apologies for my inappropriate behaviour. It was not inappropriate at all. Not at all ... This is a public newsgroup, not moderated or owned by anyone. If someone knows otherwise please inform me immediately because it would be time for me to leave. >I hope I raised a few smiles with the spam song, at least ;-) You sure did, and I don't like people making big money by providing basic education only to the rich. >Here's their web page for the training again: >http://www.enthought.com/training/building_extensions.html >And I'm happy to have learned that they are involved in scipy: >www.scipy.org :-( > >Have a good day, >Gerald. > I had a good day because of your first message but I guess this balances it out a bit. Regards, Anton. From mcfletch at rogers.com Fri Oct 11 15:02:22 2002 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Fri, 11 Oct 2002 15:02:22 -0400 Subject: Leibniz_Pi.py References: Message-ID: <3DA7203E.2040505@rogers.com> Well, the rounding errors with FP make this, as far as I can tell, basically pointless, but if you want a "better" approach, I think this is still "correct", and is a lot clearer (IMO), though as David points out, this isn't a "good" way to calculate pi. Basic principles I'm following are that ranges are the enemy (xranges are your friend, that alone gives a marked increase in speed for your algo), and that doing an extra (N) arithmetic operations (to switch sign) will be expensive when N is very large: def sum(bottom, top=1.0): result = 0 for divisor in bottom: result += (top /divisor) return result def calculate( iterations ): """Approximate pi with iterations number of iterations""" pos = sum( xrange( 1, iterations*2, 4), 1.0) neg = sum( xrange( 3, iterations*2, 4), -1.0) return 4.0* (pos + neg) Note that this will produce slightly different results than yours even for low numbers of iterations (such as 12 on my machine). I'm not sure if that's a bug in my code, or just FP being non-commutative. If you really wanted to play with this algo more, you'd probably use Numeric, which, with an algo like above, would probably make it necessary to use a much higher number of iterations to be timeable (but would still return junk most likely). BTW, for interest's sake: Using psyco to bind "sum" above makes my algo run in approx 22% of original time (.98s to .21s). While using it on yours still takes 29% of its original (1.32s to .39s) (which gets you right about the same overall run-time as the Java version). Overall improvement from original algo to psyco'd new algo is to run in around 16% of time, or about 1.6 seconds on your machine (assuming psyco is ~ equivalent in optimisations across CPUs). Just using the new algo gives you only about 74%, so still twice as slow as the Java. Enjoy yourself, Mike Cousin Stanley wrote: >Yesterday in the news group comp.lang.java.help >I found a Java example of the Leibniz Pi approximation >and converted the Java code to Python ... > >The numerical results from either version >using a LARGE number of terms as a program argument >provide approximations for the number Pi that seems correct ... > >Using 1 million terms as an input argument, >the Java version is a bit faster, which I think >is expected ... > > On a 250 MHz Win98 machine ... > > Java SDK 1.4 ....... ~ 3-4 seconds > Python 2.2.1 ......... ~ 9-10 seconds > >Since I am fairly new to BOTH Java AND Python, >I'm wondering if there are any ... > > obvious oversights ??? > Python improvements ??? > >Python code follows ... > >Cousin Stanley > >---------------------------------------------------------------- > >''' > Leibniz_Pi.py > > Pi = 4 * ( 1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + 1/13 - 1/15 ... ) > > Using one million terms provides a good approximation ... > > Posted to the NewsGroup > comp.lang.java.help 2002-10-10 > By Jonas Lindstr?m > > Converted to Python > By Stanley C. Kitching >''' > >import sys >print '\n Approximate Pi via Leibniz Sequence ' > >def calculate_pi( nTerms ) : > > limit = ( 2 * nTerms ) - 1 > > if ( ( limit - 1 ) % 4 ) == 0 : > sign = +1.0 > else : > sign = -1.0 > > sum = 0.0 > > for i in range( limit , 0 , -2 ) : > sum += sign / i > sign = -sign > > return 4.0 * sum > >nTerms = int( sys.argv[ 1 ] ) > >Pi = calculate_pi( nTerms ) > >print '\n Terms : ' , nTerms >print '\n Pi : ' , Pi > > > > -- _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From shalehperry at attbi.com Mon Oct 7 19:06:26 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Mon, 7 Oct 2002 16:06:26 -0700 Subject: newbie question on class vars In-Reply-To: References: Message-ID: <200210071606.26093.shalehperry@attbi.com> On Monday 07 October 2002 15:46, JXSternChangeX2R wrote: > > Oops, come to think of it, I did mean it to be by instance. > > Tho my syntax question, remains. > > J. then you want: class Foo: def __init__(self): self.__myvar = 1 yes, you must use self (or whatever you call the variable). This is just the way things are. You learn to prefer it after using Python for a while and then going back to other languages. if you place the variable as: class Foo: myvar = 1 def __init__(self): pass then you are making the variable global to all instances of the class as I demonstrated in my last mail. From henrik.motakef at web.de Tue Oct 8 16:10:43 2002 From: henrik.motakef at web.de (Henrik Motakef) Date: 08 Oct 2002 22:10:43 +0200 Subject: SOT : & in XML-documents References: <87bs64903u.fsf@pokey.henrik-motakef.de> Message-ID: <877kgs8zek.fsf@pokey.henrik-motakef.de> "Thomas Weholt" <2002 at weholt.org> writes: > Damn!! The original data is filled with it. My solution so far has been to > keep a list ( limited to '&' so far ) of characters to replace ( '&' is > replaced with 'and' etc. ). Not necessarily a good idea - there is a reason for & having to be escaped: It is used in entity references like  , you probably wouldn't like to convert all non-breaking space characters to "andnbsp;"... > Are there any other characters I must avoid/replace? The character '<' has to be written as <. Regards Henrik From gherron at islandtraining.com Fri Oct 18 02:59:58 2002 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 17 Oct 2002 23:59:58 -0700 Subject: Python's driving me mad. Invalid token? In-Reply-To: <5f30c71b.0210172237.28a4f847@posting.google.com> References: <5f30c71b.0210172237.28a4f847@posting.google.com> Message-ID: <200210172359.58570.gherron@islandtraining.com> On Thursday 17 October 2002 11:37 pm, Jim wrote: > Today I installed Python 2.2.2. I wrote a short script that backs up > project files, and I'm getting a weird error that I've never gotten > before. I have spent hours trying to figure this out - can anyone > help? > > My code: ... some code deleted > def CopyFiles(dirname,fnamelist): > for name in fnamelist: > destFile = open((dirname+"""\"""+name),'w') > srcFile = open(name,"r") > destFile.write(srcFile.read()) > srcFile.close() > destFile.close() ... more code deleted> > The error: > > File "C:\***\backup.py", > line 42 > MainProg() > ^ > SyntaxError: invalid token The problem is that the triple quoted string is not closed (as any good colorizing editor should be able to show). The line ..."""\"""+name starts a string with """ then has a backslashed escaped quote which is not counted as a closing quote because of the backslash, then two quotes which is not enough to close the triple-quoted string. The intererter continues to the end of the file looking for a triple quote, and produces the error when none is found. If you want a string with a backslash, try '\\' or "\\". Better yet, to create a file path from component parts, use the function 'join' from the os.path module. This does the right thing on any OS so your program is os independent. Try: import os ... pathname = os.path.join(dirname, name) destFile = open(pathname,'w') Gary Herron gherron at islandtraining.com From geek+ at andrew.cmu.edu Wed Oct 2 12:34:23 2002 From: geek+ at andrew.cmu.edu (Brian E Gallew) Date: Wed, 2 Oct 2002 12:34:23 -0400 Subject: Merging lists has made my brain hurt. In-Reply-To: <3D9B1953.3030109@moving-picture.com> References: <3D9B1953.3030109@moving-picture.com> Message-ID: <200210021634.g92GYNUK012530@smtp6.andrew.cmu.edu> Then spoke up and said: > NNTP-Posting-Host: soho6.sohonet.co.uk > User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.0.0) Gecko/20020529 > > Hi All, > > I have a list containing an arbitrary number of other lists. The > internal lists contain strings. For example > lol = [ > ['aaa', 'bbb', 'ccc'], > ['bbb', 'ccc', 'ddd'], > ['ccc', 'ddd', 'eee'] > ] > > I want to merge the three lists into a single list that only contains > the strings present in all three lists. In the above case I want to end > up with > ['ccc'] > > This has me utterly stumped. Any help is appreciated.The only articles > about merging strings that I've managed to find so far have been about > merging strings so that you don't get repeats. Not quite what I'm > looking for. This seems pretty easy to me. Of course, it assumes that you can destroy lol. while len(lol) > 1: l1 = lol.pop() l2 = lol.pop() l3 = [x for x in l1 if x in l2] lol.append(l3) lol=lol.pop() From see_reply_address at something.invalid Thu Oct 10 17:53:11 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Fri, 11 Oct 2002 10:53:11 +1300 Subject: newbie question on threads References: Message-ID: <3DA5F6C7.1070307@something.invalid> Gon?alo Rodrigues wrote: > Hi, > > I just started out studying threads and fleshing out my first > multithreaded app. But there is still one thing that I'm not completely > sure: If a thread acesses a shared object via a non-altering state > method, and without locking, is this safe? In general, no, it's not safe if another thread could be modifying the object at the same time, because the reading thread could see it in an inconsistent state. > Better safe-than-sorry strategy? Yes, unless you really know what you're doing, it would be best to always use a lock. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From bokr at oz.net Sat Oct 12 03:14:45 2002 From: bokr at oz.net (Bengt Richter) Date: 12 Oct 2002 07:14:45 GMT Subject: Leibniz_Pi.py References: Message-ID: On Fri, 11 Oct 2002 10:14:38 -0700, "Cousin Stanley" wrote: >Yesterday in the news group comp.lang.java.help >I found a Java example of the Leibniz Pi approximation >and converted the Java code to Python ...=20 > >The numerical results from either version=20 >using a LARGE number of terms as a program argument >provide approximations for the number Pi that seems correct ...=20 > >Using 1 million terms as an input argument, >the Java version is a bit faster, which I think >is expected ...=20 > > On a 250 MHz Win98 machine ...=20 > =20 > Java SDK 1.4 ....... ~ 3-4 seconds > Python 2.2.1 ......... ~ 9-10 seconds > >Since I am fairly new to BOTH Java AND Python, >I'm wondering if there are any ...=20 > > obvious oversights ??? > Python improvements ??? > >Python code follows ... > >Cousin Stanley > >---------------------------------------------------------------- > >'''=20 > Leibniz_Pi.py > > Pi =3D 4 * ( 1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + 1/13 - 1/15 ... ) > > Using one million terms provides a good approximation ... > > Posted to the NewsGroup > comp.lang.java.help 2002-10-10=20 > By Jonas Lindstr=F6m > > Converted to Python > By Stanley C. Kitching >''' > >import sys >print '\n Approximate Pi via Leibniz Sequence ' > >def calculate_pi( nTerms ) : > > limit =3D ( 2 * nTerms ) - 1=20 > > if ( ( limit - 1 ) % 4 ) =3D=3D 0 : =20 > sign =3D +1.0=20 > else :=20 > sign =3D -1.0 > > sum =3D 0.0 > > for i in range( limit , 0 , -2 ) :=20 > sum +=3D sign / i > sign =3D -sign > > return 4.0 * sum=20 > >nTerms =3D int( sys.argv[ 1 ] )=20 > >Pi =3D calculate_pi( nTerms ) > >print '\n Terms : ' , nTerms >print '\n Pi : ' , Pi > > [ 0:01] C:\pywk\pi>pisigint.py (Type Ctrl-C to stop generating pi) 50 4085.12 dig/sec 31415926535897932384626433832795028841971693993751 100 3292.99 dig/sec 05820974944592307816406286208998628034825342117067 150 2422.61 dig/sec 98214808651328230664709384460955058223172535940812 200 1851.27 dig/sec 84811174502841027019385211055596446229489549303819 250 1473.79 dig/sec 64428810975665933446128475648233786783165271201909 300 1277.74 dig/sec 14564856692346034861045432664821339360726024914127 350 1087.28 dig/sec 37245870066063155881748815209209628292540917153643 400 1003.15 dig/sec 67892590360011330530548820466521384146951941511609 450 852.50 dig/sec 43305727036575959195309218611738193261179310511854 500 742.55 dig/sec 80744623799627495673518857527248912279381830119491 550 666.12 dig/sec 29833673362440656643086021394946395224737190702179 600 624.75 dig/sec 86094370277053921717629317675238467481846766940513 650 595.61 dig/sec 20005681271452635608277857713427577896091736371787 700 535.77 dig/sec 21468440901224953430146549585371050792279689258923 750 501.08 dig/sec 54201995611212902196086403441815981362977477130996 800 470.28 dig/sec 05187072113499999983729780499510597317328160963185 850 436.58 dig/sec 95024459455346908302642522308253344685035261931188 900 333.36 dig/sec 17101000313783875288658753320838142061717766914730 950 363.52 dig/sec 35982534904287554687311595628638823537875937519577 818577805321712 965 Total digits (965 total digits) (I hit Ctrl-C fairly shortly). You can redirect the pi digits, and watch the left part on a single line being rewritten, which looks like so: [ 0:10] C:\pywk\pi>python pisigint.py >zz.txt (Type Ctrl-C to stop generating pi) 2455 Total digits [ 0:10] C:\pywk\pi> ----< pisigint.py >------------------------- #!/usr/bin/python # Print digits of pi forever, unless you hit Ctrl-C # The output is split between stderr and stdout so that you can # redirect the pi digits to a file, like so # python pisiginit.py > pidigits.txt # and still see how many and how fast digits are being output. The latter # info is rewritten without \n, so it does not scroll. If you don't # redirect you see the latter to the left and the pi digits 50 at a time # to the right. This is a modified version of the algorithm as found # somewhere on the Ruby site. # # The algorithm, using Python's 'long' integers ("bignums"), works # with continued fractions, and was conceived by Lambert Meertens. # # See also the ABC Programmer's Handbook, by Geurts, Meertens & Pemberton, # published by Prentice-Hall (UK) Ltd., 1990. import sys, signal from time import clock class SigHandler: def __init__(self): self.signaled = 0 def __call__(self, sn, sf): self.signaled += 1 sh = SigHandler() oldHandler = signal.signal(signal.SIGINT,sh) k, a, b, a1, b1 = 2L, 4L, 1L, 12L, 4L digits=0 # count to show progress lines = 0 digline = [] start=clock() sys.__stderr__.write('\r(Type Ctrl-C to stop generating pi)\n') while not sh.signaled: # Next approximation p, q, k = k*k, 2*k+1, k+1 a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1 # Print common digits d = a / b d1 = a1 / b1 while d == d1: digits += 1 #sys.__stderr__.write('\r%5d' % (digits,)) digline.append(d) if len(digline)==50: sys.__stderr__.write('\r%5d %8.2f dig/sec ' % (digits, 50.0/(clock()-start))) lines += 1 print ''.join(map(lambda x: chr(x+48),digline)) digline = [] start=clock() a, a1 = 10*(a%b), 10*(a1%b1) d, d1 = a/b, a1/b1 sys.__stderr__.write('\r'+' '*24) if digline: print ''.join(map(lambda x: chr(x+48),digline)) sys.__stderr__.write('\r%5d Total digits \n'% (lines*50+len(digline))) print '\n(%d total digits)' % (lines*50+len(digline)) signal.signal(signal.SIGINT,oldHandler) -------------------------------------------- Regards, Bengt Richter From nilesh at smalcamera.com Thu Oct 31 17:49:14 2002 From: nilesh at smalcamera.com (Nilesh Agarwalla) Date: 31 Oct 2002 14:49:14 -0800 Subject: wxPython TreeCtrl bug ? References: Message-ID: <5a2bc854.0210311449.21d75367@posting.google.com> "Uwe C. Schroeder" wrote in message news:... > Hi, > > I'm using the current development versions of wx* > You can even use the demo code to test this. Obviously the wxTreeCtrl > doesn't handle/emit/whatever all events anymore. EVT_TREE_SEL_CHANGED as > well as EVT_TREE_SEL_CHANGING are processed correctly under Linux, however > they don't show up under MSW. > My MSW is a 98 with the common controls upgraded. > Versions are identical (both Linux and MSW as of yesterday on wxwindows.org > and wxpython.org) > > Anyone else having this problem under MSW ? > > UC Hi Uwe, I too am having the problem on Windows 98 machines. The error does not seem to occur on Windows 2000/XP. The previous version of wxWindows I used (about 8 months old) worked fine. I'm trying to trace when the bug was introduced. Let me know if you have any luck. From a-steinhoff at web.de Thu Oct 31 10:53:33 2002 From: a-steinhoff at web.de (Armin Steinhoff) Date: 31 Oct 2002 07:53:33 -0800 Subject: pyQt - opinions References: <3dc01a1c$0$3342@echo-01.iinet.net.au> Message-ID: "Rob Hall" wrote in message news:<3dc01a1c$0$3342 at echo-01.iinet.net.au>... > I've been comparing different GUI development systems for a few weeks now > and thought I'd settle on wxPython. That is, until I had a look at PyQt. > > Has anyone tried it? If so, are there any gotchas? How does it compare to > wx? > > The documentation looks very good which is a bonus. ... and the bests is it works as documented :) I have recently released a configuration tool with PyQT, gadfly, Python ... works with Linux, M$Win and QNX6. No problems at all ... Armin > > Rob From maxm at mxm.dk Thu Oct 3 08:39:40 2002 From: maxm at mxm.dk (Max M) Date: Thu, 03 Oct 2002 14:39:40 +0200 Subject: Text to unicode Message-ID: <6TWm9.66667$Qk5.2826099@news010.worldonline.dk> I have a series of textfiles that are really utf-8 files in disguise. What I mean is that an editor sees them as text files. But characters that really should be one special character are represented as two *wrong* characters. As far as I understand the first two bytes in a unicode file has a special value that tells what kind of encoding the text file has. My guess is that my files are missing these two bytes so that my editor and Python believe it to be a text file. (Thay have been saved by a third party tool) It is html files, and the encoding in them is set to utf-8. When I view them in a browser I see the correct characters. I cannot seem to get my mind around how to convert them into Unicode. content = unicode(f.read(), 'utf-8') >>> UnicodeError: UTF-8 decoding error: unexpected code byte content = unicode(f.read()) >>> UnicodeError: ASCII decoding error: ordinal not in range(128) Any takers? -- regards Max M The reason I don't reach any higher is that I stand on the shoulders of little people. From rich at worldsinfinite.com Thu Oct 31 10:08:00 2002 From: rich at worldsinfinite.com (Rich Harkins) Date: 31 Oct 2002 10:08:00 -0500 Subject: Dictionary Enhancement? (Take 2) Message-ID: <1036076881.1134.22.camel@rich-laptop> On Thu, 2002-10-31 at 09:12, Rich Harkins wrote: > I was wondering if anyone else had been wanting to enhance Python > dictionaries such that instead of raising KeyError in the case of errors > that another method on the dictionary object, say __makeitem__ would be > called to try to auto-generate an appropriate value. That __makeitem__ > method would then either raise KeyError itself or return the value to > insert into the dictionary and return through __getitem__. > > I scanned the PEP's but didn't see anything similar. > > Rich > Since I'm already getting replies about setdefault() I'd better post some Python code describing what I'm talking about: class SuperDict(dict): """ A dictionary that calls a member method __makeitem__ when a KeyError would normally be generated by __getitem__. This allows for auto-generation of dictionary entities. """ def __getitem__(self,name): try: return dict.__getitem__(self,name) except KeyError: obj=self.__makeitem__(self,name) self[name]=obj return obj def get(self,name,default): try: return self[name] except KeyError: return default def __makeitem__(self,name): # Create an object automatically from name or raise KeyError # Default is to raise KeyError raise KeyError,name There are two advantages to this over setdefault(): 1) The subclass knows what to create as child keys (useful for directory listing dictionaries where the values sometimes shouldn't exist until they're demanded). In cases where this is useful the logic for the created child values is only known to the subclass and should *not* be replicated throughout the "client" code. 2) Calling setdefault() *creates* the to-be-assigned value regardless of whether the value is put in the dictionary or not. I only want to create the subvalue if and only if the key doesn't exist. I probably should have posted that the first time, sorry about the confusion. Rich From richie at entrian.com Fri Oct 11 05:44:43 2002 From: richie at entrian.com (Richie Hindle) Date: 11 Oct 2002 02:44:43 -0700 Subject: natural language regexp References: Message-ID: <8a6ba1da.0210110144.251133a3@posting.google.com> Hi Mark, > I once ran across a package/module for doing regular expressions in Python > in natural language--but I can't recall what it's called You're probably thinking of rxb by Ka-Ping Yee. See http://lfw.org/python/ -- Richie Hindle richie at entrian.com From a.clarke11 at pop.ntlworld.com Wed Oct 2 18:56:43 2002 From: a.clarke11 at pop.ntlworld.com (a.clarke11) Date: Wed, 02 Oct 2002 23:56:43 +0100 Subject: newbie: find position of item in a list References: <3D9B01B4.4000700@stacom-software.de> Message-ID: <3D9B79AC.887BF64@pop.ntlworld.com> Hi So what's wrong with l.find('b')? Or, what's the gain in using index()? Tia Tony Kerim Borchaev wrote: > Hello Alexander, > > Wednesday, October 2, 2002, 6:24:52 PM, you wrote: > > AE> Hallo Again, > > AE> i wonder weather there is no expression of finding the position of a element is a list like: > > AE> l = ['a', 'b', 'c', 'd', 'e'] > > AE> l.find('b') > AE> >> 1 > > AE> Have I overseen something in the documentation to python ? > > yes: > > >>> l = ['a', 'b', 'c', 'd', 'e'] > >>> l.index('d') > 3 > > Best regards, > Kerim mailto:warkid at storm.ru > > AE> Tanks a lot > AE> Alexander From alessandro.bottoni at infinito.it Fri Oct 18 03:58:06 2002 From: alessandro.bottoni at infinito.it (Alessandro Bottoni) Date: Fri, 18 Oct 2002 09:58:06 +0200 Subject: Python code examples that _generate_ HTML/XML? In-Reply-To: References: Message-ID: <200210180749.g9I7nel01967@mail2.infinito.it> Alle 22:29, gioved? 17 ottobre 2002, hai scritto: > I'm creating an app for use in-house, that will assist a user (complete > novice) in creating web pages. So after they complete a session I will > need to take their "instructions" and generate the items necessary to > display the desired pages in a browser. Therefore I'll be creating the > HTML/XML tags and code dynamically for things like list boxes, buttons, > hrefs, graphics, etc. Has anybody seen any code samples or URL's for such > that show how to do this in Python? Are there parts of the Zope source > code that might be helpful to look at, if so what 'py' files? > > thx Robert, if you just have to generate HTML tags (code) from within a Python program, you can take advantage of the HTMLGen library by Robin Friedrichs. You can find it at: http://starship.python.net/crew/friedrich/HTMLgen/html/main.html and: http://www.zenspider.com/Languages/Python/HTMLGen.html That is not the only one: I think you can find a large collection of tools like HTMLGen at the "Vaults of Parnassus "web site (see the python main web site fot the link) and at other python-devoted sites on the web. Try "HTML" and "Python" from Google or Yahoo, as well. Of course, you can just print HTML code to the standard output, or any other file, with a simple "print" instruction, as well. For example: print "

My Title

" or: content = "The world" initag = "

" endtag = "

" output = initag + content + " is not enough "+endtag print output (check the python manual for the characters of your text and of your tags that need to be backslashed prior of printing, most likely "\", "/" and "<", ">" ) --------------------- Alessandro Bottoni From jussij at zeusedit.com Mon Oct 7 18:26:49 2002 From: jussij at zeusedit.com (Jussi Jumppanen) Date: Tue, 08 Oct 2002 08:26:49 +1000 Subject: ANN: Zeus Programmers Editor V3.80 Message-ID: <3DA20A29.7709@zeusedit.com> The latest release of the Zeus for Windows programmer's editor is now available. To see what is new vist: http://www.zeusedit.com/whatsnew.html to read what other's have to say about the power of Zeus goto: http://www.zeusedit.com/awards.html or to see Zeus in action goto: http://www.zeusedit.com/lookcomp.html or to test drive Zeus for yourself download the fully functional shareware version from this link: http://www.zeusedit.com/download.html (3.3 Mega Byte) Jussi Jumppanen http://www.zeusedit.com From jb at yahoo.de Sun Oct 13 05:41:03 2002 From: jb at yahoo.de (JB) Date: Sun, 13 Oct 2002 11:41:03 +0200 Subject: Problems executing code with exec Message-ID: <3da93d8b_5@news.newsgroups.com> I have a piece of code that I should like to execute with the exec statement. Here is this code: def lotfusspunkt(p,g): (p1,p2) = schnitt(kreis(g.a(),p),kreis(g.b(),p)) return schnitt(gerade(p1,p2),g) and here is the procedure that executes it (with the text above being in the variable text): def start(self): i = 0 statement_list = string.split(txt,'\n') for statement in statement_list: try: exec statement+'\n' in user_name_space except: txt = str(sys.exc_info()[1]) return i i += 1 The idea is that upon return the line number of the line that caused the error is returned and I can set a cursor to this line in the text editor window that contains the statements. On the other hand, when I call exec with exec text+'\n' in user_name_space that works but then I cannot find out the number of the line that caused the error. If I use something like i = traceback.tb_lineno(sys.exc_info()[2]) then the line number of the line that contains the exec statement is returned and not the line number of the line in the variable text. Sometime it is possible to parse the error message (in sys.exc_info()[2]) to get the correct line number but sometimes this is not possible. Can anybody help me? TIA, -- Janos Blazi -----------== Posted via Newsfeed.Com - Uncensored Usenet News ==---------- http://www.newsfeed.com The #1 Newsgroup Service in the World! -----= Over 100,000 Newsgroups - Unlimited Fast Downloads - 19 Servers =----- From fperez528 at yahoo.com Tue Oct 22 13:54:35 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Tue, 22 Oct 2002 11:54:35 -0600 Subject: ipython keybinding References: Message-ID: John Hunter wrote: > > I just installed ipython http://www-hep.colorado.edu/~fperez/ipython/. > Wow, what a fantastic python shell. Thanks. Glad you like it. > So far I have just two items on my wishlist: > > 1) Is it possible to bind the 'up/down' arrow keys to the same > function that C-n/C-p are. The latter only bring up previous > commands that match what has been typed before, while the former > bring up the previous/next command regardless of the text entered > so far on the prompt. I couldn't do it. Tried a lot, never got it to work. But if someone can figure it out, I'll be glad to fix it for a future release. That's how I use my normal shell and would love to set the same thing in ipython, but I wasn't able to fix this. > 2) Is it possible to run ipython in an emacs shell, or is this in the > works (ala matlab-shell)? I fear the answer is no, since the > default editor for the @edit command is vi, which leads me to guess > that Fernando is a vi user. This is not a big requirement, since I > can just pop open a quick emacs session from within ipython with > @edit, but we emacs junkies like to do everything within one emacs > session, for cutting and pasting text across buffers that are > already open, etc... Actually, @edit is bound to call $EDITOR. I am an XEmacs user myself, the only thing I know how to do with vi is 'C-Z; killall vi' when I accidentally open it :) You can set your editor environment variable to anything you want. I personally use jed for quick edits, so I set $EDITOR to that, and I use Xemacs for heavy-duty work. Now, with Alex Schmolck's help who patched the Xemacs python mode, it _is_ possible to use ipython inside emacs as your python shell. I just uploaded the new python-mode.el file to the download directory for ipython, so you can grab it from there. I also put the following in my emacs config file, as per Alex's instructions: (defun my-activate-ansi-colors () (require 'ansi-color) (ansi-color-for-comint-mode-on)) (add-hook 'py-shell-hook 'my-activate-ansi-colors) ;; Regular expression that describes tracebacks for IPython in context and ;; verbose mode. (add-hook 'python-mode-hook '(lambda () ;; this works for @xmode verbose or context (setq py-traceback-line-re "^\\(.+?\\) in [^\00]+?\n--> \\([0-9]+\\) +"))) (setq py-shell-input-prompt-1-regexp "^In \\[[0-9]+\\]: " py-shell-input-prompt-2-regexp "^ [.][.][.]+: " ) ;; Set IPython to be the python command and give it arguments (setq py-python-command "ipython") (setq py-python-command-args (cond ((eq frame-background-mode 'dark) '("-colors" "Linux")) ((eq frame-background-mode 'light) '("-colors" "LightBG")) (t ; default (backg-mode isn't always set by XEmacs) '("-colors" "LightBG")) )) Let me know if this works ok for you. Cheers, f. From paul.moore at atosorigin.com Thu Oct 10 06:35:00 2002 From: paul.moore at atosorigin.com (Paul Moore) Date: 10 Oct 2002 03:35:00 -0700 Subject: Mixin class data References: Message-ID: <182bcf76.0210100235.5acbc105@posting.google.com> [Following up on my own post] > I have a suspicion that this needs the new-style class "cooperative > super call" machinery. But I'm not 100% certain, [...] OK, I've thought about this some more, and re-read the section of descrintro on super(). I am not sure this works, but let's try it. Assume that I have a base class B, and mixins M1, M2, ... The user is expected to derive a class from B, and from as many or few of the Ms as he likes. B must appear before the Ms in the base list. If the user class has an __init__, it must call B.__init__(self), but it does not need to know or care about whether the mixins have __init__ methods (that's an implementation detail, subject to change). I believe that these are reasonable restrictions, and I can live with them. Given that, I think I can define B and the Ms as follows - class B(object): def __init__(self): # do B's initialisation # Carry on down the chain of mixin initialisers super(B, self).__init__() class M1(object): # The derivation from object is irrelevant here, but # keep it for consistency # No __init__ needed for this class class M2(object): # This seems to need to derive from object, or B's super() # call doesn't find it... def __init__(self): # Do this class's initialisation # Is this super call needed? I think so... super(M2, self).__init__() I believe this will work. The user class becomes a new-style class, which may have some implications, but they shouldn't be a problem in practice. My questions are: 1. Why do the mixins need to derive from object? The ultimate user class will be new-style, via B, so I don't see that the Ms need to explicitly specify it. But the examples in descrintro don't use mixins (they form a diamond pattern), so it's not entirely clear. Testing indicates that mixins which use super() do need to derive from object. It's just not clear to me why... 2. Is it OK for the user class to use the conventional B.__init__(self) form? I'd prefer this to be true, as I don't want to require the user of my class to understand (or even be aware of) new-style classes and co-operative super calls to use it. I can't see why it wouldn't be (after all, B's constructor still gets the full object details via self), but again, descrintro isn't explicit on this. Testing seems to indicate that this is OK. As I mention, I've tested simple cases of this, but I'm concerned about "dark corners". This stuff is useful, and powerful, but I don't find it intuitive yet... Thanks for any help in understanding this better, Paul. From vze4rx4y at verizon.net Sun Oct 6 22:11:53 2002 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Mon, 07 Oct 2002 02:11:53 GMT Subject: XML Library from References: Message-ID: activepython at listserv.ActiveState.com; xml-sig-admin at python.org > Subject: Re: XML Library from > > > from what i remember it's a bit of an odd book: it should be titled "using > pyxie (I think that was the name)", which is the authors XML library that > converts XML to/from a simplified text format so you can leverage normal > text processing tools. There's a review on ibm.com/xml somewhere, which said > the library was buggy, I think too you will find some python/xml articles > there. > > Oreilly python/xml was more conventional: DOM/SAX etc. I highly recommend Python & XML by Chris Jones and Fred Drake. It's current, readable, highly informative, doesn't presume much, and quickly gets you up to speed. Though it's another one of the animal books, I confess that I can't name the animal on the cover. It appears to be some sort of rodent or other type of Python food. Raymond Hettinger From jubafre at brturbo.com Wed Oct 16 14:27:44 2002 From: jubafre at brturbo.com (jubafre at brturbo.com) Date: Wed, 16 Oct 2002 16:27:44 -0200 (GMT-02:00) Subject: string to float problem Message-ID: <2146681793.1034792864720.JavaMail.nobody@webmail2.brturbo.com> i have an aplication in tkinter, and i use the text componnent, i have a function to search in the componnet using 'search'. for example: start=self.text.search(string, 0.0, nocase=1, stopindex=END) return start='10.60' if i transform to float like this float(start) return 10.6 10.6!=10.60 and in my aplicattion make diference i, how can i transform this string in a float number, i want 10.60 in float? Juliano Freitas www.gebrasil.hpg.com.br From peter at engcorp.com Wed Oct 16 19:07:07 2002 From: peter at engcorp.com (Peter Hansen) Date: Wed, 16 Oct 2002 19:07:07 -0400 Subject: Paid programming and reversi propoganda >Re: Stallinman in CPU magazine References: <3D78EC92.AFBD973B@moorecad.com> <4623.54T2499T11045149threeseas@earthlink.net> Message-ID: <3dadf124@news.sentex.net> Ridiculous cross-posting to gnu.misc.discuss removed. Please reply to this thread via this message, or remember to remove the cross-posting in your own reply to avoid a slew of off-topic messages. Timothy Rue wrote: > PYTHON Programmers see below. > > On 06-Sep-02 12:57:38 Scott Moore wrote: > >>Another neat tirade by comrade Stallman, who states that the purpose of >>getting a Linux free GNU Unix is to elimnate free software "tainted" by >>paid software. Unbelievable the GNU organization still considers this >>warmed over communist to be their leader. He is never going to be satisfied >>until the programming profession is very dead. If he had everthing he >>wanted, programmers living off donations, he'd be wanting them all to live >>in communes and growing their own food. > > > > About ready to post some stuff to the public accessable archive of usenet > thru this rather slow newsgroup of gnu discuss... > > Look at the last message I dl from this group and what do I see? > > Freeloading communism promoters riding on the tail of something very > different. > > Ok, so slashdot is getting overun and bought out by the "self proclaimed > master race" but damn it all, this is not a microsoft newsgroup. > > Microsoft stuff is general controlled by them on their network. > > It is microsoft that continuely asks the consumers "where do you want to > go today" and in return for the answers that get for FREE, they then > charge the same people and everyone they can, to go there. > > It is MicroSoft that proceeds to continuely commit anti-trust violations > in what is supposed to be a free and fair market place and they do it > because they don't get punished for it. > > It is Microsoft heavyly involved in pushing their consumer fraud and > denial of consumer choice on everyone with effort to make it law. > > The DRM and Pallidumb stuff if a different product line, something less > than for use on what is versatility of computing. > > Who but Microsoft jackasses would call the GPL communism and RMS a > communist? Also claiming GPL means it must be done for free... > > What is the GPL, but just a license. It is not politically or economicly > indicating any damn thing. On the other had MS has used their license to > contridict constitutional rights, like freedom of speech. Dose the GPL do > that? No! > > What of these technologies that MS owns patents and other such controlling > rights to... DRM and Pallidumb..... that they want to use the legal system > to force everyone to pay them tax for using what is forced upon them? You > know like Saddam forcing everyone to vote for him....or Bush signing into > law the right for him to declair a war... Or tricking users into a new > EULA... Acts of self proclaimed Jackasses. Not the sort of simplicity > Stallman has, he has to constantly work at promoting his views as other > constantly play the bt flipping game against him. > > If there is anything the GPL and Richard Stallman are supporting it is the > commonwealth knowledge base of programming. Seeings how the whole human > race can and apparently is benefiting from it, it seems to me that such an > act just doesn't fit the "master race" profile. Rather it fits the > recognition of the value of the whole human race sharing values. > > > IT IS NOT UNCOMMON FOR THOSE SUPPRESSING FREEDOM TO PLAY THE BIT FLIPPING > GAME OF REVERSAL!!!! To make out something to be the opposite of what it > really is. > > So who the fuck do you think doesn't know that, that you have convinced > yourself there is someone who would believe you in your bit flipping game? > > And with this said, I shall be posting updated information regarding a > project targeted at being GPL, into the public accesible archives of > usenet, thru this group gnu discuss. Consider it an act of publishing and > copyright issues and prior art establishment. > > > *****PYTHON PROGRAMERS****** > > > I'm looking for a good python programmer who is willing to get paid for > coding the specified parts of this project as found at www.rentacoder.com > > Search on "3seas" and note that currently I have requested the oct 2nd bid > request to be cancelled as it was actually posted oct 15 ... and as such > it's exposure to potential programmers has greatly suffered. Upon > Cancellation I will be reposting the bid request, so to have the proper > exposure. If interested, go ahead and bid or comment as I will still get > and consider such, regardless. I like the idea of a middle person, for it > helps to assure fairness for both parties. I will not entertain bids > outside of such. > > > > --- > *3 S.E.A.S - Virtual Interaction Configuration (VIC) - VISION OF VISIONS!* > *~ ~ ~ Advancing How we Perceive and Use the Tool of Computers!* > Timothy Rue What's *DONE* in all we do? *AI PK OI IP OP SF IQ ID KE* > Email @ mailto:timrue at mindspring.com >INPUT->(Processing)->OUTPUT>v > Web @ http://www.mindspring.com/~timrue/ ^<--------<----9----<--------< > From cnetzer at mail.arc.nasa.gov Fri Oct 4 06:31:11 2002 From: cnetzer at mail.arc.nasa.gov (Chad Netzer) Date: Fri, 4 Oct 2002 03:31:11 -0700 Subject: [Python-Dev] PEP239 (Rational Numbers) Reference Implementation and new issues In-Reply-To: References: Message-ID: <200210041031.DAA25884@mail.arc.nasa.gov> On Friday 04 October 2002 02:16, Michael Hudson wrote: > Chad Netzer writes: > > BTW. The expression/definition that always makes me shake MY head > > is (0**0 == 1). Limits are amazing things... > > Even here you have to be careful! I presume you meant > > x > lim x = 1 > x -> 0 Well, I meant that despite the discontinuity of the limits, there is an informal (perhaps even a formal) definition for 0**0 (ie. 0 to the zeroth power) to equal the limit above (ie. 1). Python 2.2.1 (#2, Sep 13 2002, 23:25:07) >>> 0**0 1 The same in Octave or Matlab. Mathematica flags it as indeterminate, however. However, for some kinds of mathematics, 0**0 needs to equal 1, for consistency: http://db.uwaterloo.ca/~alopez-o/math-faq/node40.html Knuth, et al. even go so far as to say (in _Concrete Mathematics_): """ Some textbooks leave the quantity 0**0 undefined, because the functions x**0 and 0**x have different limiting values when x decreases to 0. But this is a mistake. We must define (x**0 == 1) for all x, if the binomial theorem is to be valid when x=0, y=0, and/or x=-y. The theorem is too important to be arbitrarily restricted! By contrast, the function 0**x is quite unimportant. """ There is a bit of levity in that passage, but nontheless, I do find the argument compelling (even though (0**0 == 1) just *looks* wrong :) ) -- Chad Netzer cnetzer at mail.arc.nasa.gov From skip at pobox.com Fri Oct 25 21:43:08 2002 From: skip at pobox.com (Skip Montanaro) Date: Fri, 25 Oct 2002 20:43:08 -0500 Subject: up arrow with raw_input In-Reply-To: <200210260057.g9Q0vYW68890@cynaptic.com> References: <200210260057.g9Q0vYW68890@cynaptic.com> Message-ID: <15801.62252.919642.249024@montanaro.dyndns.org> kevin> I've been trying to trap an up-arrow response when using kevin> raw_input() and its not going well.... I've also tried using GNU kevin> readline. This only works from the python prompt (>>>) and not kevin> while waiting for input using raw_input(). kevin> Does anyone have any ideas? You might check out ipython. It looks like it does the right thing. Google for "ipython" and hit the "feeling lucky" button. -- Skip Montanaro - skip at pobox.com http://www.mojam.com/ http://www.musi-cal.com/ From Henk Mon Oct 21 08:08:48 2002 From: Henk (Henk) Date: Mon, 21 Oct 2002 12:08:48 GMT Subject: out parameters in Python and COM References: Message-ID: <3db3ee35.1058713890@news.skynet.be> It works, thanks Stefan!!! On Mon, 21 Oct 2002 13:18:12 +0100, Stefan Schukat wrote: >You should use the makepy generated wrapper. The dynamic dispatch >does not support out parameters. > >So following should work: > >from win32com.client.gencache import EnsureDispatch > >atm = EnsureDispatch("ATM.Shell") >b4 = atm.LogOn("Administrator", "EHSW", "Python") > > >HEMgr = atm.ATMHeadEndManager >HEMgr.SetCodeTable("BS","ES","EE") >Ret, a, b, c = HEMgr.GetCodeTable("","","") > > > Stefan > >> -----Original Message----- >> From: Henk at relay.trans-it.de [mailto:Henk at relay.trans-it.de] >> Sent: Monday, October 21, 2002 10:36 AM >> To: python-list at python.org >> Subject: out parameters in Python and COM >> >> >> Hi, >> >> Code snippet at the end of the post. >> >> I have an exe which exposes some functionality through an IDispatch >> interface. The GetCodeTable-method has 4 parameters: >> first 3 are [out] BSTR* >> last one [out,retval] long * >> >> When debugging my exe using Python I always get empty values for a,b >> and c (see below) allthough they are filled in correctly inside the >> exe (checked with a debugger). >> >> Any idea what could be wrong? >> >> Thanks, >> >> Henk >> >> import win32com.client >> >> atm = win32com.client.Dispatch("ATM.Shell") >> b4 = atm.LogOn("Administrator", "EHSW", "Python") >> >> >> a="" >> b="" >> c="" >> HEMgr = atm.ATMHeadEndManager >> HEMgr.SetCodeTable("BS","ES","EE") >> HEMgr.GetCodeTable(a,b,c) >> print a >> print b >> print c >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > From cliechti at gmx.net Tue Oct 15 21:19:26 2002 From: cliechti at gmx.net (Chris Liechti) Date: 16 Oct 2002 03:19:26 +0200 Subject: Python pattern repository References: Message-ID: [posted and mailed] bokr at oz.net (Bengt Richter) wrote in news:aoi76i$b1m$0 at 216.39.172.122: > On Tue, 15 Oct 2002 18:33:13 GMT, Robin Munn wrote: > The fact that there is so much that can be found via Google ... > Introducing PyPAN: Python Pervasive Archive Network ;-) > > Here's the concept: If you want to include your code snippet > in the PyPAN, post it embedded in a document that Google will see. while i think your idea is nice, this can be the first problem... google is only includeing pages that are linked somewhere. it took many months until it indexed my page with a gcc port... > You embed it for easy extraction by putting a PyPAN expression > in the first and last (+/- 1, discussed later[1]) lines of your > snippet, e.g., > > # ++PyPAN++ mySnippet.py /clp/forcomment/ -- minimal PyPan snippet > def mySnippet(): > print 'Hello PyPAN!' > # --PyPAN-- > > I think Google would find '++PyPan++' and show an interesting list. why do you use "+-" etc in the marker? those are special characters to google and it ignores punctuation/special chars in other cases. i'd stay with letters only. > The "/clp/forcomment/" part of the expression is optional, but the > intent is to express the location of mySnippet.py in a classification > hierarchy, to aid in searching, to limit hits to particular topics > etc. mySnippet.py is a recommended file name, and comes first after > the '++PyPAN++' tag. > > The classification path is also for optional use as an actual > directory path which can be rooted anywhere convenient for the user > (e.g., ~/PyPAN or C:\pywk\PyPan etc.) and thereby support automatic > extraction/downloading/placement from e.g., newsgroup archives, disk > files, etc. > > One common usage would be to see a PyPAN snippet in a post -- like the > above in this post. To make it available to the extraction tool as a > file, I wrote a little program [2] called getclip.exe which simply > gets the text from the windows clipboard and writes it to stdout. This > makes the clipboard visible as a file object using os.popen('getclip') > -- which you can pass to anything that wants to read a file. (getclip > is also handy outside of Python, since you can easily pipe the output > or redirect it to a file, without having to go to an editor an pasting > and saving-as. Instead you just type getclip>theFile.txt). > > The intent is not to require you to select the exact lines, but just > do a select-all, copy or whatever is easy. Then getclip will make all > that available to the actual snippet extractor, which can put it in > particular directories, etc. > > I am putting together a PyPAN.py module to provide convenient methods > for retrieving PyPAN snippets from clipboard, files, or urls, etc. by > regex pattern matches, but it's not finished. It will be runnable from > the command line or importable for programmatic use. There will be > options for file placement similar to winzip extraction. I.e., you can > ignore paths and put everything in a specified directory, or you can > root the paths where you like etc. I guess if there is no interest in > PyPAN, I may only be able to retrieve my own snippets ;-) oh, i think if it's that simple to use that many people will use the marker in their news posts. > In any case, I would be interested in hearing of any standard > hierarchy for classifying software. Is there real librarian in the > house? well i'm no expert in that area... but i found the reverse URL type of hierarchy of Java a good idea. that way you avoid name conflicts. on the other hand many people will prefer an order by topic rather than organization/author. > --------------- > [1] Variations on the PyPAN tags: > (Note that PyPAN will search based on space-delimited tags, therefore > quoting them as in the following makes them safe against inadvertently > interfering with searching for an actual snippet like the (not quite) > minimal one above). > > '++PyPAN++' => start with current line > '++PyPAN++-' => start with previous line > '++PyPAN+++' => start with next line > '++PyPAN--' => reserved for future expressions within a snippet > '--PyPAN--' => end with current line > '--PyPAN---' => end with previous line > '--PyPAN--+' => end with next line as mentioned above, i'm not sure how well the special characters will work. e.g. google searches for entire words and ignores special chars, but i think it understands "+" and "-" as include/exclude word so that --PyPAN-- would possibly mean no results containing that string... why do you want to complicate thigs with that many magic tags anyway? why not '# PyPANsnippet filename.py /hier/archy version' > --------------- > > [2] > /* ++PyPAN++ getclip.c -- get and write win32 clipboard text to stdout > */ /* > ** To compile with msvc++60 at command line use > ** cl getclip.c /link /defaultlib:user32 > */ > > #include > #include > #include > > int main (){ > HANDLE hClipData; /* handle to clip data */ > LPSTR lpClipData; /* pointer to clip data */ > if (!OpenClipboard(NULL)) return 0; /* NULL <=> current task */ > /* get text from the clipboard */ > if( (hClipData = GetClipboardData(CF_TEXT)) && > (lpClipData = GlobalLock(hClipData)) > ){ > write(1, lpClipData, strlen(lpClipData)); /*text string to > stdout */ GlobalUnlock(hClipData); > CloseClipboard(); return 0; > } else { > CloseClipboard(); return 1; > } > } > /* --PyPAN-- */ > > > Note: The cl command assumes environment settings, which > you can set by invoking D:\VC98\Bin\VCVARS32.BAT (or > whatever your path to it is). > > BTW, getclip.exe is not big (freshly recompiled): > > 02-10-15 15:58 24,576 getclip.exe hehe. 3'584 Bytes GCC/stripped. --makefile-- CFLAGS = -mno-cygwin getclip.exe: getclip.o $(CC) -mno-cygwin -o $@ $^ strip $@ ------------ > Further ideas? as mentioned above, google is a bit picky if a site is not referenced anywhere. so it would mabe make sense if there were a page (where many links point to) where anyone could enter his URL, so that the chances are increased that it is found by google and other search engines. a simple wikki page would do, or a mailinglist with HTML accessible archive. a bunch of people should place a link to that site on their pages to increase the google pagerank and to increase the probability that the linked pages are found. i think this is a nice idea. with your PyPAN module there could be an easy access to the information and we get a lot of infrastructure "sponsored" (storage space for the snippets (with redundancy :-) search engines, ...) it may be a bit slow 'cause most pages are not refreshed that often. so it may take a week or two until a snipped is indexed. and an other problem might come up. i'll just mention "versions"... it will become difficult to find the best snipped if there are so many similar entries etc. oh, and maybe there should be some convention for keywords, like that they should follow right after the tagline as python comment or so. or do you think that the source code + message around it is enough to find it? there will be ground for many tools, like pygoogle combined with xx etc, indexing bots, that collect all snippets and place them on their own page, spcialized search engines, ... chris -- Chris From wholovesomar at ido.com Mon Oct 21 04:35:36 2002 From: wholovesomar at ido.com (Roma) Date: Mon, 21 Oct 2002 08:35:36 GMT Subject: Tkinter, problem when using 2 scrollbars References: Message-ID: > I'd whip something up real quick, but I don't have Tk on this machine. > > Jeff > > How's this: class ScrolledListbox(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.rowconfigure(0, weight=1) self.columnconfigure(0, weight=1) self.listbox = Listbox(self) self.listbox.grid(row=0, column=0, sticky=N+E+S+W) self.vscroll = Scrollbar(self, orient=VERTICAL) self.vscroll.grid(row=0, column=1, sticky=N+S) self.hscroll = Scrollbar(self, orient=HORIZONTAL) self.hscroll.grid(row=1, column=0, sticky=E+W) self.listbox.config(yscrollcommand=self.vscroll.set) self.listbox.config(xscrollcommand=self.hscroll.set) self.vscroll.config(command=self.listbox.yview) self.hscroll.config(command=self.listbox.xview) greg From thorsten at thorstenkampe.de Tue Oct 8 05:52:01 2002 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Tue, 8 Oct 2002 11:52:01 +0200 Subject: Merging lists has made my brain hurt. References: <3D9B1953.3030109@moving-picture.com> Message-ID: * Thorsten Kampe > * Alex Martelli >> Thorsten Kampe wrote: [massive snip] >> have another auxiliary function: >> def binop(seq0, seq1, op): >> count0 = tocount(seq0) >> count1 = tocount(seq1) >> if len(count0) > len(count1): >> count1, count0 = count0, count1 >> for item in count0: >> count0[item] = op(count0[item], count1.get(item, 0)) >> >> and implement your 'and' by returning binop(seq0, seq1, min) and >> your 'or' by returning binop(seq0, seq1, max) -- I think this also >> clarifies the parallelism between the two cases. > > It's not that easy. Union and symmetric difference take elements of > both sequences (e. g. union([11, 22], [22, 33])) so you have to loop > through both sequences! > > So for the union, I think my "seq0 + (seq1 - seq0)" is shorter (and > probably faster). Okay, I rewrote the "seq0 + (seq1 - seq0)" part: #v+ elif boolean_modus == 'or': # union union = {} for item in count0: union[item] = max(count0[item], count1.get(item, 0)) for item in count1: union[item] = max(count0.get(item, 0), count1[item]) return toseq(union) #v- Like I predicted, with "seq0 = seq1 = [1] * 1000000" it's about a 0.8 sec slower and with "seq0 = [1] * 1000000, seq1 = range(1000000)" it's about 3.7 sec slower. >>> elif boolean_modus == 'xor': # symmetric difference >>> return boolean(boolean(seq0, seq1, 'or'), boolean(seq0, seq1, >>> 'and'), 'not') >> >> This one could also be more speedily implemented with the already >> presented binop and another little auxiliary function: >> >> def maxminusmin(onecount, anothercount): >> return max(onecount, anothercount) - min(onecount, anothercount) > > That's abs(onecount - anothercount), isn't it? > >> and your 'xor' is implementable as >> return binop(seq0, seq1, maxminusmin) > > Same as for union: I'd have to loop through both lists, but that's > cheap compared to the triple todict -> to seq conversion I do at the > moment. I rewrote this, too: #v+ elif boolean_modus == 'xor': # symmetric difference symdiff = {} for item in count0: symdiff[item] = abs(count0[item] - count1.get(item, 0)) for item in count1: symdiff[item] = abs(count0.get(item, 0) - count1[item]) return toseq(symdiff) #v- With the same test as with union, it's three and two times as fast. Thanks! Thorsten From grante at visi.com Sat Oct 19 15:46:28 2002 From: grante at visi.com (Grant Edwards) Date: Sat, 19 Oct 2002 19:46:28 GMT Subject: RedHat 7.3 References: <283adf56.0210161600.48b9824b@posting.google.com> <283adf56.0210190750.5f35a1b8@posting.google.com> Message-ID: In article <283adf56.0210190750.5f35a1b8 at posting.google.com>, Kevin Dahlhausen wrote: >> There are python2 packages that RH distributes... If those don't fit your >> needs, grab the SRPM and modify it to suit. > > I'll track these down. The problem is of course the redhat > configuration utilites. Do you know offhand if these RPM's contained > updated Redhat utilities as well - such as printconf-gui etc? No. The Python2 RPMs leave Python 1.5.2 installed as "python" and that's what is used by the system utilities. The Python2 RPMS install a second python version and you can invoke that interpreter as python2. $ which python /usr/bin/python $ python Python 1.5.2 (#1, Apr 3 2002, 18:16:26) [GCC 2.96 20000731 (Red Hat Linux 7.2 2 on linux-i386 Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam >>> $ which python2 /usr/bin/python2 $ python2 Python 2.2 (#1, Apr 12 2002, 15:29:57) [GCC 2.96 20000731 (Red Hat Linux 7.2 2.96-109)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> -- Grant Edwards grante at visi.com From DavidA at ActiveState.com Wed Oct 30 15:26:39 2002 From: DavidA at ActiveState.com (David Ascher) Date: Wed, 30 Oct 2002 12:26:39 -0800 Subject: Rackspace and Python @ PHPCon Message-ID: <3DC0407F.8080602@ActiveState.com> From Jeremy Zawodny's blog, on PHPCon (where Yahoo announced their 100% PHP move): http://jeremy.zawodny.com/blog/archives/000282.html#000282 "The conference was closed by Dirk, one of the founders of Rackspace discussing the critical role that PHP played in getting Rackspace off the ground. He focused on PHP's integration, quick development times, and flexibility. He then threw us a bit of a curve ball by revealing that a sizable chunk of their PHP code is being replaced by Python. The silver lining in the story is that SOAP is allowing them to keep much of the customer-facing stuff in PHP and the back-end code in Python." From mcfletch at rogers.com Mon Oct 7 11:23:38 2002 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Mon, 07 Oct 2002 11:23:38 -0400 Subject: Function GetData() in wxImage References: <41c203e.0210070707.15595d94@posting.google.com> Message-ID: <3DA1A6FA.1020600@rogers.com> http://wiki.wxpython.org/index.cgi/WorkingWithImages BTW: It's generally more efficient to use the wxPython users mailing list for these kinds of questions. Enjoy, Mike Anand wrote: >Hi > > I am writing an image viewer in wxPython using the wxImage class. >I want to manipulate the image data for effects. I tried to use the >GetData() method of the wxImage class which returns a const char *(wxWindows >documentation). > > How do I manipulate this object. Is it a python object or a C unsigned char * >stream ? Can i apply std 'C' calls on it or do I need to use methods of >python ? > >Concerned code... > > def myfunc: > > ... > self.img = wxImage(fileName) > chunk = self.img.GetData() # What is this chunk ? > pass > > >Thanks > >Anand > > -- _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From mchermside at ingdirect.com Wed Oct 23 08:59:10 2002 From: mchermside at ingdirect.com (Chermside, Michael) Date: Wed, 23 Oct 2002 08:59:10 -0400 Subject: What happens after return statement? Message-ID: <902A1E710FEAB740966EC991C3A38A8903C35AF6@INGDEXCHANGEC1.ingdirect.com> > I really ought to know better after 2 years with Python, but I became > uncertain. Have a look, please: [... code ...] > Is the file closed, or is it not? That is, what happens after each return > statement? > > # Gustaf Three points. (1) Any time that a file gets garbage collected (and this happens as soon as it goes out of scope unless you have a reference loop) it will automatically be closed for you. So yes, the file is closed. (2) Perhaps your question was really whether "return" causes the function/method to IMMEDIATELY exit, or whether it perhaps executes some additional code (outside of an if statement it might be in when you used "return"). The answer is that it IMMEDIATELY exits the function/method. No additional clean-up code is called. (3) Perhaps your REAL question is HOW do I call some clean-up code. For example, some consider it poor form to allow a file to close itself instead of calling close() on it. Or you might have some other form of cleanup needed. The answer to THIS question is "try-finally", which works like this: >>> def f(): ... try: ... print 'doing work' ... return 'some value' ... finally: ... print 'doing cleanup' ... >>> print f() doing work doing cleanup some value -- Michael Chermside From johnroth at ameritech.net Thu Oct 3 08:13:43 2002 From: johnroth at ameritech.net (John Roth) Date: Thu, 3 Oct 2002 08:13:43 -0400 Subject: Decimal arithmetic, with example code References: Message-ID: "James J. Besemer" wrote in message news:mailman.1033512243.4377.python-list at python.org... > > Tim Peters wrote: > > >No single rounding discipline is > >suitable for all commercial applications, > > > Ain't it the Truth!! > > Businesses in the US are required to file quarterly reports about periodic tax payments made during the quarter. Taxes, e.g. on FICA and Medicare, are computed as a percentage of each employee's wages and deducted from the employee's paycheck each pay period. On the quarterly report, the actual liability is computed, based as a percentage of total payroll for the period. > > These two computations (sum of percentages and percentage of sums) do not always produce the same amount. And yet the amounts on the return have to match to the exact penny -- no rounding off to the nearest dollar (like on personal returns). Consequently, the form includes an explicit entry for "round off error," to correct for minor differences in computed liability vs. actual payments. It gets even worse. Sometimes you've got to stagger which employees get their pay, deductions and so forth rounded which way so that the total payroll comes out close to the overall computation. And there's simply no way to put that kind of logic into a basic arithmetic computation. John Roth > > --jb > > -- > James J. Besemer 503-280-0838 voice > 2727 NE Skidmore St. 503-280-0375 fax > Portland, Oregon 97211-6557 mailto:jb at cascade-sys.com > http://cascade-sys.com > > > > > From tdelaney at avaya.com Mon Oct 21 23:12:07 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Tue, 22 Oct 2002 13:12:07 +1000 Subject: New to python Message-ID: > From: Peter Hansen [mailto:peter at engcorp.com] > > Oh come, let's not exaggerate! While there have been the odd > times when a contributor has suddenly and without apparent > explanation gone offline for extended periods - even permanently - > and some have been replaced by new and advanced bots without > notice or fanfare, I can assure you that the PSU kills outspoken > contributors rather less frequently than it used to. These > days it is much more common simply to receive an unexpected Furthermore, there is *no* cannibalism in c.l.py, and when I say none I mean there is a certain amount. Jenkins! Tim Delaney From hwlgw at hotmail.com Mon Oct 14 10:29:20 2002 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 14 Oct 2002 07:29:20 -0700 Subject: realtime design References: Message-ID: After spending a day on trying to find a solution using threads, I found out there is probably none. Argh! The problem: I am trying to come up with a method to run a function in such a way that the whole thing will take at most x milliseconds, with x a reasonable value like 200. If the function is not finished by that time, a default value should be used. If the function *does* finish in time, the return value of the function should be used. The main point is that the calling program should be able to continue with the next statement after x milliseconds. And it would be nice if the called function is interrupted or something if it has not finished, so it will not eat CPU resources. But I found this: From: Tim Peters (tim.one at home.com) Subject: RE: embedded python - cancel "while 1: pass" Newsgroups: comp.lang.python Date: 2001-01-08 00:07:17 PST Java's thread .stop(), .resume(), and .suspend() methods were all deprecated, because they proved to be "inherently unsafe" in practice. This isn't real surprising: a thread is cheaper than an OS process largely because the runtime *doesn't* save enough info to clean up a thread safely, short of the death of the process it's running in. Aha! So what I am trying to do is basically impossible with threads! I guess some people have been here before. Anyway, thank you Tim Peters. There should be a collection with Tim Peters' c.l.p. postings you can search on subject. His postings have been useful for me before! I found this one using google groups search. What I am going to look into is how to write a function that will start the target function in another *process* in Windows, and use a default value if the process does not finish in time. Any ideas? and-now-I-am-thinking-about-how-to-kill-a-Windows-process-ly y'rs ''' Multithreading will rot your teeth. -- Michael Swaine ''' From jdhunter at nitace.bsd.uchicago.edu Tue Oct 22 12:48:27 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Tue, 22 Oct 2002 11:48:27 -0500 Subject: ipython keybinding Message-ID: I just installed ipython http://www-hep.colorado.edu/~fperez/ipython/. Wow, what a fantastic python shell. So far I have just two items on my wishlist: 1) Is it possible to bind the 'up/down' arrow keys to the same function that C-n/C-p are. The latter only bring up previous commands that match what has been typed before, while the former bring up the previous/next command regardless of the text entered so far on the prompt. 2) Is it possible to run ipython in an emacs shell, or is this in the works (ala matlab-shell)? I fear the answer is no, since the default editor for the @edit command is vi, which leads me to guess that Fernando is a vi user. This is not a big requirement, since I can just pop open a quick emacs session from within ipython with @edit, but we emacs junkies like to do everything within one emacs session, for cutting and pasting text across buffers that are already open, etc... Thanks for any suggestions! John Hunter From hst at empolis.co.uk Thu Oct 31 05:58:08 2002 From: hst at empolis.co.uk (Harvey Thomas) Date: Thu, 31 Oct 2002 10:58:08 -0000 Subject: Iterating through multiple sequences Message-ID: <8FC4E7C302A6A64AAD5DB1FA0E825DEB220D98@hendrix.empolisuk.com> Mark Charsley wrote: > > In several cases recently I've wanted to iterate through two > sequences at > the same time. The way I've been doing it so far is > > assert(len(myList1) == len(myList2)) > for i in range(len(myList1)): > doSomethingWith(myList1[i],myList2[i]) > > which is a little ugly. Is there some clever idiom I'm > missing that would > simplify things? Something like > > for elem1,elem2 in myList1,myList2: > doSomethingWith(elem1,elem2) > > which, while valid python, doesn't do what I hoped for > > TIA > > Mark > assert(len(myList1) == len(myList2)) map(doSomethingWith, myList1, myList2) Harvey _____________________________________________________________________ This message has been checked for all known viruses by the MessageLabs Virus Scanning Service. From eppstein at ics.uci.edu Mon Oct 21 14:17:02 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Mon, 21 Oct 2002 11:17:02 -0700 Subject: int() should be extended? References: Message-ID: In article , sismex01 at hebmex.com wrote: > >>> s = "0x41" > >>> int(s[2:]) > 65 > > Good luck! You have a strange Python processor. When I run this, I get 41. You did run it, right? -- David Eppstein UC Irvine Dept. of Information & Computer Science eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/ From alain at onesite.org Sun Oct 20 22:18:18 2002 From: alain at onesite.org (Alain Tesio) Date: Mon, 21 Oct 2002 04:18:18 +0200 Subject: How to get the minor and major device numbers with os.stat ? Message-ID: Hi, I can't manage to get the major or minor device numbers with os.stat : ~ $ll /dev/xda7 /dev/xda8 brw-rw---- 1 root disk 13, 7 Nov 30 2000 /dev/xda7 brw-rw---- 1 root disk 13, 8 Nov 30 2000 /dev/xda8 ~ $python Python 2.2.2 (#4, Oct 15 2002, 04:21:28) [GCC 2.95.4 20011002 (Debian prerelease)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> os.stat("/dev/xda7") (25008, 17383L, 5643L, 1, 0, 6, 0L, 1007270448, 975597764, 1007270448) >>> os.stat("/dev/xda8") (25008, 17384L, 5643L, 1, 0, 6, 0L, 1007270448, 975597764, 1007270448) >>> 17384 / 256 , 17384 % 256 (67, 232) I expected major*256+minor, I've tried a lot of combinations at random and couldn't manage to get 17383 from (13,7) Any idea ? Thanks Alain From gerhard.haering at opus-gmbh.net Tue Oct 8 11:25:56 2002 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 8 Oct 2002 15:25:56 GMT Subject: SimpleXMLRPCServer Releasing Ports References: Message-ID: Ulli Stein [2002-10-08 13:32 GMT]: > John Abel wrote: > >> Hi, >> >> I have a script running, using SimpleXMLRPCServer, which works OK. >> Except, when I stop, and restart the script, I receive the error, >> "Address already in use". Is there something I can do, like a >> destructor, to tidy up, so that the script can be restarted? >> >> Thanks >> >> John > > It is probably an os issue. Maybe you can tweak it using low level socket > operations which state how long your IP/Port will be blocked. Yep. The SO_REUSE flag should do the trick. But that probably means changing the xmlrpclib module in some way. -- Gerhard From diltonm at pacbell.net Mon Oct 14 00:41:31 2002 From: diltonm at pacbell.net (Dilton McGowan II) Date: Mon, 14 Oct 2002 04:41:31 GMT Subject: A simple generator application References: Message-ID: <%Vrq9.3400$tN4.243209515@newssvr21.news.prodigy.com> Guess I missed your point Avery, maybe it's overly intellectually stimulating. Doug wrote a piece of code that does something programmers need to do every day, iterate directory trees and work with files. (Though I agree with Oren about recursion, also Erik made a good point about the copyright.) I'm addressing your comment that your code *does* something. I grant that it *may* do something. Instead of taking aim, try helping load the ammo. "Avery Andrews" wrote in message news:Pine.GSO.4.21.0210130849040.122-100000 at supreme.pcug.org.au... > > > On Sat, 12 Oct 2002, Doug Fort wrote: > > > I'm interested in generators. I've read Dr. David Mertz's 'Charming > > Python' articles (http://gnosis.cx/publish/tech_index_cp.html), and > > the discussion here on c.l.p. > > > > I've been looking for an excuse to actually use a generator. I need to put > > include guards on a bunch of C++ header files. So I started out to create > > a generator that does what os.path.walk does, with yield in place of the > > callback 'visitor' function. > > > > Here's one that I just wrote that actually does something, basically > combining two calls to an interface to AmziProlog into one convenient > package, the context is looking at sequentially numbered lines of text > where some line numbers appear twice (variants, errors, etc), > 'next_line_num' is a 'deterministic' Prolog call that produces one answer, > 'retrive_num_line' is a 'nondeterminstic one that produces multiple > answers. the results of the .run and .calls methods are basically > copies of the argument with the capital letters filled out by whatever > the Prolog engine can come up with, if anything, that makes the statements > true; the argument-positions are then accessible by indexing: > > # > # generator to smooth out call-redo cycle. Might be better > # if the Prolog were also rethought. > # > def LineGetter(engine, linenum=0): > # > # Loops indefinitely until it kills itself > # > engine.clearCall() > while (1): > lino=engine.run("next_line_num(%d,X)"%linenum) > if lino == None: > return > linenum = int(lino[2]) > for result in engine.calls("retrieve_num_line(%d,T,I,N,L)"%linenum): > yield result[1:6] > > > From jgresula at seznam.cz Sat Oct 5 07:48:15 2002 From: jgresula at seznam.cz (Jaroslav Gresula) Date: 5 Oct 2002 04:48:15 -0700 Subject: Which Linux distribution Message-ID: <814a0eba.0210050348.452ed9ab@posting.google.com> I've installed RH 7.3 recently and I'm pretty frustrated from their approach to Python packages. It is almost impossible to switch to Python 2.x version since majority of their scripts is based on 1.5.x. I've already read some guides how to accomplish that but it is PITN. I'm about to switch to different distribution and that's my question. What is your experience? What distribution would you recommend to me? My primary requirement on the distrubution is to have a nice Pyton environment with easy maintenance of multiple python versions. From mis6 at pitt.edu Fri Oct 11 15:29:46 2002 From: mis6 at pitt.edu (Michele Simionato) Date: 11 Oct 2002 12:29:46 -0700 Subject: raw strings References: <2259b0e2.0210081328.2c749ab7@posting.google.com> <2259b0e2.0210100939.6fb23d46@posting.google.com> <2259b0e2.0210110528.449ce434@posting.google.com> Message-ID: <2259b0e2.0210111129.1dc80074@posting.google.com> Duncan Booth wrote in message >> s/regexp1/regexp2/ >... where regexp1 is a regular expression and regexp2 is a string. Maybe regexp2 is not a regular expression, but certainly is not a standard string, since can contain grouping characters. For instance in a text I needed to change expressions of kind [decimal number] --> (decimal number) and I used sub(r'\[(\d+)\]', r'(\1)') If the second expression was a real string, '(\1)' would be replaced instead of the correct decimal number ! With this in mind I used the term regular expression for regexp2, even if I agree which is not a regular expression in the same sense of regexp1. But it is not a standard string. In lack of a good term I used the notation regexp2. > You could try writing re.sub(regexp1, replacement, string), or using > your terminology: > re.sub(r'regexp1', r'regexp2', text) > where regexp2 is not a regular expression. I had the impression that the use of re.sub(), without compiling first the regular expression, was quite inefficient. Now I did some profiling and discovered that it is worse, but only by 10%, practically nothing. Therefore I will use the non-compiled form in the future. > I think you have a fundamental misunderstanding of what a 'raw > string' actually is. Even if at the time of my first posting I was unsure about the exact meaning of a raw string, after the reply by Bengt Richter I quickly realized how things work, this is the reason why I wrote > The problem seems much more complicated than I expected. Now I understand well the way Python interprets strings and the reason why it is not obvious at all to define a raw_string function. I had already thought to the preprocessor idea suggested by Gerhard H?ring but I discarded it since I wanted raw_string() working on variables, not only on string constants which would be the case for a preprocessor. In this way I would simply give a longer name to the r operation ! Therefore for the moment I will stay with the ugly r notation. Still, I don't believe I am the only one who thinks the "r" is ugly! It seems to me a last minute hack more than a pythonic construct. At least, IMHO. Thanks to all people who answered and helped me to understand, Michele From carlca at dircon.co.uk Sun Oct 20 18:49:23 2002 From: carlca at dircon.co.uk (Carl Caulkett) Date: Sun, 20 Oct 2002 23:49:23 +0100 Subject: New to python References: <3db2fcc9$0$5803$fa0fcedb@lovejoy.zen.co.uk> Message-ID: <5ic6rusts9cruhoasccnsgrpar4ghihak3@4ax.com> On Sun, 20 Oct 2002 19:56:56 +0100, "e-tones.co.uk" wrote: >Cheers, >Taz Is that Taz Higgins aka "The Taz" ? If so, are you still doing Delphi stuff? I haven't seen you on the Borland newsgroups for many a long month. -- Carl From jeffrey.b.layton at lmco.com Fri Oct 18 06:41:16 2002 From: jeffrey.b.layton at lmco.com (Jeff Layton) Date: Fri, 18 Oct 2002 06:41:16 -0400 Subject: Globals References: Message-ID: <3DAFE54B.90E6F27D@lmco.com> Newt wrote: > Hi, > > What's the best 'way' of defining globals? How about a newbie answer? I've been using a 'Borg' to do something like what you mentioned: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66531 I created a 'Borg' class then in each module where I need it, I can create an instance of the class there and access the data and methods in the class. Very cool for my application (thank you Alex!). Good Luck! Jeff > > > To better express my self, if I wanted to have strVar (a string), iVar (an > integer) (for example) as globals, I assume I'd have to declare them in my > main program: > > strVar = "" > iVar = 0 > > and use the global command when ever I wanted to reference them: > > global strVar > global iVar > > Questions: > > 1. Is this the correct/best way? > 2. To save typing in all the global statements, can I put them in to an > include file or a source file? > 3. If I declare them in a .py file, do I still need the global commands to > use them within Classes and Functions etc defined within that same module? > > Thanks > > Newt -- Jeff Layton "Is it possible to overclock a cattle prod?" - Irv Mullins This email may contain confidential information. If you have received this email in error, please delete it immediately, and inform me of the mistake by return email. Any form of reproduction, or further dissemination of this email is strictly prohibited. Also, please note that opinions expressed in this email are those of the author, and are not necessarily those of the Lockheed-Martin Corporation. From tim.one at comcast.net Thu Oct 17 00:28:45 2002 From: tim.one at comcast.net (Tim Peters) Date: Thu, 17 Oct 2002 00:28:45 -0400 Subject: Most efficient method to search text? In-Reply-To: <20021016183924.A469@unpythonic.net> Message-ID: [Tim] > re doesn't build a DFA. Alternatives are searched for one at a > time, left to right. See Friedl's "Mastering Regular Expression" book > for long discussions of the tradeoffs. [Jeff Epler] > I repent of the sin of suggesting this approach. Oh well. It's not a sin, but it's not nearly as straightforward as what you're imagining. Read the book -- Python/Perl regular expressions are irregular in ways that go beyond the capabilities of DFAs. Especially for purposes of building lexers, it might be useful if the re package could recognize when a DFA approach was sufficient and practical, and switch to a different scheme entirely then. Or it might not. Build code to try it both ways, and let us know how it turns out ... From aleax at aleax.it Thu Oct 3 02:34:27 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 03 Oct 2002 06:34:27 GMT Subject: PEP239 (Rational Numbers) Reference Implementation and new issues References: <20021002221421.GA29958@thyrsus.com> <3D9B7DB5.4000702@tismer.com> Message-ID: Chris Gonnerman wrote: ... > I agree, > > 1/3 > > is pretty nice as a rational literal; but would it hurt > so much to say > > 1/3R > > instead? No, it wouldn't hurt much (though I'd spell it with a lowercase r -- I think that would make it more readable). A trailing d could specify decimal, a trailing L (normally uppercase for legibility) long -- the latter should be extended to literals such as: 1e7L meaning the same as 10000000L -- it's silly to force the author AND every reader of the source to count out zeroes carefully whenever such integral literal amounts must be expressed. That's not so crucial anymore for Italians, now that we've switched from liras to euros, but, for example, Turkey still uses their own liras, and they're inflated enough that 1e7L Turkish liras is a few US $... Alex From strombrg at nis.acs.uci.edu Fri Oct 11 21:12:40 2002 From: strombrg at nis.acs.uci.edu (Dan Stromberg) Date: Sat, 12 Oct 2002 01:12:40 GMT Subject: jython example program Message-ID: I had a hard time finding a contemporary, working jython applet example program with source code, so after getting one working, I've put it at http://nis.acs.uci.edu/~strombrg/jython/ . The experts will of course know this is a nothing-achievement, but maybe it'll make another newbie's quest easier someday. From martin at v.loewis.de Sat Oct 12 18:41:47 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 13 Oct 2002 00:41:47 +0200 Subject: how to use smtp starttls() encryption? References: <8f41cfd.0210101719.ad47c7@posting.google.com> <8f41cfd.0210120805.6ced204a@posting.google.com> Message-ID: xucs007 at yahoo.com (Xu, C.S.) writes: > > AttributeError: SSLFakeSocket instance has no attribute 'sendall' > > Any suggestions? That's a bug in smtplib.py, which will be fixed in 2.2.2. Please apply the patch below. Regards, Martin Index: smtplib.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/smtplib.py,v retrieving revision 1.46.4.2 retrieving revision 1.46.4.3 diff -u -r1.46.4.2 -r1.46.4.3 --- smtplib.py 25 Feb 2002 10:52:43 -0000 1.46.4.2 +++ smtplib.py 2 Jun 2002 12:32:04 -0000 1.46.4.3 @@ -137,6 +137,8 @@ self.sslobj.write(str) return len(str) + sendall = send + def close(self): self.realsock.close() From grante at visi.com Mon Oct 7 12:27:47 2002 From: grante at visi.com (Grant Edwards) Date: Mon, 07 Oct 2002 16:27:47 GMT Subject: Which Linux distribution References: <3DA0C5AB.7050609@something.invalid> Message-ID: <7Cio9.259$YJ1.942107@ruti.visi.com> In article , Bengt Richter wrote: > IMO it would be nice if RH took that advice for *its* use of > Python, and left bare "python" for the user to link as he saw > fit, if s/he didn't like a default convenience setting to the > latest stable version. I agree completely. If RH scripts depend on 1.5.2, then they should install an interpreter as python152, and call it explicitly. Fortunately it will be a moot point as soon as RH 8.2 comes out. I'm not upgrading until then -- I got burned upgrading to 6.0 and 7.0 was even worse. I haven't heard too many reports on 8.0, so my only conclusion is that those who upgraded to 8.0 must have been killed during the install process when their computers exploded. ;) -- Grant Edwards grante Yow! I'm protected by at a ROLL-ON I rented from visi.com AVIS... From a at b.c Wed Oct 2 05:55:08 2002 From: a at b.c (Michael Bakkemo) Date: 2 Oct 2002 09:55:08 GMT Subject: Why doesn't this work? References: Message-ID: > > Because of the way Tk works. You are setting up a lot of things before > entering the mainloop(), and not giving Tk a chance to execute and > update it's internal state (not your fault, really). > > But to fix things, add the line: > > sc.update() > > Just before: > > rect = MovingRect(root, sc, 40,40, 10, 10) > > [...] > > Chad Netzer > cnetzer at mail.arc.nasa.gov Thank you. That would have taken forever to figure out. From hancock at anansispaceworks.com Sat Oct 19 02:08:46 2002 From: hancock at anansispaceworks.com (Terry Hancock) Date: Fri, 18 Oct 2002 23:08:46 -0700 Subject: Python-list digest, Vol 1 #12813 - 12 msgs In-Reply-To: <20021019051101.19052.97519.Mailman@mail.python.org> References: <20021019051101.19052.97519.Mailman@mail.python.org> Message-ID: On Friday 18 October 2002 10:11 pm, python-list-request at python.org wrote: > Does anyone use Jython for serious applications? There is no Jython > newsgroup that I can locate, so I wonder if Jython postings are ok here? I > don't see to many of them. Most of the users here are using C Python, but the Python part should be the same regardless. Serious Jython discussion is available on a mailing list -- go to http://www.jython.org and follow the mailing list links to sign up for it. Volume is moderate -- I think it's about 10 posts a day or so. Jython specific questions are of course, really Java questions, since, aside from a few very minor details the behavior of interpreted code is going to be the same. I have never made anything serious in Jython myself, though I did finally manage to build a browser applet with it (basically "Hello world"). I'm told by wiser prorammers than me that it would be very inefficient to do any serious applets this way because of the long download times. On the other hand, the alternatives of programming in Javascript or Java are unattractive (probably for no better reasons than personal preference -- I prefer not having a huge number of different languages in a project, and my server side is in Python). Jython seems like the most transparent way to put Python on the client side, and not being a Java programmer, this seems to me to be Jython's main attraction. Java enthusiasts, however, seem to find this application irrelevant or trivial, and prefer to focus on the "huge array of Java libraries" that are available (compared I presume to Python or C, though I haven't found either that lacking, myself -- perhaps I just have a limited set of needs?). Making a specialized client that users must download and install isn't an option for the projects I'm working on now, so I'm still considering Jython for this application, despite the objections I've heard. Alternatively, I could use Java itself, but I don't know it (yet), so using Jython to script pre-existing classes seems more appropriate. I haven't gotten into that phase of the project, though, so, other than a few simple tests, I haven't done much with it. Certainly some folks get very opinionated about the strengths and weaknesses of Python versus Java -- to the point that some people are quite convinced that one or the other is altogether unnecessary. Clearly, if you believed that, Jython would be a poor or marginally useful option. Jython's existence implies a world in which Java and Python each have niches and can effectively cooperate. Some people seem to think that's true. Sorry to ramble, but I haven't reached any definitive conclusions about Jython -- I don't know if it's a "felicitous union" or an "illegitimate child" of Python and Java yet, but both appraisals seem to exist. :-) Cheers, Terry -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From tim.one at comcast.net Mon Oct 14 03:13:57 2002 From: tim.one at comcast.net (Tim Peters) Date: Mon, 14 Oct 2002 03:13:57 -0400 Subject: property() bug In-Reply-To: <20021014065234.GCVJ14888.fed1mtao01.cox.net@there> Message-ID: [Chuck Esterbrook] > I found a bug in both 2.2.2b1 and 2.2.1. Nope. Proof: If you had, I would be panicking . > Looking through the SourceForge Bugs Summaries, I didn't see it > listed. Anyone have any comments on this before I add it to the list? > > ------------------------------------------------------------------------ > class Good: > def foo(self): > # raises IOError as expected > return open('lsadflkdsfkjsdf').read() > try: > print Good().foo() > except IOError, e: > pass # as expected > > > class Bad: That's your problem. Properties are a new-in-2.2-feature that require new-style classes in order to work as intended, and you're defining an old-style ("classic") class. Change this to class Bad(object): and it will work fine. You could also do class Bad: __metaclass__ = type to force a new-style class without inheriting from object, or even put __metaclass__ = type near the top of the module to force *all* classes in the module to be new-style. Those are (IMO) more obscure, though. From achim.domma at syynx.de Tue Oct 15 06:04:37 2002 From: achim.domma at syynx.de (Achim Domma) Date: Tue, 15 Oct 2002 12:04:37 +0200 Subject: XMLGenerator / StringIO / ordinal not in range Message-ID: Hi, I try to produce an XML string in memory using XMLGenerator and StringIO. Everything works fine as long as I dont' try to write Non-ASCII charakters to the stream. If I would write to file, I would open it with codecs.open, but how can I tell StringIO to accept utf-8 encoding? greetings Achim From bellman at lysator.liu.se Wed Oct 9 12:37:31 2002 From: bellman at lysator.liu.se (Thomas Bellman) Date: Wed, 9 Oct 2002 16:37:31 +0000 (UTC) Subject: Misc questions about type objects and Python 3.0 References: Message-ID: "David Brown" writes: > As far as I > know, the only other way to do this is to regularly scan through all current > pointers to see what's in use - if there are any objects around that aren't > pointed to, they can be garbage collected. Yes, more or less. For example, the mark-and-sweep method works by traversing the web of objects, setting a bit in every object reached (marking them), and when that is finished, work through *all* objects, deleting those that weren't marked (sweeping). But there are lots of other methods and variations too. > This has got to be a much less efficient method. Not necessarily. You are likely underestimating the overhead of reference counting. For example, think about this little code snippet: y = 17 z = 69 x = y + z Lets look at the last line. First the values of y and z are extracted, and the reference counts of 17 and 23 are incremented. Then the __add__ method of 17 is located, and its refcount is incremented (you don't want it removed during its execution, which could happen if the __add__ method called some other code which eventually removed all other references to the int class). Then int.__add__ is called. It calculates the value 86, creates (or finds) the object 86, increments its refcount, and returns it. The refcounts of 17, 69, and the int.__add__ method, can now be decremented. 86 is bound to x, incrementing the refcount of 86. 86 is finally removed from the stack, decrementing its refcount. That's a total of nine (9) refcount manipulations. And the *only* object that has a different refcount than we started with, is 86; eight of those changes were in effect unnecessary. Now, that is admittedly a rather naive implementation. The last two changes of the refcount of 86 could for example easily be optimized away, leaving us with "only" six unnecessary refcount changes. But the int value 86 is, if I remember correctly, immortal in C-Python, and it is therefore really unnecessary to change its refcount too... A more intelligent implementation could probably optimize away a couple more of those refcount changes for this specific case, but in the general case you can't always do that. There are several GC methods that can be decidedly faster than reference counting. A google search should give you some reading material. http://www.cs.utexas.edu/users/oops/papers.html seems like a good start; especially Paul R Wilson's "Uniprocessor Garbage Collection Techniques" is supposed to be a good read. Besides, C-Python version 2 already implements true GC. Having *two* methods for GC running simultaneously, is *definitely* wasteful. -- Thomas Bellman, Lysator Computer Club, Link?ping University, Sweden "When C++ is your hammer, everything ! bellman @ lysator.liu.se looks like a thumb." ! Make Love -- Nicht Wahr! From see_reply_address at something.invalid Wed Oct 9 00:42:10 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Wed, 09 Oct 2002 17:42:10 +1300 Subject: [OT} How to un-GPL parts of a GPL'd module. References: Message-ID: <3DA3B3A2.1070902@something.invalid> Fernando P?rez wrote: > Seen on slashdot: > > "GPL made simple: What was my stuff is now our stuff. If you improve our > stuff, please keep it our stuff." > > Credit: user #46721, whoever that is. (I quote my sources :) I would put it as: "If you add your stuff to our stuff, your stuff is now our stuff too. Resistance is futile." :-) -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From gerhard.haering at gmx.de Thu Oct 10 04:22:42 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Thu, 10 Oct 2002 10:22:42 +0200 Subject: PyGreSQL-3.2 -> setup -> _pg In-Reply-To: References: Message-ID: <20021010082242.GA727@lilith.ghaering.test> * tertius [2002-10-09 22:42 +0200]: > Platform : Windows 32bit > Hi All, > The PyGresSQL setup program builds the _pg module from PostgreSQL + source > + pgmodule.c using "cl.exe" (I presume MS C compiler) Yep. Use python setup.py --compiler=mingw32 to build with the free GNU compilers. > Does anyone know where can I download a binary of that module? > (Without having to download PostgreSQL source and having to install a > MS C compiler) I used to provide them, but nowadays I recommend people to use pyPgSQL instead, which incidentally does have win32 binaries ==> http://pypgsql.sf.net/ If you've used the proprietary non DB-API interface of PyGreSQL, you can ask me to describe how to build the PostgreSQL client libraries and PyGreSQL using the free mingw compiler or fix your app to use the DB-API interface, in which case you can use pyPgSQL (or psycopg, if you're so inclined). > Documentation mentions http://highqualdev.com/ but the site does not seem to > exits. That was my domain once. -- Gerhard From jaqui at shaw.ca Mon Oct 21 15:39:20 2002 From: jaqui at shaw.ca (Jaqui) Date: Mon, 21 Oct 2002 19:39:20 GMT Subject: How do I invoke IE browser from Python on Mac OS X? References: <3DB43104.2030206@shaw.ca> Message-ID: <3DB4587D.1040708@shaw.ca> Skip Montanaro wrote: > >> I suspect perhaps there's something special about URLs so that they > >> are only opened with the default browser. > > jaqui> that isn't really a bad thing. I could not run the script you are > jaqui> working on if it requires ie, not available on linux.(besides my > jaqui> not liking ie and not wanting it on my comp ) default browser is > jaqui> a more portable solution than requiring a specific browser > > Yes, but the OP's question asked specifically how to launch IE on MacOSX > from Python viewing a particular URL. I don't use IE much either. I only > retain it for when some website I visit doesn't like Opera (or when the > current Opera 6.0 beta1 version I'm using bugs out on me). > true, which is why I only made the comment when you mentioned the default browser with urls issue. ~g~ I just think it is bad coding to rely on a specific proprietary app that doesn't support all os options if you want to make use of python's portability. had someone asking in a forum about the appearance of his frameset page. my view raised an issue for him, I only got the sources, not the view. and I noticed that he had coded the frames by pixel size not by percentages. he completely rebuilt his page to make it work for all viewers. it had upset him that I got the code insted of the page. ~g~ he felt it was an error in his coding. ( which it was, but how many people use mozilla with no javascript?) ;) From max at alcyone.com Wed Oct 2 21:02:25 2002 From: max at alcyone.com (Erik Max Francis) Date: Thu, 03 Oct 2002 01:02:25 GMT Subject: string.join question References: <3d9b905f_1@goliath.newsgroups.com> Message-ID: <3D9B9721.ABB1F632@alcyone.com> mongo57a at comcast.net wrote: > Trying to join a string as follows: string.join(['\,'aaa','\],'') > (the last characters are 2 single quotes). > I want a character string which looks like 'aaa' (with quotes). > Anybody know > what I'm doing wrong? or if this is possible with string.join? If I understand you correctly (which I'm not sure that I do), try something like string.join(["'", 'aaa', "'"], '') If you insist on using single quotes, you can use '\'' instead of "'". -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ Love is the selfishness of two persons. \__/ Antoine de la Salle Maths reference / http://www.alcyone.com/max/reference/maths/ A mathematics reference. From phoebe_1 at att.net Wed Oct 9 16:25:02 2002 From: phoebe_1 at att.net (Holden Caulfield) Date: 9 Oct 2002 13:25:02 -0700 Subject: Building Python 2.2.1 for HP Tru64 UNIX V4.0F References: Message-ID: "change" wrote in message news:... > Hi, > > I'm trying to build Python 2.2.1 for HP (COMPAQ) Tru64 UNIX V4.0F with the > debug option. > > The build fails in Python/marshal.c: > > cc -c -O -Olimit 1500 -I. -I./Include -DHAVE_CONFIG_H -o Python/marshal.o > Python/marshal.c > cc: Error: Python/marshal.c, line 64: Invalid expression. (badexpr) > *p->ptr++ = Py_SAFE_DOWNCAST(c, int, char); > ----------------------------^ > cc: Error: Python/marshal.c, line 64: Invalid statement. (badstmt) > *p->ptr++ = Py_SAFE_DOWNCAST(c, int, char); > ----------------------------^ > *** Exit 1 > Stop. > > > The problem seems to be the definition of Py_SAFE_DOWNCAST in > Include/pyport.h > > #ifdef Py_DEBUG > #define Py_SAFE_DOWNCAST(VALUE, WIDE, NARROW) \ > (assert((WIDE)(NARROW)(VALUE) == (VALUE)), (NARROW)(VALUE)) > #else > #define Py_SAFE_DOWNCAST(VALUE, WIDE, NARROW) (NARROW)(VALUE) > #endif > > > I also wrote a simple c program mimicking this behavior: > > #include > #include > > > #define SAFE_DOWNCAST(VALUE, WIDE, NARROW) (assert ((WIDE)(NARROW)(VALUE) > == (VALUE)), (NARROW)(VALUE)) > > main () { > > char p ; > int c ; > > c = 65 ; > p = SAFE_DOWNCAST(c, int, char) ; > > printf ("INT is: %d and CHAR is: %c\n", c, p) ; > > } > > > This program does not seem to compile with the cc or the gcc compilers. Is > there a problem with my C compilers or the switches I use with them? > > Thanks, > > Narendra All right do this: CC="cc -std1 -msg_disable longlongtype" export CC ( I am assuming you are bourne/Korn shell) Then run configure again. It will compile fine with or w/o the Debug option enabled. Explanation of the options: -std1 : This enforces strict compliance with ANSI C standard. Python seems to be one of the few apps that I have had success using the flag. Anyways, it is good thing to be compliant with the standard :) I guess -msg_disable longlongtype: All this does is reduce the noise on the long long type being a language extension (it is Informational and *not* warning btw). Now, as to why '-std1' would work. I have not had the time to shift through this. What it does do is define the macro __STDC__ = 1. cheers From BPettersen at NAREX.com Mon Oct 14 20:20:36 2002 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Mon, 14 Oct 2002 18:20:36 -0600 Subject: realtime design Message-ID: <60FB8BB7F0EFC7409B75EEEC13E2019201773D5C@admin56.narex.com> > From: Aahz [mailto:aahz at pythoncraft.com] > > In article , > Will Stuyvesant wrote: > > > >I am trying to come up with a method to run a function in such a way > >that the whole thing will take at most x milliseconds, with x a > >reasonable value like 200. If the function is not finished by that > >time, a default value should be used. If the function *does* finish in > >time, the return value of the function should be used. > > That last part isn't really possible, not if there are > statements that depend on external connectivity like I/O. > But it's certainly possible to make your main loop work the > way you want: have your function put its result on a > Queue.Queue. In your main function, time.sleep() for however > long it's supposed to, then do a non-blocking get() on the > queue. If the get() fails, do whatever's appropriate. This > gets trickier if your main program needs to be responsive > during the 200ms, but it's not impossible. You should be able to re-work the "Futures" receipe (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/84317) into doing what you want... (basically set a timestamp in __init__ and conditionally return a default value in __call__). -- bjorn From pinard at iro.umontreal.ca Wed Oct 2 18:56:49 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: Wed, 02 Oct 2002 18:56:49 -0400 Subject: PEP239 (Rational Numbers) Reference Implementation and new issues In-Reply-To: <20021002221421.GA29958@thyrsus.com> ("Eric S. Raymond"'s message of "Wed, 2 Oct 2002 18:14:21 -0400") References: <20021002221421.GA29958@thyrsus.com> Message-ID: [Eric S. Raymond] >> 1) Should future division return rationals rather than floats. > +1 for returning rationals. It's the right thing -- and if it fails, > it will fail noisily, right? While I agree with the theoretical arguments, I have the practical fear that rationals could grow very big, rather quickly, in the course of a long computation involving them in various ways. By big, I mean the numerator and denominator of the fraction taken in isolation, not the number itself. Consider inversions of an integer matrices, approximations with truncated series, or worse things like, maybe, discrete Fourier transforms. Bigger rationals are, slower they become, and more memory they take. The danger is that programmers may get surprised or hurt by Python performance degradation, raising frequent and recurrent questions here and elsewhere. On the other hand, I would love if Python was not loosing precision on non-truncating integer division, so let me try a bit to destroy my own fears. On average, most programs will not use matrices of rational numbers, nor play with series. Moreover, most programs do not use so many different numeric variables anyway, nor perform long computations involving them. Many programs do not go beyond adding or subtracting one, once in a while! So, I would guess that _on the average_, using rational numbers might be acceptable and go almost unnoticed by most people. So it might be more worth accepting as a community to warn programmers who are more prone to numerical algorithms of the intrinsic dangers of integer division in Python. But those feelings are no proof of anything. How do we get the confirmation that using rationals in Python would be easy going and innocuous in practice, beforehand? It would surely be nice relying in such a feature! -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From max at alcyone.com Tue Oct 8 21:25:00 2002 From: max at alcyone.com (Erik Max Francis) Date: Tue, 08 Oct 2002 18:25:00 -0700 Subject: [OT} How to un-GPL parts of a GPL'd module. References: <3DA350E7.5D190C5F@alcyone.com> Message-ID: <3DA3856C.DA574E90@alcyone.com> Anton Vredegoor wrote: > This is a strange coincidence. You just weren't wearing your foil cap, so I could read your mind :-). For the record, the software he's referring to is: http://www.alcyone.com/pyos/lsystem/ which is a really simple implementation of some Lindenmayer systems. > In the end I decided not to use the lindenmeyer system simulator > because I can just as soon write a tuple conversion script as wait for > you to answer my email. I do not want to imply that you are not > answering e-mail, just that the time it would take would be longer > than just writing a convertor myself. That's what I thought *then*. I didn't receive any email (my response to you in this thread was indeed mere coincidence). I checked my recent spam filters and didn't find anything either; when did you send me this? > By the way the lindenmeyer system algorithms themselves *are* in the > public domain, I think? Algorithms are patentable (whether that's wise or not), not copyrightable, so "public domain" doesn't quite have the same applicabilty. It's certainly not the case that Lindenmayer systems are patented (that I'm aware of), and I certainly wouldn't hold any such patent. Perhaps you were referring to the "obviousness" of the algorithm, which I'll address below. I'm presuming the algorithm you're referring to is that which is used to updated the Lindenmayer system each generation; i.e., the core routine inside LSystem.step. > However, just because the two systems would work so well together for > other implementations I got a bit frustrated about the license > imcompatibilities and started this thread in order to adress the issue > in a more general way. Now it seems not so hard at all to get in > contact with the author: The author contacts me voluntarily! At your service! If you tried to contact me in the past, I didn't get the email for whatever reason. > Since my program is public domain I have no problem with someone > relicensing (parts of) it as GPL, but then the problem for me would be > that I could not use the GPL'd derivates myself, because I want my > code in the public domain. I could get into a lenghty explanation > about this but lets just say I am a postmodernist and I want my code > snippets to survive seperately if my complete script would not be > used. > > Maybe we can work something out? Thanks for writing free sourcecode, As others have pointed out, GPL involves copyright, not patents, and copyright only applies to fix works; i.e., ideas, algorithms, and the like are not copyrightable and so a GPL license for some software implementing them does not apply to them directly. Furthermore, reading some copyrighted (GPL or otherwise) code that implements and algorithm doesn't preclude you from using the _algorithm_, even if it really didn't occur to you before seeing the code how to do it. This preclusion doesn't happen anymore than a company paying for training you in some skill now owns your skill. Despite however proud I might feel about my code, the Lindenmayer system implementation in question is really a very straightforward implementation of a well-defined, very well-known algorithm. Even if it were patented (by me or someone else contemporary), there would certainly be obviousness (can't remember the legal term) and prior art objections to it. This is even a special case, where usually a description of what a Lindenmayer system _is_ contains an outline of the algorithm for implementing one, so it's hard to see anybody could defend a patent on the algorithm (should one hypothetically exist). The core algorithm which I presume you're referring to is implemented in less than ten lines of Python code. That you read the copyrighted code and realized the algorithm doesn't preclude you from using the _algorithm_, just the _code_. So go ahead and reimplement the algorithm in your own code, just don't cut and paste. (If you're feeling nice you can credit me with the inspiration.) It's likely that another implementation of the algorithm would look very similar, but that shouldn't be too surprising in an expressive but concise language like Python. Certainly you should be commended on your presence of mind to actually publicly ask such questions rather than just making up your own mind to begin with, or, worse yet, ignore the GPL restrictions on the lsystem code and just use it to your heart's content anyway. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ Granted that I must die, how shall I live? \__/ Michael Novak Max Pandaemonium / http://www.maxpandaemonium.com/ A sampling of Max Pandameonium's music. From sholden at holdenweb.com Wed Oct 9 08:21:31 2002 From: sholden at holdenweb.com (Steve Holden) Date: Wed, 9 Oct 2002 08:21:31 -0400 Subject: Python-mysql: Still stuck. References: <3da326da$1_4@goliath.newsgroups.com> Message-ID: "ddoc" wrote in message news:anvnmf$gjv$1 at newsg2.svr.pol.co.uk... > mongo57a at comcast.net wrote: > > > Having (still) a problem getting MySQL and Python to work (MySQLdb), and > > I'm running out of hair to pull out. > > I'm also finding it alarmingly hard to get on top of this. > I have, in the past, spent some time tearing my hair out to get the client side of MySQL to compile on its own under Cygwin. I even asked for help from the MySQL implementors, but nothing came of that. There appeared to be some minor nits in the coding which made it hard for me to understand, but I'm not a C programmer. The position on Unix appears to depend on having the client-side libraries available. It really does seem quite bizarre that running under Python 2.2 the distutils are installing under 1.5. This sounds like a Red Hat installation: do any of the Python files contain a "#!/usr/bin/python" or similar which cause them to be executed under 1.5? regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- From mcfletch at rogers.com Wed Oct 2 12:31:44 2002 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Wed, 02 Oct 2002 12:31:44 -0400 Subject: Merging lists has made my brain hurt. References: <3D9B1953.3030109@moving-picture.com> Message-ID: <3D9B1F70.8090803@rogers.com> This is just off the top of my head, there are probably better ways... PythonWin 2.2.1 (#34, Apr 9 2002, 19:34:33) [MSC 32 bit (Intel)] on win32. Portions Copyright 1994-2001 Mark Hammond (mhammond at skippinet.com.au) - see 'Help/About PythonWin' for further copyright information. >>> lol = [['aaa', 'bbb', 'ccc'],['bbb', 'ccc', 'ddd'],['ccc', 'ddd', 'eee']] >>> def common( source ): ... if not source: ... return [] ... set = {} ... for item in source[0]: ... set[item] = 1 ... for other in source[1:]: ... for item in other: ... if set.has_key( item ): ... set[item] = set[item]+1 ... return [ key for (key,value) in set.items() if value == len(source)] ... >>> common(lol) ['ccc'] >>> I think Python 2.3 is going to have a sets module (hopefully back ported to Python 2.2.x eventually) which would probably be a more obvious approach. HTH, Mike Huw Lynes wrote: > Hi All, > > I have a list containing an arbitrary number of other lists. The > internal lists contain strings. For example > lol = [ > ['aaa', 'bbb', 'ccc'], > ['bbb', 'ccc', 'ddd'], > ['ccc', 'ddd', 'eee'] > ] > > I want to merge the three lists into a single list that only contains > the strings present in all three lists. In the above case I want to end > up with > ['ccc'] > > This has me utterly stumped. Any help is appreciated.The only articles > about merging strings that I've managed to find so far have been about > merging strings so that you don't get repeats. Not quite what I'm > looking for. > > Thanks, > Huw > _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From thephoenix235 at gmx.net Sun Oct 20 22:56:43 2002 From: thephoenix235 at gmx.net (thephoenix235 at gmx.net) Date: Mon, 21 Oct 2002 04:56:43 +0200 (MEST) Subject: variable refences for nested functions Message-ID: <29908.1035169003@www52.gmx.net> Hi, As I understand it, a nested function can access the local variables of the enclosing function. The following code works. def foo (): a=1 def bar(): print a bar() foo() But this does not. def foo (): a=1 def bar(): print a a=1 bar() foo() foo() is actually a state machine which takes a file as a argument. there are several bar()'s, each corresponding to a different state. 'a' is a line of the file. I could make foo into a class but i'd then have to prefix 'self.' to every value. (besides, it does not look like a function call anymore.) i am using python 2.2.1. anyone have a better workaround? ps: please include my address in the reply as i am not subscribed to the list. Chirayu. -- +++ GMX - Mail, Messaging & more http://www.gmx.net +++ NEU: Mit GMX ins Internet. Rund um die Uhr f?r 1 ct/ Min. surfen! From max at alcyone.com Tue Oct 8 17:40:55 2002 From: max at alcyone.com (Erik Max Francis) Date: Tue, 08 Oct 2002 14:40:55 -0700 Subject: [OT} How to un-GPL parts of a GPL'd module. References: Message-ID: <3DA350E7.5D190C5F@alcyone.com> Anton Vredegoor wrote: > how can I use a class or a function from a GLP'd module (cut-and-paste > style) in a module with BSD or public domain style release? > > I guess I could e-mail the author for permission but if I would have > to wait for them to answer, it would slow my coding process down to a > snail's pace, and there's always the possibility of the author being > unwilling. > > So that's not an option for me. I would rather rethink the problem and > start writing a new script. You really have only three options: 1. Don't use the snippet and be safe. 2. Use the snippet and be bound to GPL your code. 3. Contact the author and ask him to make a private release of the material for you with an altered license. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ A physicist is an atom's way of knowing about atoms. \__/ George Wald REALpolitik / http://www.realpolitik.com/ Get your own customized newsfeed online in realtime ... for free! From cliechti at gmx.net Thu Oct 10 16:48:06 2002 From: cliechti at gmx.net (Chris Liechti) Date: 10 Oct 2002 22:48:06 +0200 Subject: How to stop a thread? References: Message-ID: marvelan at hotmail.com (M) wrote in news:c0abefc3.0210101117.4db044fe at posting.google.com: > How can I stop a thread that is waiting to handle a TCP > socket? > > As there is no kill thread function in Python my first idea > was to do a handle_request until I set a global magical_flag. that's basicaly a good plan. maybe you want the terminate flag per thread. that way you can shutdown single connections without killing the entire app. > But then I realised that this works only when I have a steady > flow of connections comming in. Otherwise it will just hang > (as it should) in handle_request and thus the thread would > never stop. you could make the socket non-blocking, but then it may use lots of cpu power just to poll if there is data. the ususal way to go is select.select() with that function you're able to wait for data while having a timeout which allows to poll the terminate flag. if you don't want to do this "by hand" i sugest a look at TimeoutSocket (search google) chris > So, how can I stop the thread in the example below? I would > like to stop it when user presses the "stop" button in some > way. > > > class Foo(Thread): > > def run(self): > self.server = SocketServer.ThreadingTCPServer(addr, h) > > while not magical_flag: > self.server.handle_request() > -- Chris From dsavitsk at e-coli.net Sun Oct 6 13:32:05 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Sun, 06 Oct 2002 17:32:05 GMT Subject: Searching Python Manuals References: Message-ID: google's advanced search will let you limit the domain that you search in, so limit yourself to python.org. -d "Alexander Schmolck" wrote in message news:yfsy99b4wvu.fsf at black132.ex.ac.uk... > "Matt Gerrans" writes: > > > Is there some way to to search the Python manuals, other than grepping > > through all the html files? I use ActiveState's help file on the Windows > > platform for this purpose, but it only seems to work on certain platforms > > (;-). > > > > I exclusively use the 'info' version of the python manuals for exactly the > reason that it is fully searchable and very fast to navigate (*much* faster > than the hideous interface a webbrowser offers for the same > purpose). Unfortunately, there is no info version of the 2.2.1 docs, but one > for 2.2 can be found here: > > http://www.python.org/ftp/python/doc/2.2/info-2.2.tgz > > alex From aleax at aleax.it Mon Oct 7 10:25:42 2002 From: aleax at aleax.it (Alex Martelli) Date: Mon, 07 Oct 2002 14:25:42 GMT Subject: How to use the exec statement References: <3d9eca56_3@news.newsgroups.com> <3da09bf9_5@news.newsgroups.com> <3da18bc6_7@news.newsgroups.com> Message-ID: JB wrote: > Alex Martelli wrote: > [...] > > Thx, now everything works fine (but for catching user errors > that raise exceptions, which I have not implemented yet). Good to have been of use! Since you want to catch just about every error the user could make, you probably want a try/except with a very broad condition... in fact I fear you need a condition-less except (always a problem) since the user could raise a string, and even "except Exception:" won't catch THAT... that's rather a fragile thing to do (as it may mask any programming error) but it's hard to think of alternatives. > The concept of namespaces seems to be rather powerful > indeed. Full agreement -- ALMOST powerful enough to tame 'exec' (not quite, even with the further help given by modules rexec and Bastion, but almost...). Alex From cnetzer at mail.arc.nasa.gov Thu Oct 3 23:35:25 2002 From: cnetzer at mail.arc.nasa.gov (Chad Netzer) Date: Thu, 3 Oct 2002 20:35:25 -0700 Subject: [Python-Dev] PEP239 (Rational Numbers) Reference Implementation and new issues In-Reply-To: <3D9CFA77.19D2944A@alcyone.com> References: <3D9CF2ED.3020507@something.invalid> <3D9CFA77.19D2944A@alcyone.com> Message-ID: <200210040335.UAA15155@mail.arc.nasa.gov> My comments about 0/0 were somewhat tongue-in-cheek, so don't take them too seriously. :) As Tim Peters pointed out, there is often a convention in the numerical field to declare (for the purposes of floating point calculation) that: 1.0/0.0 = Inf 0.0/0.0 = NaN A useful question is what to do with the equivalent rational expressions? Should the floating point conventions be followed? Should there even be the equivalent of a NaN or Inf? Do they apply only when memory limits, or lossy conversions, come into play? My gut instinct is that both 1/0 and 0/0 should simply throw divide by zero, and that NaN and Inf do not exist. If they do exist, they are defined directly by subclasses of the rational type (and are NOT created by any simple, defined expression, only by practical limits). At least that should be the default; like floating point, there may be a need to override the exception throwing behavior (for array operations, etc.) But this complicates things, and since these are not performance critical, I think it best to keep things simple and consistent. Those working with large numbers of rationals may just have to deal with the possibility of exceptions, and perhaps precondition there data. (A compromise might be a DividedByZero object, that is distinct from a Nan or Inf) That said, I have little practical experience with rational types in other languages or toolkits. Any thoughts on these ideas? BTW. The expression/definition that always makes me shake MY head is (0**0 == 1). Limits are amazing things... -- Chad Netzer cnetzer at mail.arc.nasa.gov From tjreedy at udel.edu Thu Oct 10 13:03:25 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 10 Oct 2002 13:03:25 -0400 Subject: No tabs in post PLEASE!!! (was Re: partial list sort) References: <20021009094141.GA852@jsaul.de> <2Rep9.19819$ne4.8631@fe05> Message-ID: <0F6dnf9Fx-PKLjigXTWc3A@News.GigaNews.Com> > Is that why the subject line says "PLEASE!!!" that's a pretty loud shout. That was someone else. I should have said, perhaps, 'inspired' subthread rather than 'started'. TJR From mwh at python.net Tue Oct 1 10:22:48 2002 From: mwh at python.net (Michael Hudson) Date: Tue, 1 Oct 2002 14:22:48 GMT Subject: How do we explain clp to newcomers? References: Message-ID: Michael Hudson writes: > http://www.python.org/psa/MailingLists.html#clp > > ? > > Not the most obvious location, to be sure. And, actually reading the link, the comment: The traffic on this newsgroup can be heavy at times; for example, in February 1998, it received nearly 50 messages per day, and in March, 65! is pretty funny -- what's it running at now? 100? Cheers, M. -- [3] Modem speeds being what they are, large .avi files were generally downloaded to the shell server instead[4]. [4] Where they were usually found by the technical staff, and burned to CD. -- Carlfish, asr From timr at probo.com Thu Oct 3 03:14:44 2002 From: timr at probo.com (Tim Roberts) Date: Thu, 03 Oct 2002 00:14:44 -0700 Subject: regex: im getting better References: Message-ID: <8arnpugje10dnmpt8habhsgc2hlqcj9roi@4ax.com> ":B nerdy" wrote: >$pattern = '|]*)="([^"]*)")*>|ism'; Is that Perl? It ain't Python. The Python equivalent would be, I think: pattern = re.compile(']*)="([^"]*)")*>', re.I|re.S|re.M) >i'd like to match all the input tags's but also in a subexpression, i'd like >to match each of the parameters in the format >parameter_name="parameter_value" >where parameter_name and parameter_value are strings > >my pattern doesnt work, it only matches the last parameter, whats wrong with >my pattern? and can someone show me how one would match my description >above? You will need to do this in two steps: one to isolate the tag, another to use findall to fetch the parameters. However, this isn't very robust. The double quotes are optional in HTML (although not in XHTML), and the strings might very well contain either double quotes or angle brackets. Both will screw this up. Michal is correct; you should use one of the HTML parsers (like sgmllib). -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From sismex01 at hebmex.com Thu Oct 10 12:36:42 2002 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Thu, 10 Oct 2002 11:36:42 -0500 Subject: No tabs in post PLEASE!!! (was Re: partial list sort) Message-ID: Argh!! Talking about broken software... sent my post before I finished it. This must be divine justice for my arrogance or something like that. Please excuse my last post :-( Anyhow, what I wanted to exemplify in my verbose text, was that maybe it's handling it's tabs correctly (Alex' software), but since it's inserting a "> " at the beginning of the line, *some* text gets misaligned and other doesn't, because tabs don't move, yet spaces do. And, then there's the fact about programs having differing tab settings... So, actually, sending tabs to someone else, or to an open forum like Usenet, actually is endangering the sanity of any source code you might be quoting or inserting. So, as an act of courtesy, changing tabs to their equivalent spaces is very much appreciated. Alas, said courtesy is sometimes too much to ask. Please forgive our arrogance. -gustavo From Simon.Foster at smiths-aerospace.com Tue Oct 15 08:16:03 2002 From: Simon.Foster at smiths-aerospace.com (Simon.Foster at smiths-aerospace.com) Date: Tue, 15 Oct 2002 13:16:03 +0100 Subject: Problem with win32file.CreatFile... Message-ID: <00196A28.C22236@smiths-aerospace.com> Having installed the latest version of WIN32ALL on Python 2.2 I am getting the following error when running the Comport demo. Where has my win32file.CreateFile gone? Anyone any ideas? I'm running on NT4 SP5. D:\Python22\Lib\site-packages\win32\demos>D:\Python22\Lib\site-packages\win32\de mos\win32comport_demo.py Serial port terminal demo - press Ctrl+C to exit Traceback (most recent call last): File "D:\Python22\Lib\site-packages\win32\demos\win32comport_demo.py", line 124, in ? port = FindModem() File "D:\Python22\Lib\site-packages\win32\demos\win32comport_demo.py", line 29, in FindModem handle = CreateFile(port, NameError: global name 'CreateFile' is not defined D:\Python22\Lib\site-packages\win32\demos>python Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import win32file >>> dir( win32file ) ['ACCESS_SYSTEM_SECURITY', 'CALLBACK_CHUNK_FINISHED', 'CALLBACK_STREAM_SWITCH', 'COPY_FILE_FAIL_IF_EXISTS', 'COPY_FILE_RESTARTABLE', 'CREATE_ALWAYS', 'CREATE_NE W', 'DELETE', 'FILE_ACTION_ADDED', 'FILE_ACTION_MODIFIED', 'FILE_ACTION_REMOVED' , 'FILE_ACTION_RENAMED_NEW_NAME', 'FILE_ACTION_RENAMED_OLD_NAME', 'FILE_ADD_FILE ', 'FILE_ADD_SUBDIRECTORY', 'FILE_ALL_ACCESS', 'FILE_APPEND_DATA', 'FILE_ATTRIBU TE_ARCHIVE', 'FILE_ATTRIBUTE_COMPRESSED', 'FILE_ATTRIBUTE_DIRECTORY', 'FILE_ATTR IBUTE_HIDDEN', 'FILE_ATTRIBUTE_NORMAL', 'FILE_ATTRIBUTE_OFFLINE', 'FILE_ATTRIBUT E_READONLY', 'FILE_ATTRIBUTE_SYSTEM', 'FILE_ATTRIBUTE_TEMPORARY', 'FILE_CASE_PRE SERVED_NAMES', 'FILE_CASE_SENSITIVE_SEARCH', 'FILE_CREATE_PIPE_INSTANCE', 'FILE_ DELETE_CHILD', 'FILE_EXECUTE', 'FILE_FILE_COMPRESSION', 'FILE_FLAG_BACKUP_SEMANT ICS', 'FILE_FLAG_DELETE_ON_CLOSE', 'FILE_FLAG_NO_BUFFERING', 'FILE_FLAG_OVERLAPP ED', 'FILE_FLAG_POSIX_SEMANTICS', 'FILE_FLAG_RANDOM_ACCESS', 'FILE_FLAG_SEQUENTI AL_SCAN', 'FILE_FLAG_WRITE_THROUGH', 'FILE_GENERIC_EXECUTE', 'FILE_GENERIC_READ' , 'FILE_GENERIC_WRITE', 'FILE_LIST_DIRECTORY', 'FILE_MAP_ALL_ACCESS', 'FILE_MAP_ COPY', 'FILE_MAP_READ', 'FILE_MAP_WRITE', 'FILE_NOTIFY_CHANGE_ATTRIBUTES', 'FILE _NOTIFY_CHANGE_CREATION', 'FILE_NOTIFY_CHANGE_DIR_NAME', 'FILE_NOTIFY_CHANGE_FIL E_NAME', 'FILE_NOTIFY_CHANGE_LAST_ACCESS', 'FILE_NOTIFY_CHANGE_LAST_WRITE', 'FIL E_NOTIFY_CHANGE_SECURITY', 'FILE_NOTIFY_CHANGE_SIZE', 'FILE_PERSISTENT_ACLS', 'F ILE_READ_ATTRIBUTES', 'FILE_READ_DATA', 'FILE_READ_EA', 'FILE_SHARE_DELETE', 'FI LE_SHARE_READ', 'FILE_SHARE_WRITE', 'FILE_TRAVERSE', 'FILE_UNICODE_ON_DISK', 'FI LE_VOLUME_IS_COMPRESSED', 'FILE_WRITE_ATTRIBUTES', 'FILE_WRITE_DATA', 'FILE_WRIT E_EA', 'GENERIC_ALL', 'GENERIC_EXECUTE', 'GENERIC_READ', 'GENERIC_WRITE', 'MAILS LOT_NO_MESSAGE', 'MAILSLOT_WAIT_FOREVER', 'MAXIMUM_ALLOWED', 'MEM_COMMIT', 'MEM_ DECOMMIT', 'MEM_FREE', 'MEM_IMAGE', 'MEM_MAPPED', 'MEM_PRIVATE', 'MEM_RELEASE', 'MEM_RESERVE', 'MEM_RESET', 'MEM_TOP_DOWN', 'OPEN_ALWAYS', 'OPEN_EXISTING', 'OVE RLAPPED', 'PAGE_EXECUTE', 'PAGE_EXECUTE_READ', 'PAGE_EXECUTE_READWRITE', 'PAGE_E XECUTE_WRITECOPY', 'PAGE_GUARD', 'PAGE_NOACCESS', 'PAGE_NOCACHE', 'PAGE_READONLY ', 'PAGE_READWRITE', 'PAGE_WRITECOPY', 'PROGRESS_CANCEL', 'PROGRESS_CONTINUE', ' PROGRESS_QUIET', 'PROGRESS_STOP', 'READ_CONTROL', 'SECTION_ALL_ACCESS', 'SECTION _EXTEND_SIZE', 'SECTION_MAP_EXECUTE', 'SECTION_MAP_READ', 'SECTION_MAP_WRITE', ' SECTION_QUERY', 'SEC_COMMIT', 'SEC_FILE', 'SEC_IMAGE', 'SEC_NOCACHE', 'SEC_RESER VE', 'SPECIFIC_RIGHTS_ALL', 'STANDARD_RIGHTS_ALL', 'STANDARD_RIGHTS_EXECUTE', 'S TANDARD_RIGHTS_READ', 'STANDARD_RIGHTS_REQUIRED', 'STANDARD_RIGHTS_WRITE', 'SYNC HRONIZE', 'TRUNCATE_EXISTING', 'WRITE_DAC', 'WRITE_OWNER', '__builtins__', '__do c__', '__file__', '__name__', 'calldll', 'cstring', 'file', 'gencb', 'kernel32', 'memory_mapped_file', 'structob', 'windll', 'winerror'] From sholden at holdenweb.com Tue Oct 1 12:21:09 2002 From: sholden at holdenweb.com (Steve Holden) Date: Tue, 1 Oct 2002 12:21:09 -0400 Subject: Decimal arithmatic, was Re: Python GUI app to impress the bos s? References: Message-ID: "James J. Besemer" wrote in message news:mailman.1033464184.26508.python-list at python.org... > > sismex01 at hebmex.com wrote: > > >"Integer arithmetic" != "32-bit integer arithmetic". > > > I never said it was. I made a true assertion about "normal integers," > meaning the native machine word size on most machines. > > >Python longs are memory-limited, yet they > >are also based on machine integers. Does that make them > >unsuitable? > > > I know. I never said they weren't. > > But Steve said "integers' NOT "Python longs" and my only point was that > Steve's original suggestion (as stated) was not practical with most > machine's native integers. > I never said that, as I have already pointed out. It was Outlook Express' weird quoting, which in that post I failed to correct, that made it look like me. Be that as it may, if that was your only point you'd do well to stop hammering it now everyone's heard you. > And I'll add that if you're going to consider Longs you may as well go > with FixedPoint and do it "right". ;o) > regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- From chrabros at seznam.cz Tue Oct 1 11:43:13 2002 From: chrabros at seznam.cz (Chrabros) Date: Tue, 01 Oct 2002 17:43:13 +0200 Subject: Help mi please with optimalization of simple Python code Message-ID: Hello,, I have written my first simple application in Python and I have a problem that processing of cca 10MB file takes ages (30 seconds). I think that problem is in data structure used. Could you please give me an advice how to optimize the following piece of code? Thank you in advance. Dalibor while y I want to write something like: If ClassOf(myobj) == "MyClass": print "OK!" or If ClassOf(myobj) == MyClass: print "OK!" # no quotes on class The best I've found in Python is based on str(myobj.__class__). What's the official way? Thanks. Newbie still, Joshua Stern From jb at yahoo.de Thu Oct 3 17:28:59 2002 From: jb at yahoo.de (JB) Date: Thu, 03 Oct 2002 23:28:59 +0200 Subject: Python on a Novell server References: <3d928cb5_6@news.newsgroups.com> Message-ID: <3d9cb480_2@news.newsgroups.com> Bo wrote: > JB wrote in > news:3d928cb5_6 at news.newsgroups.com: > >> We have a Novell net at our school and are trying to >> install Python 2.2 on a Novell server. This does not work >> at the moment as we get the error message "python.dll not >> found" at the moment. >> >> Is it possible to install Python a a server or has it to >> be installed locally on each workstation? >> > > > > Are you trying to run it off a common mapped drive? > Watch your permissions to make sure that the use can > see\use it. > > bo Thx. what do you mean by "it"? -- J.... B.... -----------== Posted via Newsfeed.Com - Uncensored Usenet News ==---------- http://www.newsfeed.com The #1 Newsgroup Service in the World! -----= Over 100,000 Newsgroups - Unlimited Fast Downloads - 19 Servers =----- From aremovethiscanton at adamsremovethis-blake.com Sun Oct 13 21:47:52 2002 From: aremovethiscanton at adamsremovethis-blake.com (Adams-Blake Co.) Date: Sun, 13 Oct 2002 18:47:52 -0700 Subject: What dir. should Jython be installed in? Message-ID: <3daa230b@monitor.lanset.com> The Jython 2.1 installer seems to want to put Jython in the directory that it was downloaded in. Being new to Linux (Mandrake 8.2) I'm wondering if I should be in root for this install and if I should put it in /usr/lib or someplase other than a home sub-directory. Thanks, Al From kalteisn at yahoo.com Thu Oct 10 17:57:34 2002 From: kalteisn at yahoo.com (Nico C. Kalteis) Date: Thu, 10 Oct 2002 17:57:34 -0400 Subject: Python Forms? References: Message-ID: I want to thank all of you for your help with this. It's been invaluable and much appreciated. Cheers! Nico "Nico C. Kalteis" wrote in message news:ao1q28$ua0$1 at slb3.atl.mindspring.net... > Good day! > > First of all, thank you to anybody who can answer me this. I'm primarily an > ASP developer and have only recently had cause to tinker with Python. So > here is my question: > > Is there a way to use Python to retrieve variables that are passed to it by > a form without using a CGI script? In other words, is there something > equivalent to the ASP script: > > <% localvariable = request("querystring") %> > > Any help would be greatly appreciated... > > Sincerely, > > Nico C. Kalteis > > > From op73418 at mail.telepac.pt Wed Oct 16 10:53:31 2002 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Wed, 16 Oct 2002 15:53:31 +0100 Subject: design question on threading Message-ID: Hi, I have been studying the code in the threading module and in it the responsability of putting the Thread object in the active threads list is on the Thread object itsef. I want to change this and place this burden in a dedicated ThreadManager object - with the proviso that the Thread's themselves should know about it as little as possible, after all a Thread does not have to know that it is managed or owned by something in another thread. This object will have a start method with an initialized (but not started) Thread as argument, and I have devised one way to do this that I will describe in words. Before doing it, let me say that a Thread has a variable set from None to an integer id that indicates it has started. A: Issue the start method of the Thread and then enter a loop, possibly sleeping in the middle, where we probe the variable until we get the desired result, then we add the Thread to the active list. Are there better ways to do this? I say better because I do not like entering busy loops to check for something. On the other the communication between the threads is kept to a minimum which is something i particularly like... All the best, Gon?alo Rodrigues From martin at v.loewis.de Wed Oct 16 22:02:02 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 17 Oct 2002 04:02:02 +0200 Subject: International APPs / pygettext References: <3DAC5E22.1060102@web.de> <3DAD2741.8040903@web.de> <3DAD2D18.7000108@web.de> <3DAD53C0.2070106@web.de> <3DADA4CB.1050606@web.de> <3DADE118.6080304@web.de> Message-ID: Ingo Linkweiler writes: > > Did you try "pygettext.py -d langtest *.py"? > > same result: > File "C:\python22\tools\i18n\pygettext.py", line 509, in main > fp = open(filename) > IOError: [Errno 2] No such file or directory: '*.py' > > It seems there are no wildcards allowed. How can I get one .pot-file > from many .py-files? Ah, I see. Windows. You need to list all files explicitly on the command line. Alternatively, get a shell that does wildcard expansion, or extend pygettext.py to do wildcard expansion, or use Unix. Regards, Martin From jb at cascade-sys.com Tue Oct 1 18:43:13 2002 From: jb at cascade-sys.com (James J. Besemer) Date: Tue, 01 Oct 2002 15:43:13 -0700 Subject: Decimal arithmetic, with example code References: Message-ID: <3D9A2501.6030402@cascade-sys.com> Tim Peters wrote: >No single rounding discipline is >suitable for all commercial applications, > Ain't it the Truth!! Businesses in the US are required to file quarterly reports about periodic tax payments made during the quarter. Taxes, e.g. on FICA and Medicare, are computed as a percentage of each employee's wages and deducted from the employee's paycheck each pay period. On the quarterly report, the actual liability is computed, based as a percentage of total payroll for the period. These two computations (sum of percentages and percentage of sums) do not always produce the same amount. And yet the amounts on the return have to match to the exact penny -- no rounding off to the nearest dollar (like on personal returns). Consequently, the form includes an explicit entry for "round off error," to correct for minor differences in computed liability vs. actual payments. --jb -- James J. Besemer 503-280-0838 voice 2727 NE Skidmore St. 503-280-0375 fax Portland, Oregon 97211-6557 mailto:jb at cascade-sys.com http://cascade-sys.com From ianb at colorstudy.com Tue Oct 15 19:24:37 2002 From: ianb at colorstudy.com (Ian Bicking) Date: 15 Oct 2002 18:24:37 -0500 Subject: Clipboard (was Re: Python pattern repository) In-Reply-To: References: Message-ID: <1034724278.826.2794.camel@dsl-65-184-205-5.telocity.com> On Tue, 2002-10-15 at 18:09, Bengt Richter wrote: > BTW2, ISTM it ought to be possible to make a getclip for unix (maybe talking to gpm or > some gui thing?) so that os.popen(getclip) will be a platform-independent thing to write. xclip -o (don't know about gpm, though) Ian From ianb at colorstudy.com Thu Oct 10 20:25:31 2002 From: ianb at colorstudy.com (Ian Bicking) Date: 10 Oct 2002 19:25:31 -0500 Subject: Concrete classes -- stylistic question In-Reply-To: References: Message-ID: <1034295932.21802.124.camel@dsl-65-184-205-5.telocity.com> On Thu, 2002-10-10 at 16:29, Alex Martelli wrote: > Gerhard H?ring wrote: > ... > > Now who will come up with a neat example using metaclasses? > > I borrowed Guido's time machine to post about that: > > http://tinyurl.com/1wq1 I should really learn to understand what's going on with metaclasses, but here's my attempt at similar functionality without metaclasses... # Use Required if you don't want an attribute to have a default # (i.e., a value has to be given at instantiation) class Required: pass def bunchbuilder(className, **kw): class Bunch(object): __slots__ = kw.keys() __defaults = kw __name = className def __init__(self, **kw): for var in self.__slots__: if self.__defaults[var] is Required \ and not kw.has_key(var): raise TypeError, "%s() did not provide required keyword argument %s" % (self.__name, var) if kw.has_key(var): setattr(self, var, kw[var]) del kw[var] else: setattr(self, var, self.__defaults[var]) if kw: raise TypeError, "%s() got unexpected keyword argument %s" % (self.__name, kw.keys()) def __repr__(self): names = [name for name in dir(self) if not name.startswith('__') and not name.startswith('_Bunch__')] names.sort() return "%s(%s)" % (self.__name, ", ".join( ["%s=%s" % (name, repr(getattr(self, name))) for name in names])) return Bunch # Example, create a Point class: Point = bunchbuilder('Point', x=Required, y=Required, color='grey') p = Point(x=4.3, y=0.3) print p p.x = 10 From mwilson at the-wire.com Tue Oct 22 09:47:24 2002 From: mwilson at the-wire.com (Mel Wilson) Date: Tue, 22 Oct 2002 09:47:24 -0400 Subject: New to python References: <3db2fcc9$0$5803$fa0fcedb@lovejoy.zen.co.uk> Message-ID: In article , Bob Koss wrote: >I'm a very experienced C++/Java programmer. Can anyone recommend papers or >books that will help me avoid programming C++ using Python syntax and to >learn to do things the "Python way". I dunno, I found the docs supplied with the Python release to be very, very good. I ditched the O'Reilly books (for the first time in my life) and just learned from the docs. I only know a little C++ and Java, but it seemed that there was a pretty direct mapping of the useful parts. Lose the braces, as you know them, and most of the semicolons, obviously. Where you would use ``, use lists, or tuples ,, that is [] or () . Where you would use ``, use dictionaries ,, that is {} . The semantics of iterators is available, but most of the syntax goes away. `for item in alist:` iterates over all the items in alist, one by one .. where `alist` is a sequence, i.e. a list, tuple, or string. To iterate over a sublist, use slices: `for item in alist[1:-1]:` does as above, but omits the first and last items. For trickier iterations, read and re-read the Library doc on the topic of general-purpose functions. There are some functions that apply to sequences: map, filter, reduce, zip. that can work wonders. Hidden somewhere under the documentation for sequences there is a description of string methods that you'll want to read. Hidden under the docs for 'Other Types' are the descriptions of all the file methods. There are no iostreams per se, but the class method __str__ can get some of the effect for your own classes, and there are surely other angles I haven't thought of. Forget polymorphism. You can define a function, and call it with anything you want, but if it has to behave differently for different type operands, you have to use the run-time type identification `type` function explicitely within the single definition of the function. Default arguments to functions are just as powerful a tool as in C++. In class definitions the equivalents of operator methods are covered in a chapter in the Python Language Reference. (Look for the double-underscore methods like __cmp__, __str__, __add__, etc.) In C, the gotcha for new users is probably about pointers; they're tricky and they can't be avoided. The gotchas in Python are situations when you use different references to a single object, thinking you are using different objects. I believe the difference between mutable and immutable objects comes into play. I have no clear answers here .. I still get caught once in a while .. keep your eyes open. Read the Tutorial once, skim the Library Reference .. at least the table of contents, then skim the Language Reference and you will probably have encountered everything you need. Regards. Mel. From aleax at aleax.it Tue Oct 8 18:47:19 2002 From: aleax at aleax.it (Alex Martelli) Date: Tue, 08 Oct 2002 22:47:19 GMT Subject: Python threading? References: Message-ID: Steve Holden wrote: ... > Until I read this, I thought there might be practical reasons to think > about mixing the two approaches. Asyncore is a great way to be responsive > to incoming network connections and data, but if the process then has to > hang around to do database I/O you might not win very much from the > asynchronous approach. It seems that Twisted Matrix lets you mix the two approaches quite nicely -- as an asyncore fan to another, I would suggest you look into Twisted, as "a better asyncore than asyncore" in some ways:-). (I've only really looked into the lower levels, so far, but I like what I see there, quite a lot). Alex From vze4rx4y at verizon.net Thu Oct 3 17:04:30 2002 From: vze4rx4y at verizon.net (news.verizon.net) Date: Thu, 03 Oct 2002 21:04:30 GMT Subject: A challenge from the Mensa Puzzle Calendar References: Message-ID: > I'm a puzzle kind of guy, so I thought some of you might be, too. > I'd be very curious to see the kind of solutions people come up with. > My solution ended up being a total of 19 lines of code, including a > print statement to give me a nice formatted output for each solution, > resembling the initial problem from the calendar. > > OK, folks. The gauntlet is down. Have at it! for a in range(700,800): for b in range(100): digits = list('%d%d%d' % (a, b, a*b)) digits.sort() if digits == list('0123456789'): print '%5d\n%5d\n-----\n%5d' % (a, b, a*b) Raymond Hettinger From aahz at pythoncraft.com Mon Oct 14 00:42:07 2002 From: aahz at pythoncraft.com (Aahz) Date: 14 Oct 2002 00:42:07 -0400 Subject: newbie question on threading References: <7cpjqugerih8sos23strcsftgt53tbs8lo@4ax.com> Message-ID: In article <7cpjqugerih8sos23strcsftgt53tbs8lo at 4ax.com>, Gon?alo Rodrigues wrote: >On 13 Oct 2002 02:32:32 -0400, aahz at pythoncraft.com (Aahz) wrote: >>In article , >>Gon?alo Rodrigues wrote: >>> >>>#Balancing act: We can't afford a pure busy loop, so we >>>#have to sleep; but if we sleep the whole timeout time, >>>#we'll be unresponsive. >>> >>>My question is: why is a busy loop not affordable (without a sleep >>>call), e.g. something like (in pseudo-code description) >>> >>>while 1: >>> >>> if : >>> break >>> if : >>> break >>> >> >>Consider this: >> >> while 1: >> pass >> >>Given the above loop in a thread, how much useful work is the thread >>doing? Not much, right? Well, adding an "if" statement to the loop >>doesn't do any good for producing useful work. > >I must be missing something but I am not understanding. Isn't that what >the wait method is supposed to do? Put the thread dormant, waiting until >you get timedout or you can acquire the lock? The only difference >between the pseudo-loop I wrote above and the one in the threading >module is a call to to time.sleep - and that is the core of my question, >why even bother to add the sleep call? Why not just a pure simple busy >loop? Why can't we afford it? Note carefully that I said "useful work". The point is that a busy loop consumes CPU resources, but it is *NOT* doing useful work, and in consuming those CPU resources, it is keeping other threads from doing useful work. Because time.sleep() causes an OS-level block, other threads can run during the time.sleep(). The problem is a tradeoff between the delay in response caused by calling time.sleep() versus the amount of CPU time consumed by the busy loop. In fact, you shouldn't even be using condition objects in the first place, IMO. Figure out a way to use a Queue, and your application will almost certainly be both more efficient *and* more responsive. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From max at alcyone.com Fri Oct 18 15:30:14 2002 From: max at alcyone.com (Erik Max Francis) Date: Fri, 18 Oct 2002 12:30:14 -0700 Subject: repr(x) == repr(y) <=> x == y AND eval(repr(x)) == x References: Message-ID: <3DB06146.EB1BFA8F@alcyone.com> Thorsten Kampe wrote: > I'm using dictionaries for some "very generalized programs". This > means that I cannot tell in advance if all the items I'm operating on > are hashable. The "trick" that came to my mind was to use repr(x) as > the key (instead of x). > > This relies on two assumptions: > > 1. repr(x) == repr(y) <=> x == y An overridden __repr__ might not qualify, but the default one (containing the class name and the id of the object) would. > 2. eval(repr(x)) == x (for further processing) Any user-defined instance that defines __hash__ but doesn't do very special tricks with __repr__ would not qualify. Which potentially means you're leaving out a huge group of potential objects. If you're interested in whether or not the objects are hashable, why not just try calculating their hashes, and then handle the error should one happen? -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ Consistency is the last refuge of the unimaginative. \__/ Oscar Wilde Church / http://www.alcyone.com/pyos/church/ A lambda calculus explorer in Python. From martin at v.loewis.de Mon Oct 21 17:59:10 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 21 Oct 2002 23:59:10 +0200 Subject: Parsing SGML document in Python program References: Message-ID: pinard at iro.umontreal.ca (Fran?ois Pinard) writes: > This was a while ago, but _if_ I remember well, the documentation was very > clear when I needed it. The trick is to read slowly and carefully! :-) In any case, I think we can safely post the code in question. Regards, Martin def read_sgml_file(name): stack = [] current = [] attrs = {} # Avoid docbk30, which raises some unanalysed interference. # Also request UTF-8 processing for line in os.popen('SGML_CATALOG_FILES= SP_ENCODING=UTF-8 SP_CHARSET_FIXED=YES nsgmls %s' % name).readlines(): if line[0] == '(': stack.append(current) current = [string.lower(line[1:-1])] if attrs: current.append(attrs) attrs = {} continue if line[0] == ')': element = tuple(current) current = stack[-1] del stack[-1] current.append(element) continue if line[0] == '-': line = line[1:-1] line = string.replace(line, '\\n', '\n') line = string.replace(line, '\\011', '\t') line = string.rstrip(line) current.append(line) continue if line[0] == 'A': attr = line[1:].split() if attr[1] == "IMPLIED": continue if attr[1] == "TOKEN": attrs[attr[0].lower()] = attr[2].lower() continue raise ValueError,_("Unsupported attribute %s") % `attr` continue if line[0] == 'C': return current[0] raise ValueError,_("SGML in `%s' is not conformant.\n") % name From hansgeunsmeyer at earthlink.net Fri Oct 11 20:55:00 2002 From: hansgeunsmeyer at earthlink.net (hg) Date: 11 Oct 2002 17:55:00 -0700 Subject: Using SaveThread and RestoreThread with callbacks References: Message-ID: <95959723.0210111654.5a55609c@posting.google.com> adam at cardaccess.com.au (Adam Rutkowski) wrote in message news:... > I've got some Python code calling a C function, which performs a > PyEval_SaveThread(), does some stuff, then calls a > PyEvalRestoreThread(). The problem is, part of the stuff it does is > execute a Python callback function. To do this, it performs a > PyEvalRestoreThread(), does the callback, then does a > PyEval_SaveThread(). So the code looks something like this: > > x = PyEval_SaveThread() > C stuff... > PyEvalRestoreThread(x) > Callback() > x = PyEval_SaveThread() > C stuff... > PyEvalRestoreThread(x) Instead of PyEval_SaveThread/RestoreThread I'd say it's safer to use the macro's Py_BEGIN_ALLOWTHREADS/Py_END_ALLOWTHREADS, because if you forget or misplace one of them, you'll get a compile-time error. These calls are only necessary in a multi-threaded application, and only if the C-stuff may block other threads. If your C-stuff isn't blocking, I don't see a reason to save/restore the thread state. > The question is, is this the way I should be doing things? I don't > quite understand what thread state information is being > saved/restored, so I don't whether it's possible for code to alter the > thread state in such a way that restoring to a saved thread state will > cause problems. If you use the macro's, it will also be less tempting to do something with x. It's surely possible to alter the saved thread state in such a way that all sorts of funny things start to happen when you restore it. (The simplest change would be to set x = NULL...) But why would you do that? :) If the C-stuff isn't touching x (or what it points to), I don't think the state can alter before it has been restored. Hans From pedronis at bluewin.ch Mon Oct 7 09:13:37 2002 From: pedronis at bluewin.ch (Samuele Pedroni) Date: Mon, 7 Oct 2002 15:13:37 +0200 Subject: [Python-Dev] Fw: MRO 2.2 vs 2.3 References: <038401c26d70$52fd6c60$6d94fea9@newmexico> <200210062027.g96KRwh28684@pcp02138704pcs.reston01.va.comcast.net> Message-ID: <027001c26e03$5982d960$6d94fea9@newmexico> From: "Robin Becker" > I got the impression from lurking on the discussion that this new > behaviour was intended and not achieved. Personally I found the > reasoning about why one should do the extended precedence thing > extremely tenuous as it seems to be based on assertions about programmer > expectation. It's hard to believe that many can do high order graph > analysis by inspection of the terminal node order. > if with extended precedence you refer to the extended precedence graph, both 2.2 mro algo and C3 respect it (intuitively, you can think of both as L*LOOPS + further constraints) so there's no difference in that. regards From robin at jessikat.fsnet.co.uk Thu Oct 10 12:28:46 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Thu, 10 Oct 2002 17:28:46 +0100 Subject: Strange compiler warning References: <3da227db$1@news.sentex.net> <3da4af97@news.sentex.net> Message-ID: <$OLOkWA+qap9EwjT@jessikat.fsnet.co.uk> In article <3da4af97 at news.sentex.net>, Peter Hansen writes ....... >It's not necessarily better. That's why I said both "generally", >above, and "what are you really trying to accomplish?" > >Once we know exactly what you intended, it may become >feasible to discuss which really _is_ better. Until >then, I can say only that "except NameError" (and note >it should NOT be just "except") is more readable _to me_ >than the lengthy expression you used. Just personal taste, >at this point. Oh, also probably faster, since it is >not executing two or more Python function calls to do >the job, if that matters to you. .... this isn't a real problem, I'm lazy and I want to do some local debugging inside a method without putting the global into the module, that way I can remove things without moving up and down too much. So it's probably not an issue about speed. I was just querying whether setting up a try/except is more complex than a dict lookup in globals(). For the two cases I see code like 6 SET_LINENO 6 9 LOAD_GLOBAL 0 (globals) 12 CALL_FUNCTION 0 15 LOAD_ATTR 1 (has_key) 18 LOAD_CONST 1 ('_dbg') 21 CALL_FUNCTION 1 24 UNARY_NOT 25 JUMP_IF_FALSE 22 (to 50) 28 POP_TOP 29 SET_LINENO 7 32 LOAD_GLOBAL 2 (open) 35 LOAD_CONST 2 ('/tmp/_dbg.txt') 38 LOAD_CONST 3 ('w') 41 CALL_FUNCTION 2 44 STORE_GLOBAL 3 (_dbg) and 6 SET_LINENO 10 9 SETUP_EXCEPT 11 (to 23) 12 SET_LINENO 11 15 LOAD_GLOBAL 0 (_dbg) 18 POP_TOP 19 POP_BLOCK 20 JUMP_FORWARD 28 (to 51) >> 23 SET_LINENO 12 26 POP_TOP 27 POP_TOP 28 POP_TOP 29 SET_LINENO 13 32 LOAD_GLOBAL 1 (open) 35 LOAD_CONST 1 ('/tmp/_dbg.txt') 38 LOAD_CONST 2 ('w') 41 CALL_FUNCTION 2 44 STORE_GLOBAL 0 (_dbg) so probably the try has it since the op codes seem very simple. -- Robin Becker From jubafre at brturbo.com Thu Oct 3 15:41:02 2002 From: jubafre at brturbo.com (jubafre at brturbo.com) Date: Thu, 3 Oct 2002 16:41:02 -0300 (GMT-03:00) Subject: Button in tkinter??/ Message-ID: <1031421493.1033674062333.JavaMail.nobody@webmail1> I have a button with a event call, when i start the program and click in the button the event do somenthing, after the event finished the button continues pressioned, why???? self.open = Button(frame, text='Procuar',widt=10,bd=3) self.open.bind("", Procura) self.open.pack(side=LEFT, padx=5) Juliano Freitas www.gebrasil.hpg.com.br From aleax at aleax.it Thu Oct 10 06:00:38 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 10 Oct 2002 10:00:38 GMT Subject: Combinatorics References: <3D9B1953.3030109@moving-picture.com> Message-ID: Peter Dobcsanyi wrote: > Thorsten Kampe wrote: >> The program uses some standard external routines: >> comb, fact, perm, quotient_set, set and cartes listed beneath the code > ... >> #v+ >> def comb(n, k): >> return fact(n) / (fact(k) * fact(n-k)) >> >> def fact(integer): >> factorial = 1 >> for factor in range(2, integer+1): >> factorial *= factor >> return factorial >> >> def perm(n, k): >> return fact(n) / fact(n-k) > > Risking the sin of premature optimization :-), here is a version for > comb() not defined in terms of the factorial function. I think a simpler optimization is to memoize fact (untested, I'm just typing this in by memory): _facts = [1] def fact(integer): assert integer >= 0 for i in range(len(_facts), integer+1): _facts.append(i*_facts[-1]) return _facts[integer] This makes it fast enough in an amortized sense to use freely as a primitive. And you only need to pre-populate _facts in the obvious way to a greater extent to reduce the startup cost to be amortized. You need _facts = [1L] if you want to support old versions of Python, of course. Alex From paul at nlhas.no Tue Oct 15 04:32:33 2002 From: paul at nlhas.no (paul at nlhas.no) Date: Tue, 15 Oct 2002 08:32:33 GMT Subject: Subclassing FixedPoint Message-ID: Can anyone explain why the following fails when using the subclass (recursion problem), but work using the base class? It worked with the last "pre-Sourceforge" version of FixedPoint, so I presume this might be a bug in the latest version -- I just can't for the life of me see what could cause this! pm ================================================== from fixedpoint import FixedPoint class FP(FixedPoint) : """Subclass of FixedPoint""" def __init__(self, value, precision): FixedPoint.__init__(self, value, precision) def _test(): _y = 378 _x = FP(793.1 , 6) #_x = FixedPoint(793.1 , 6) _z = _y/_x print type(_y) , ' : ' , _y print type(_x) , ' : ' , _x print type(_z) , ' : ' , _z if __name__ == '__main__': _test() From bokr at oz.net Sat Oct 19 19:33:50 2002 From: bokr at oz.net (Bengt Richter) Date: 19 Oct 2002 23:33:50 GMT Subject: Using Python for blogging References: Message-ID: On 19 Oct 2002 03:06:39 -0700, hwlgw at hotmail.com (Will Stuyvesant) wrote: >Hello all ! > >reStructuredText (reST) looks cool! So I was thinking about doing >blogging (web logging, sort of keeping a diary at your ISP) with >Python. The existing blogging software I know of positively stinks >IMHO. > >My ideal thing would be to be able to edit a file at home using reST. >Then I need some scripts to transform that into html and send it to my >ISP. For turning reST into html there are example scripts in the reST >Tools directory. > >I now have some scripts that work. For every day there is a reST file >with name e.g. 291002.txt for date 19 october 2002. And it is in a >directory with name 1002 (guess what:). So you just edit the files >using reST and you write scripts to turn that into html (could just >use html.py in the reST Tools directory). I have just this to add to Gerhard's useful post: Before you accumulate a lot of files and directories, I would recommend you change your date representation to yymmdd or yy-mm-dd to get sensible sorting of file listings outside the directory listing utility (e.g. if you pipe the output of a whole dir tree through a filter and want it sorted). E.g., you can tell windows to use alternate date representation, and it will show up that way most everywhere you see a date in a windows app. > >But! The resulting html does not really look like I want, I mean I do >not like the fonts and the sizes etc. Unfortunately I do not know >much about HTML so I have a question: How to improve this? >Recommandations? Use CSS? Any pointers on that? Regards, Bengt Richter From huw at moving-picture.com Wed Oct 2 12:05:39 2002 From: huw at moving-picture.com (Huw Lynes) Date: Wed, 02 Oct 2002 17:05:39 +0100 Subject: Merging lists has made my brain hurt. Message-ID: <3D9B1953.3030109@moving-picture.com> Hi All, I have a list containing an arbitrary number of other lists. The internal lists contain strings. For example lol = [ ['aaa', 'bbb', 'ccc'], ['bbb', 'ccc', 'ddd'], ['ccc', 'ddd', 'eee'] ] I want to merge the three lists into a single list that only contains the strings present in all three lists. In the above case I want to end up with ['ccc'] This has me utterly stumped. Any help is appreciated.The only articles about merging strings that I've managed to find so far have been about merging strings so that you don't get repeats. Not quite what I'm looking for. Thanks, Huw From mchermside at ingdirect.com Wed Oct 23 09:32:28 2002 From: mchermside at ingdirect.com (Chermside, Michael) Date: Wed, 23 Oct 2002 09:32:28 -0400 Subject: hostid? Message-ID: <902A1E710FEAB740966EC991C3A38A8903C27846@INGDEXCHANGEC1.ingdirect.com> > Thanks all for your advice. Magnus Lycka provided the solution, for Windows > XP: > > If you by MacID mean MAC address, or Media Access Control > address, i.e. the hardware address in the network card, > this could work on Win 2000 for instance. I realize this is long solved, but just wanted to point out a sometimes-useful resource. FAQTs python section had a great solution for this, and it even handled multiple NIC cards: http://www.faqts.com/knowledge_base/view.phtml/aid/5418/fid/244 Sometimes the Python section (http://www.faqts.com/knowledge_base/index.phtml/fid/199) at FAQTs is handy. -- Michael Chermside From sismex01 at hebmex.com Mon Oct 7 19:13:28 2002 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Mon, 7 Oct 2002 18:13:28 -0500 Subject: how safe is Python for CGI? Message-ID: > From: DG [mailto:david at fielden.com.au] > > Greetings, > > I am thinking about using Python's CGI capabilities to write > some simple web front ends to a database. The web server is > running apache under Linux, Python 2.2.1. > > How secure is Python for this? For example, it seems that I > will need to put the database path, username and password into > the database connect() line in the cgi-bin script, is it > possible for someone to download the script from the cgi-bin > directory without running it, and then inspect the > source to find the database path/user/pass? > > What are common Python practices to circumvent this, if it is > a problem? > > Are there any other gotchas to this sort of script? > > tia > > Rowdy > This is responsability of your Apache installation, not Python's. You have to mark your cgi-bin directory as executable, non-browsable, etc etc. There's other FAQs you can search for which contain detailed documentation on this subject. Google is your friend :-) -gustavo From fuf at mageo.cz Wed Oct 9 07:22:30 2002 From: fuf at mageo.cz (Michal Vitecek) Date: Wed, 9 Oct 2002 13:22:30 +0200 Subject: Removing ^M In-Reply-To: References: <200206081448.g58Empj11746@localhost.localdomain> Message-ID: <20021009112230.GA8357@foof.i3.cz> if your system has vim installed you could do: $ vim file.html :set ff=unix :wq this changes the fileformat from whatever it was to unix (removing ^M characters) and writes the changed file and quits vim. Sean 'Shaleh' Perry wrote: >> >> There's a program called dos2unix that will do this. From your mail >> headers it looks to me like you have a Unix/Linux system in which case >> it may already be installed. If not do a google search on dos2unix. >> > >another possibility is fromdos (and its brother todos). -- fuf (fuf at mageo.cz) From mark.charsley at REMOVE_THIS.radioscape.com Tue Oct 1 06:32:00 2002 From: mark.charsley at REMOVE_THIS.radioscape.com (Mark Charsley) Date: Tue, 1 Oct 2002 11:32 +0100 (BST) Subject: redhat8 References: Message-ID: In article , anthony at computronix.com (Anthony Tuininga) wrote: > According to the release documentation: > > Python 2.2.1 is on the CD. > > Finally.... :-) Have they got a link called python_2_2_1 which is used in all their system configuration scripts, or are we going to be in analogous situation in a couple of years time, cursing Redhat because upgrading to python 2.4 breaks their system scripts? -- Mark - personal opinion only, could well be wrong, not representing company, don't sue us etc. etc. From gerhard.haering at opus-gmbh.net Wed Oct 2 05:11:39 2002 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 2 Oct 2002 09:11:39 GMT Subject: patch in Python? References: <7xit0l3koi.fsf@ruckus.brouhaha.com> Message-ID: Alex Martelli [2002-10-02 08:53 GMT]: > Gerhard H?ring wrote: > ... >>> Looking at the docs I don't see any features that gmpy doesn't have. >>> I think it would be better to use gmpy, which is widely used, has >>> assembly language optimizations for many cpu's, etc. >> >> Probably, except one of the requirements is a BSD-ish license, as in the >> end this will be used for the NUMERIC type of pyPgSQL. If it's going to >> be useful for other purposes, that's a nice side-effect. > > Both the "assembly language optimizations" and the LGPL license, of > course, are due to the underlying GMP library (which my gmpy just > wraps for Python consumption). My comment was meant to be about GMP, not the wrapper, as the GMP license (LGPL) effectively covers your Python wrapper as well. > [...] Besides, even if gmpy were to be BSD-licensed, the underlying GMP would > no doubt remain LGPL, so, changing gmpy's license would be rather useless per > se Yep. -- Gerhard From xx758 at cam.ac.uk Mon Oct 7 05:25:28 2002 From: xx758 at cam.ac.uk (Xiao-Qin Xia) Date: Mon, 07 Oct 2002 10:25:28 +0100 Subject: Tcl/Tkinter problem Message-ID: Hi, After installed a Chinese ttf font, Tkinter for Python2.2 cannot work anymore: """ [xqxia at mwise1 xqxia]$ python Python 2.2 (#2, Aug 21 2002, 16:22:49) [GCC 2.96 20000731 (Red Hat Linux 7.1 2.96-98)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from Tkinter import * >>> r = Tk() Traceback (most recent call last): File "", line 1, in ? File "/usr/local/lib/python2.2/lib-tk/Tkinter.py", line 1487, in __init__ self.tk = _tkinter.create(screenName, baseName, className) TclError: Can't find a usable init.tcl in the following directories: /usr/lib/tcl8.3 / $(Af g g?%f (B.3 / $(Af f This probably means that Tcl wasn't installed properly. """ and wish faces the samilar problem: """ [xqxia at mwise1 tcl8.3]$ wish #?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#? #?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#? #?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#? #?#?#?#?#?#?#?#?#?#?#?#?#?#?usr/lib/tcl8#?#?#?#?lib/tcl8#?#?#?#?lib/tcl8 #?3/librar#?#?#?librar#?#?#?tcl8#?3/librar#?#?#?usr/lib/tcl8#?#?#?#? #?#?#?#?#?#?#?#?#?#?#?#?#?#?#?@(#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#? #?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#?#? #?#?#?#?#?#?#?#?#?#?#?#?#?[xqxia at mwise1 tcl8.3]$ """ but the Tkinter of python1.5 or pythonworks can work properly. If I rename the directory /usr/lib/tcl8.3 and /usr/lib/tk8.3 to anything other, python1.5 cannot use Tkinter either. So I guess python1.5 and python2.2 use the same Tk library. But why they behavior different? Does anybody know how to solve this problem? Cheers, Xiao-Qin From bokr at oz.net Thu Oct 3 20:51:40 2002 From: bokr at oz.net (Bengt Richter) Date: 4 Oct 2002 00:51:40 GMT Subject: Decimal arithmetic, with example code References: Message-ID: On 3 Oct 2002 18:16:55 GMT, bokr at oz.net (Bengt Richter) wrote: >On 3 Oct 2002 07:08:38 GMT, bokr at oz.net (Bengt Richter) wrote: >[...] >> >>BTW, you probably noticed I wasn't really rounding in my evenround function -- >>I was just noodging the value so the subsequent round inside %.f looked like it >>was doing decimal bankers round. I just played a hunch with the BIAS multiply. >>Using FixedPoint as a final formatter for floating point should work better than >>bias-kludging the ordinary round. It's probably about as good an estimate of the >>nearest decimal of a given precision to a given fp number as you can get. >> >[...] >> >>BTW, FWIW, since the denominator is 1L << -e where you round the conversion, >>the following should hold (I think, not very tested): >> >> exactHalf = 1L << (-e-1) >> n = top + exactHalf # ok round except banker's tie with odd no >> wasTie = not (n & ((exactHalf<<2)-1L)) # odd => even and no 1's below >> n = (n >> -e) - wasTie # readjust for bad tie result >> >> assert n == _roundquotient(top, 1L << -e) >> >>Whether it's worth doing depends on speeds which I haven't tested. Depends on divmod and cmp... >>Out of steam for tonight... >> >Not enough steam to get it right ;-/ -- this should work better and faster: > > exactHalf = 1L << (-e-1) > wasTie = not (top & (exactHalf-1L)) # no 1's below > n = top + exactHalf # ok round except banker's tie => odd > n = (n >> -e) > n -= n & wasTie # readjust for bad tie result > assert n == _roundquotient(top, 1L << -e) > Sheesh ;-0 exactHalf = 1L << (-e-1) wasTie = (top & ((exactHalf<<1)-1L))==exactHalf n = top + exactHalf # ok round except banker's tie => odd n = (n >> -e) n -= n & wasTie # readjust for bad tie result assert n == _roundquotient(top, 1L << -e) I was too anxious to avoid the shift. Thanks for not stomping all over me ;-) I'm testing a debugging class using sys.settrace, so the above is not getting thorough attention, except that I can now look at it with the new tool ;-) > >>BTW2, I wonder if it would be worth while to do a banker's round like round, but guaranteeing >>that the result's magnitude will be the first fp state >= the true decimal value. It would >>be biased minisculely, but it might be helpful for printing non-surprising decimals. str(f) >>seems to be solving part of the problem, but an alternate %f (%F?) to control bankers round >>at a given precision might be nice. A few bits from fixedpoint could be cannibalized. >> Regards, Bengt Richter From Henrik.Weber at sys.aok.de Wed Oct 9 06:10:26 2002 From: Henrik.Weber at sys.aok.de (Henrik Weber) Date: 9 Oct 2002 03:10:26 -0700 Subject: DBI cursor behaviour with multiple statements? References: <7e964d1d.0209270137.568a3f3@posting.google.com> <23891c90.0209300554.5b37c195@posting.google.com> <7e964d1d.0210010652.5b8768de@posting.google.com> <23891c90.0210020458.e69b4fd@posting.google.com> Message-ID: <7e964d1d.0210090210.724589c5@posting.google.com> paul at boddie.net (Paul Boddie) wrote in message news:<23891c90.0210020458.e69b4fd at posting.google.com>... > Henrik.Weber at sys.aok.de (Henrik Weber) wrote in message news:<7e964d1d.0210010652.5b8768de at posting.google.com>... > > paul at boddie.net (Paul Boddie) wrote in message news:<23891c90.0209300554.5b37c195 at posting.google.com>... [...] > > > However the result of that operation has to be a SQL statment that the native > > RDBMS will understand, so it's not important what the query string looks like > > as long as the underlying database will accept it. > > Indeed, and many database systems accept placeholders/parameters > because they do understand them. > > > > Personally, I'd recommend supporting different parameter notations, > > > since this issue always confuses people. > > > > The paramstyle variable is supposed to be a string, so I can't put > > several different values in there. > > You could support paramstyle reconfiguration at connection time. This > would require you to substitute the parameters used for those employed > by the database system, however. In the last few days I have made some experiments with ADO and the Jet OLE DB provider. They seem to understand several syntax styles for parameters more or less directly. For the rest I think it is possible to reformat the query string. Alright, I'll make the paramstyle user configurable. > > > I could use the native parameter notation of the database, which is > > qmark in this case. This is not one of the preferred notations > > according to the DBI description, so I thought I might use pyformat > > instead. Somewhere I have read that preparing a query doesn't make a > > difference in performance with Access so I might just as well pass a > > new query string to the database for every set of parameters without > > losing anything. In the example it would have been possible to pass a > > named placeholder (like "%(parm)s") and a sequence of dictionaries > > instead without changing the code of the method. > > Yes, but then you have to do the quoting of the supplied values on > behalf of the caller - it's not up to them to do this. > > > Anyway I haven't yet decided on a quoting style and the style I'm > > currently using is different from the one in the example. It was just > > that the example was shorter this way and it didn't make a difference > > for the question I was trying to have answered. > > No, but the use of apostrophes in the values suggested that you > equated placeholders/parameters with string > substitution/interpolation/replacement, when they're clearly not the > same thing. If you weren't under that illusion then I apologise now. No reason to apologise. Basically I was under that illusion. I hadn't given much thought to parameters when I posted my first message. Well, I got answers for two questions by posting only one. That's pretty efficient ;-) > > > > "SELECT * FROM table WHERE column IN %s" > > [...] > > > > This appears highly counter-intuitive, of course, since the > > > Python-style %s parameter marker actually represents a list in this > > > case - another reason for choosing a better parameter notation. > > > > No, it doesn't represent a list. > > Consider the alternative notation: > > SELECT * FROM table WHERE column IN :1 Would you also expect the database module to know to place parentheses around the placeholder? The Jet Provider complains about them missing, so the user at least has to write: SELECT * FROM table WHERE column IN (:1) > > I would definitely expect a list/tuple/sequence to be supplied as the > value that binds to the parameter. Indeed, the psycopg developers > appear to agree. > > [...] > > > As I said above a DBI wrapper doesn't parse the query to find out how > > to interpret the parameters (at least it would surprise me very much > > if it did). It is still the users responsibility to assure that the > > queries sent to the database are syntactically correct. Passing lists > > as query criteria like in your example above is not going to work. > > You're right in the sense that some database modules don't need to > look at the query string at all. If the underlying database system > supports placeholder notation, you can risk sending the query string > to the database system... > > some_api_query("SELECT * FROM SOME_TABLE WHERE SOME_COLUMN = :1") > > ...and then traverse the list of values, binding each one as you go: > > for i in range(0, len(values)): > if some_api_bind(i, values[i]) == FAILED: > raise SomeException, "Could not bind all values." > > If the database system doesn't like it, you'll get told about it, and > you would pass this failure condition back in some meaningful way. The Jet OLE DB provider does not like lists or tuples as parameters directly. What might work is to try to bind the parameter. When the attempt fails determine if the parameter is a sequence and if so replace the placeholder with a number of new placeholders depending on the length of the sequence. Then the elements of the sequence could be bound one by one to the new placeholders. > On the issue of syntax, the only thing the user needs to guarantee is > the syntax of the query string, *not* whether the query string with > "pasted in" values is also syntactically correct (especially since a > simplistic string replacement is *not* what goes on). Moreover, with > some database modules, the user doesn't really need to check the types > of the values very carefully either, but that's another story. > > Paul Thanks for your input. It will help me address some issues I'm just now starting to come across. --Henrik From mwh at python.net Mon Oct 14 07:42:14 2002 From: mwh at python.net (Michael Hudson) Date: Mon, 14 Oct 2002 11:42:14 GMT Subject: Amazon review (was Re: Love "Python Cookbook") References: <%Dfp9.35332$cS4.1385227@news2.tin.it> Message-ID: "Thorsten Roskowetz" writes: > Matthias Huening wrote: > > By the way: Amazon has just reduced the price of the Cookbook > > (EUR 48,12 > EUR 36,10 / $39.95 > $27.97). > > Considering that as of today a EUR is $0,9876 its quite a > difference in pricing - is this all due to taxes? At least in Britain, we don't pay VAT (sales tax) on books. (The amount more I would have spent on books in the last copule of years if we did is, frankly, terrifying). Cheers, M. -- Q: What are 1000 lawyers at the bottom of the ocean? A: A good start. (A lawyer told me this joke.) -- Michael Str?der, comp.lang.python From martin at v.loewis.de Fri Oct 4 02:08:16 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 04 Oct 2002 08:08:16 +0200 Subject: xml.dom.minidom parser error References: Message-ID: revyakin at yahoo.com (revyakin) writes: > Thanks Martin! I'll do that, I wonder why it was not necessary with > 2.1 though. Was PyXML included with it? No. Did you get perhaps get prebuilt binaries for 2.1? Regards, Martin From martin at v.loewis.de Fri Oct 11 01:52:33 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 11 Oct 2002 07:52:33 +0200 Subject: Python, CORBA, and Borland Java interop? References: <37d3f56b.0210101713.74e1b934@posting.google.com> Message-ID: dave at 3dex.com (Dave Benjamin) writes: > Does anyone know of a possible solution (open source or commercial) to > this Python->Java interoperability issue? If you can impose restrictions on the expressiveness of the IDL you need to support, then it should be possible to add valuetypes to any of the ORBs in reasonable time. For example, if you only need StringValue/WStringValue, then implementing this as a special case. I'm most familiar with Fnorb these days; I'd invite you to post details of your requirements (only value boxes or true value types, inheritance or not, truncation or not, support for cyclic structures or not, what to do about methods, etc.). I also seem to recall that omniORBpy has made progress in the area of valuetypes, so you may want to check the latest version. Regards, Martin From Henk Wed Oct 9 05:23:01 2002 From: Henk (Henk) Date: Wed, 09 Oct 2002 09:23:01 GMT Subject: getting the script name Message-ID: <3da3f528.11933703@news.skynet.be> Hi, Is there any way to retrieve the name of the running script from within this running script? Thanks, Henk From meles at free.fr Thu Oct 17 19:10:19 2002 From: meles at free.fr (Meles MELES) Date: Fri, 18 Oct 2002 01:10:19 +0200 Subject: Barre de progression Message-ID: <5jfnoa.94c.ln@farfadet.home.org> Bonsoir ? tous, je suis ? la recherche d'exemple d'impl?mentation d'une ba rre de progression en mode console (ou, ? d?faut en mode graphique) un peu du style de celle de urpmi lors de l'installation d'un paquet a vec la mandrake. Si en plus, ? la fin de celle ci, le pourcentage de t ravail effectu? pouvait s'afficher, ce serai le bonheur. L'id?al pour moi serait de voir un code tout fait pour m'en inspirer, au pire un peu de docs derait l'affaire. Cordialement Blaise TRAMIER -- Le plus ane des trois n'est pas celui qu'on pense. -- Jean de La fontaine, Le Meunier, son fils et l'Ane From wurmy at earthlink.net Sun Oct 20 13:06:43 2002 From: wurmy at earthlink.net (Hans Nowak) Date: Sun, 20 Oct 2002 17:06:43 GMT Subject: Q: Subclassing dict and __cmp__ References: <33803989.0210192240.6dced01b@posting.google.com> Message-ID: <3DB2E390.7030407@earthlink.net> Miki Tebeka wrote: >>>>class H(dict): >>> > def __cmp__(self, other): > '''Compare only x's''' > if self['x'] == other['x']: > return 0 > return 1 What do you want this code to do when 'x' doesn't exist in either of the dictionaries? Also, __cmp__ doesn't return just 0 or 1... it is supposed to return -1 if self < other, 0 if self == other, and 1 if self > other. Third, overriding just __cmp__ may not be enough. There's also the __eq__ method. Here's my version (untested and all that), with print statements so it's clear which method is called: >>> class H(dict): def __cmp__(self, other): print 'wheee!' return cmp(self['x'], other['x']) def __eq__(self, other): print '__eq__ called' return self['x'] == other['x'] >>> h1 = H({'x': 2}) >>> h2 = H({'x': 3}) >>> h1 > h2 wheee! 0 >>> h2 > h1 wheee! 1 >>> h1 == h2 __eq__ called 0 >>> h1 == h1 __eq__ called 1 HTH, -- Hans (base64.decodestring('d3VybXlAZWFydGhsaW5rLm5ldA==')) # decode for email address ;-) The Pythonic Quarter:: http://www.awaretek.com/nowak/ Kaa:: http://www.awaretek.com/nowak/kaa.html From cbbrowne at acm.org Thu Oct 17 13:01:10 2002 From: cbbrowne at acm.org (Christopher Browne) Date: 17 Oct 2002 17:01:10 GMT Subject: SOAP frustrations References: <3DAC6F04.2030704@mindspring.com> <23891c90.0210170137.481cda6@posting.google.com> Message-ID: The world rejoiced as paul at boddie.net (Paul Boddie) wrote: > Christopher Browne wrote in message news:... >> Perl's SOAP::Lite takes, to my mind, the /right/ approach to this; it >> creates what the implementors call a "SOM" object which is essentially >> a 'parse tree' of the XML message. >> >> $foo = some_soap_call(arguments); >> print $foo->result(), "\n"; # Prints the result >> print $foo, "\n"; # $foo is an object containing the >> # parse tree... > > Well, unless "SOM" is interoperable with the DOM, I don't think it's > entirely the right approach. I've been using various Java APIs to do > SOAP stuff, and someone at Sun clearly decided that instead of > exposing a normal DOM interface to SOAP messages, they would invent > another API which is very similar but incompatible. If it weren't > for Jaxen (the XPath package for Java) stepping in to save the day, > I'd be at an even higher point of irritation with JAXM than I > already am. I'm not sure if "SOM" is interoperable with anything at all, and I frankly don't care. It's easy enough to work with, if we consider the evils of doing recursive tree walks in Perl to be a "stipulated given." The point is that it involves keeping the XML parse tree, which is the Right Thing, as opposed to parsing it and throwing the XML data away, which is the Wrong Thing that naive SOAP implementations do. >> The problem with many of the SOAP implementations (including those for >> Python) is that the call to the result() method is implicit, and you >> /never/ get a chance to intercept the XML so as to be able to do more >> sophisticated things with it, such as looking for encrypted portions >> and decrypting them... > My unfashionable opinion is that if you want to do RPC, especially if > other languages are involved, then CORBA is a mature enough technology > that probably won't be as frustrating as SOAP to use or to deploy. There's one problem with CORBA: It's nastier to get it through firewalls, because there are lots of reasonably interoperable HTTP proxies, but IIOP proxies are much rarer. Of course, SOAP has /no/ "call-back" approach, so its functionality "bottoms out" rather quickly... Note that I've books in print that demonstrate the use of both CORBA and SOAP using Python; while "future royalties" commend the idea of my commending interest in SOAP, I certainly prefer CORBA... -- (concatenate 'string "aa454" "@freenet.carleton.ca") http://cbbrowne.com/info/publications.html "The nice thing about standards is that you have so many to choose from. Furthermore, if you do not like any of them, you can just wait for next year's model." -- Tanenbaum, "Computer Networks" From gerhard.haering at gmx.de Sat Oct 19 11:13:48 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 19 Oct 2002 15:13:48 GMT Subject: Using Python for blogging References: Message-ID: Will Stuyvesant wrote in comp.lang.python: > Hello all ! > > reStructuredText (reST) looks cool! Indeed. > [...] But! The resulting html does not really look like I want, I > mean I do not like the fonts and the sizes etc. Unfortunately I do > not know much about HTML so I have a question: How to improve this? > Recommandations? Use CSS? Definitely. > Any pointers on that? http://dmoz.org/Computers/Programming/Internet/CSS/Tutorials/ Here's a simple one I use on http://www.cs.fhm.edu/~ifw00065/ I have this in a file global.css: to use the style sheets, I just have this in the section of the HTML files: HTH, -- Gerhard From martin at v.loewis.de Fri Oct 11 01:57:42 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 11 Oct 2002 07:57:42 +0200 Subject: how to use smtp starttls() encryption? References: <8f41cfd.0210101719.ad47c7@posting.google.com> Message-ID: xucs007 at yahoo.com (Xu, C.S.) writes: > Anybody can teach me? Previously I can just use the > smtp.login(user, password) to authenticate my machine > before sending out emails. Now, before invoking login, you invoke starttls. This causes the connection to become encrypted, which, in turn, protects your password against being snooped. Since you are not verifying any certificates in this mode of operation, you are prone to a man-in-the-middle attack. However, this is the usual operation of starttls in the internet, so you should not worry about this too much. Regards, Martin From loewis at informatik.hu-berlin.de Wed Oct 2 12:27:46 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 02 Oct 2002 18:27:46 +0200 Subject: I really give up References: Message-ID: "piter" writes: > I tried it also. Doesn't work... It works fine for me. In a C program, if I do printf("%x\n", make_hash("Hallo",45)); I get 53589e48 When I do print hex(make_hash("Hallo",45)) with the posted Python function, I get 0x53589E48L Seems close enough to me... Regards, Martin From lichvb at public.cs.hn.cn Thu Oct 31 04:57:42 2002 From: lichvb at public.cs.hn.cn (cn) Date: 31 Oct 2002 01:57:42 -0800 Subject: aids fewr aids mko aids fewrfs aids rewr aids Message-ID: <7693c9c8.0210310157.953bbcc@posting.google.com> aids mko aids rwqrs aids mkl klp jkp dfsad dsad ewd aids jiop aids ewqe aids erwqe aids dwqd fsd aids fewd aids cdfe fsa dsews aids wedxd aids rwesd fsd fdsre fsdaids mko aids njio aids yjkh aids wfdsf aids jio aids nhji aids rwesd aids ewaew rewr r3wrsdf aids mko aids rwqrs aids mkl klp jkp dfsad dsad ewd aids jiop aids ewqe aids erwqe aids dwqd fsd aids fewd aids cdfe fsa dsews aids wedxd aids rwesd fsd fdsre fsdaids mko aids njio aids yjkh aids wfdsf aids jio aids nhji aids rwesd aids rewrsd 3rsf rsr fdsfew deasd jiom rw fsr mop rewrsdd kop cdsfwe kop rwqe jiop ewaew rewr r3wrsdf aids mko aids rwqrs aids mkl klp jkp dfsad dsad ewd aids jiop aids ewqe aids erwqe aids dwqd fsd aids fewd aids cdfe fsa dsews aids wedxd aids rwesd fsd fdsre fsdaids mko aids njio aids yjkh aids wfdsf aids jio aids nhji aids rwesd aids rewrsd 3rsf rsr fdsfew wedsad fsr aids mko aids rwqrs aids mkl klp jkp dfsad dsad ewd aids jiop aids ewqe aids erwqe aids dwqd fsd aids fewd aids cdfe fsa dsews aids wedxd aids rwesd fsd fdsre fsdaids mko aids njio aids yjkh aids wfdsf aids jio aids nhji aids rwesd aids ewaew rewr r3wrsdf aids mko aids rwqrs aids mkl klp jkp dfsad dsad ewd aids jiop aids ewqe aids erwqe aids dwqd fsd aids fewd aids cdfe fsa dsews aids wedxd aids rwesd fsd fdsre fsdaids mko aids njio aids yjkh aids wfdsf aids jio aids nhji aids rwesd aids rewrsd 3rsf rsr fdsfew deasd jiom rw fsr mop rewrsdd kop cdsfwe kop rwqe jiop ewaew rewr r3wrsdf aids mko aids rwqrs aids mkl klp jkp dfsad dsad ewd aids jiop aids ewqe aids erwqe aids dwqd fsd aids fewd aids cdfe fsa dsews aids wedxd aids rwesd fsd fdsre fsdaids mko aids njio aids yjkh aids wfdsf aids jio aids nhji aids rwesd aids rewrsd 3rsf rsr fdsfew aids ews aids fef aids fd aids fef aids aids mko aids rwqrs aids mkl klp jkp dfsad dsad ewd aids jiop aids ewqe aids erwqe aids dwqd fsd aids fewd aids cdfe fsa dsews aids wedxd aids rwesd fsd fdsre fsdaids mko aids njio aids yjkh aids wfdsf aids jio aids nhji aids rwesd aids ewaew rewr r3wrsdf aids mko aids rwqrs aids mkl klp jkp dfsad dsad ewd aids jiop aids ewqe aids erwqe aids dwqd fsd aids fewd aids cdfe fsa dsews aids wedxd aids rwesd fsd fdsre fsdaids mko aids njio aids yjkh aids wfdsf aids jio aids nhji aids rwesd aids rewrsd 3rsf rsr fdsfew deasd jiom rw fsr mop rewrsdd kop cdsfwe kop rwqe jiop ewaew rewr r3wrsdf aids mko aids rwqrs aids mkl klp jkp dfsad dsad ewd aids jiop aids ewqe aids erwqe aids dwqd fsd aids fewd aids cdfe fsa dsews aids wedxd aids rwesd fsd fdsre fsdaids mko aids njio aids yjkh aids wfdsf aids jio aids nhji aids rwesd aids rewrsd 3rsf rsr fdsfew wedsad fsr aids mko aids rwqrs aids mkl klp jkp dfsad dsad ewd aids jiop aids ewqe aids erwqe aids dwqd fsd aids fewd aids cdfe fsa dsews aids wedxd aids rwesd fsd fdsre fsdaids mko aids njio aids yjkh aids wfdsf aids jio aids nhji aids rwesd aids ewaew rewr r3wrsdf aids mko aids rwqrs aids mkl klp jkp dfsad dsad ewd aids jiop aids ewqe aids erwqe aids dwqd fsd aids fewd aids cdfe fsa dsews aids wedxd aids rwesd fsd fdsre fsdaids mko aids njio aids yjkh aids wfdsf aids jio aids nhji aids rwesd aids rewrsd 3rsf rsr fdsfew deasd jiom rw fsr mop rewrsdd kop cdsfwe kop rwqe jiop ewaew rewr r3wrsdf aids mko aids rwqrs aids mkl klp jkp dfsad dsad ewd aids jiop aids ewqe aids erwqe aids dwqd fsd aids fewd aids cdfe fsa dsews aids wedxd aids rwesd fsd fdsre fsdaids mko aids njio aids yjkh aids wfdsf aids jio aids nhji aids rwesd aids rewrsd 3rsf rsr fdsfew aids. From pu at myRealBox.com Sun Oct 20 13:25:56 2002 From: pu at myRealBox.com (pu) Date: Sun, 20 Oct 2002 19:25:56 +0200 Subject: mx.ODBC execute() error 07001 with MsAccess Message-ID: <3db2e655_2@news.vo.lu> Hi all, I am a newcomer to Python and ODBC and I have the following code that misbehaves with mx.ODBC and an MS-ACCESS database: db = mxODBC.connect(DBname) c2 = db.cursor() sqlcmd = "select count(*) from %s where (%s > ? and %s <= ?) and (%s)" % (TBname,TBcol,TBcol,condit) print now()," ...",sqlcmd c2.execute(sqlcmd, (maxnow, maxnow2)) at the execute, I get the following message: 2002/10/20 18:17:59 ... select count(*) from testtb where (key > ? and key <= ? ) and (text="stop") Traceback (most recent call last): File "I:\My Programs\Python\DBListener.py", line 83, in ? db=DBListener(waittime,DBname,TBname,keyCol,condit) File "I:\My Programs\Python\DBListener.py", line 34, in __init__ c2.execute(sqlcmd, (maxnow, maxnow2)) mxODBC.ProgrammingError: ('07001', -3010, '[Microsoft][ODBC Microsoft Access Dri ver] Too few parameters. Expected 3.', 4573) Any ideas? From tjreedy at udel.edu Thu Oct 17 11:26:30 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 17 Oct 2002 11:26:30 -0400 Subject: About Python Syntax References: Message-ID: > The Python's unstructured statements like break, continue, while, if elseif else These *are* structured programming flow control statements. >In my opinion those constructions could replace all Python's compound statements Yes, there are several equivalent ways ways to express the same underlying flow control ideas. You are welcome to design and release a language based on your version. TJR From gerhard.haering at opus-gmbh.net Fri Oct 11 08:58:33 2002 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 11 Oct 2002 12:58:33 GMT Subject: mod_snake WIndows installer, anyone? References: Message-ID: Steve Holden [2002-10-11 12:48 GMT]: > Has anyone compiled mod_snake for Windows? FYI: mod_snake is orphaned now, so unless you plan to hack on it, it probably doesn't make much sense to build it. Quoting http://modsnake.sf.net/ RIP - Mod Snake I no longer have the time or motivation to work on mod_snake, so instead of letting it sit here, I have decided to kill this project. RIP - Mod Snake Jon Travis Last modified: Thu May 9 19:00:01 PDT 2002 mod_python development is currently focused on the Apache 2.x version (mod_python 3.0) and there have been two beta releases of this branch recently, IIRC. -- Gerhard From kdahlhaus at yahoo.com Wed Oct 16 20:00:43 2002 From: kdahlhaus at yahoo.com (Kevin Dahlhausen) Date: 16 Oct 2002 17:00:43 -0700 Subject: RedHat 7.3 Message-ID: <283adf56.0210161600.48b9824b@posting.google.com> I compiled and installed Python 2.2.1, (now compiling 2.2.2) on my Redhat system. That broke some of the RedHat utility programs, as they use very old versions of some xml libraries. It should still work as I've changed the interpreter in the scripts themselves to python1.5. The scripts are kicked off by a compiled binary and I think that may be the problem. So the question is, how do I upgrade my python on a redhat system? I prefer to compile and install it myself. thanks From xx758 at cam.ac.uk Wed Oct 9 08:08:13 2002 From: xx758 at cam.ac.uk (Xiao-Qin Xia) Date: Wed, 09 Oct 2002 13:08:13 +0100 Subject: Simple Regular Expression Needed... References: <88caaeda.0210081328.58d18591@posting.google.com> Message-ID: import re s = """ YOUNG J STRONG 309 1356 1994 FELDMAN DJ WEAK 15 297 1962 Some other stuff """ print re.compile('(?<=)([A-Z]+\s+[A-Z]+\s+(?:STRONG|WEAK)\s+\d+\s+\d+\s+\d+)\s*').findall(s) From alain at onesite.org Sun Oct 20 22:55:12 2002 From: alain at onesite.org (Alain Tesio) Date: Mon, 21 Oct 2002 04:55:12 +0200 Subject: How to get the minor and major device numbers with os.stat ? References: Message-ID: On Mon, 21 Oct 2002 02:46:13 +0000, Grant Edwards wrote: > AFAIK, os.stat() has never returned device number info. > Last time I looked, the posix stat wrapper doesn't do anyting > with the st_rdev field. [Don't know why -- it sure would be > useful sometimes.] Thanks, if anyone if ever looking for a working example : map(lambda h: eval("0x%s" % h),execute('stat -t -c "%%T %%t" %s' % fileName)[0].split()) Alain From bokr at oz.net Wed Oct 16 20:22:23 2002 From: bokr at oz.net (Bengt Richter) Date: 17 Oct 2002 00:22:23 GMT Subject: Most efficient method to search text? References: <886c5e4b.0210151635.123359bb@posting.google.com> Message-ID: On Wed, 16 Oct 2002 13:35:09 GMT, Michael Hudson wrote: >robin.siebler at corp.palm.com (Robin Siebler) writes: > >> I wrote a script to search a slew of files for certain words and >> names. However, I am sure that there has to be a faster/better way to >> do it. > >I should point out that I'm not really replying in order to help you >-- if I do, that's a bonus. I've actually wanted to sit down and >write this code out for a while, and this seemed like a good excuse. > >Here's a way to quickly (I hope! Haven't done any benchmarks) tell if >one of a bunch of words is contained in a chunk of text, assuming the >words are known beforehand: > >import string > >wordchars = string.letters >allchars = map(chr, range(256)) >hittoken = 'hit' > >def _compile(wordlist, d, skipalong): > t = {} > for word in wordlist: > t.setdefault(word[0], []).append(word[1:]) > for k, v in t.iteritems(): > d[k] = {} > if '' in v: > for c in allchars: > d[k][c] = hittoken > for c in wordchars: > d[k][c] = skipalong > else: > for c in allchars: > d[k][c] = skipalong > _compile([y for y in v if y <> ''], d[k], skipalong) > >def compile(wordlist): > root = {} > skipalong = {} > for c in allchars: > skipalong[c] = root > for c in wordchars: > skipalong[c] = skipalong > for c in allchars: > root[c] = root > _compile(wordlist, root, skipalong) > return root > >def match(set, text): > _hittoken = hittoken > for c in text + '\000': > set = set[c] > if set is _hittoken: > return 1 > else: > return 0 > >You probably don't want to try and print the kind of things compile() >returns... > >I don't really feel like explaining it, either, but it shouldn't be >too hard to grasp the principles if you've heard of a dfa. > >You use it like this: > >>>> set = robin.compile(['Tim', 'Guido', 'Barry']) >>>> files = glob.glob(os.path.expanduser("~/src/python/dist/src/Lib/*.py")) >>>> for file in files: >... if robin.match(s, open(file).read()): >... print os.path.basename(file) >... >cgi.py >doctest.py >getpass.py >gettext.py >imputil.py >profile.py >pstats.py >pty.py >pydoc.py >random.py >rfc822.py >site.py >smtpd.py >tabnanny.py >telnetlib.py >threading.py >tokenize.py >whrandom.py >xmlrpclib.py >sets.py >heapq.py >>>> > >There are surely cleverer Boyer-Moore tricks you can pull, but I >personally think this code is really really neat. You should be able >to write lexers very like this (though not full-on regexps -- >backtracking ain't gonna fit, here). > That's pretty cool, but for just finding words I just thought of an alternative has_word, I think ;-) Given a wordlist and string to search, the wordsearch part could be a long one liner, but I think this is a little clearer ;-) Don't know about the timing: No guarantees... #!/usr/bin/python # __PyPAN_Py has_word.py -- searches string and returns words found of given list # # May also be run at command line to search for words in globbed files: # Usage: python has_word.py [word]+ -- [fileglob]+' # def has_word( wordlist, # 'word' or ['word', 'word2', 'etc'] aString, # string to find words in trans = ''.join([c.isalnum() and c or ' ' for c in map(chr,range(256))]) ): """ Search for any of a list of words in a string and return list of words found. """ if isinstance(wordlist, str): wordlist = [wordlist] # allow single word for convenience string_words = dict( map(None, aString.translate(trans).split(),[])) return [w for w in wordlist if w in string_words] # and 1 or 0 for bool return if __name__ == '__main__': import sys, os, glob try: eow = sys.argv.index('--') words = sys.argv[1:eow] if eow<0 or not words: raise ValueError globs = sys.argv[eow+1:] for g in globs: files = glob.glob(g) # "~/src/python/dist/src/Lib/*.py")) for filename in files: found = has_word(words, file(filename).read()) if found: print '%16s: %s' % (os.path.basename(filename), found) except: print 'Usage: python has_word.py [word]+ -- [fileglob]+' # __PyPAN__ Which may be used like: [17:07] C:\pywk\ut>python has_word.py Tim Guido Barry Michael -- d:\python22\lib\*.py cgi.py: ['Guido', 'Michael'] doctest.py: ['Tim'] getpass.py: ['Guido'] gettext.py: ['Barry'] imputil.py: ['Tim', 'Guido'] profile.py: ['Guido'] pstats.py: ['Guido'] pty.py: ['Guido'] pydoc.py: ['Guido'] random.py: ['Tim', 'Guido'] rfc822.py: ['Guido'] site.py: ['Guido'] smtpd.py: ['Barry'] tabnanny.py: ['Tim'] telnetlib.py: ['Guido'] threading.py: ['Tim'] tokenize.py: ['Tim'] whrandom.py: ['Guido'] Regards, Bengt Richter From fredrik at pythonware.com Sun Oct 13 07:22:36 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 13 Oct 2002 11:22:36 GMT Subject: Swedish characters in Python strings References: <7d546104.0210120944.17486548@posting.google.com> Message-ID: <0Icq9.2091$MV.88372@newsc.telia.net> Urban Anjar wrote: > That is perfectly OK, but... > > >>> S = '???' > >>> print S > ??? > >>> print len(S) > 6 on all machines I have access to, I get: >>> S = "???" >>> print S ??? >>> print len(S) 3 check the locale settings; to minimize the pain, make sure you use an 8-bit encoding (e.g ISO-8859-1) and not a designed-for-internal- use-only variable-width encoding like UTF-8. with UTF-8, your operating system is messing things up before Python gets a chance to look at the characters (most likely, Python gets 6 characters from the keyboard, and sends 6 characters to the console). if you cannot get RedHat to behave intelligentely, use a decent editor instead. (avoiding RedHat 8.0 might also help. based on the kind of bugs I've experienced this far, 8.0 might qualify as the worst unix-like operating system ever released...) From grante at visi.com Wed Oct 16 22:37:18 2002 From: grante at visi.com (Grant Edwards) Date: Thu, 17 Oct 2002 02:37:18 GMT Subject: Question about output... References: Message-ID: In article , Dave Cole wrote: >Tony> cout << "The average of " << firstInt << " and " << secondInt << >Tony> " is " << average << endl; >>>> firstInt = 10 >>>> secondInt = 20 >>>> average = (firstInt + secondInt) / 2 >>>> print 'The average of', firstInt, 'and', secondInt, 'is', average > The average of 10 and 20 is 15 Or sys.stdout.write("The average of %d and %d is %d\n" % (firstInt, secondInt, average) The format operator "%" provides more control over how operands are formatted. The format string works just like C. -- Grant Edwards grante at visi.com From gerhard.haering at gmx.de Thu Oct 10 12:21:19 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 10 Oct 2002 16:21:19 GMT Subject: Concrete classes -- stylistic question References: Message-ID: Andrew Koenig wrote in comp.lang.python: > On a few occasions I've wanted to define ``concrete classes'' -- > classes that are so simple that their structure is their interface. > For example, I might want a little class to hold (x, y) pairs. > > Of course, I can use a tuple, but then I have to remember the meaning > of each element. Moreover, if I want to have (x, y) pairs and (r, theta) > pairs, I don't have an easy way of checking which one is which in case > I use the wrong one by accident. > [...] > My questions: > > 1) Am I reinventing the wheel here? If so, where is the original? Check out Alex Martelli's 'bunch' recipe: 'The simple but handy "collector of a bunch of named stuff" class' http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52308 -- Gerhard From pedronis at bluewin.ch Mon Oct 21 10:48:50 2002 From: pedronis at bluewin.ch (Samuele Pedroni) Date: Mon, 21 Oct 2002 16:48:50 +0200 Subject: Mitch Kapor's open source PIM to use wxPython Message-ID: <3db415ab_4@news.bluewin.ch> Jon Udell commenting: http://weblog.infoworld.com/udell/2002/10/21.html#a475 . From pinard at iro.umontreal.ca Thu Oct 10 10:06:29 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: Thu, 10 Oct 2002 10:06:29 -0400 Subject: No tabs in post PLEASE!!! (was Re: partial list sort) In-Reply-To: <2Rep9.19819$ne4.8631@fe05> ("Steve Holden"'s message of "Thu, 10 Oct 2002 08:58:22 -0400") References: <20021009094141.GA852@jsaul.de> <2Rep9.19819$ne4.8631@fe05> Message-ID: [Steve Holden] > "Daniel T." >> Alex Martelli wrote: >> > Terry Reedy wrote: >> > ... >> > > Tabs are bad for Usenet posting if you want stupid people like me who >> > > use Outlook Express to read posted code. >> > >> > Seconded! They're almost as bad for (expletive deleted) people like ME, >> > who use KDE's KNode (0.6.1 with KDE 2.2.2 at least, haven't tried more >> > recent versions yet). >> > >> > PLEASE folks, even if you're tabs-maniacs, make SURE you turn them >> > into spaces when posting or mailing your sources...!!! >> >> You have got to be kidding... > > Well, that all depends whether you want readers to be able to see the code > as you wrote it rather than the code as mangled by whatever gets in the way > between your fingers and their eyeballs. There is some common sense that people often forget when we come to these things. These pop up recurrently, all over, in a variety of flavours. Deep down, it all depends where the mangling occurs. If at the originator site, then it is the originator's responsibility to correct the problem. But when the mangling occurs at the recipient's site, this is clearly the recipient's responsibility to get or use some sensible software. I've seen a constant push, for years, by recipients using broken software, asking the whole planet to be polite and help them cope with their brokenedness. That push should be considered unwelcome, and politeness is misplaced here. This is really the base principle. The problem is tinily more concentrated now around deciding whether a message in transit is broken or not. _This_ might be a religious issue. Should messages in transit have TABs or not? For one, I surely do not have a firm, definitive opinion. The fact that many terminals and applications automatically define TAB at multiples of 8 columns does not necessarily make it universal. MIME (or whatever) does not have a way to describe what is the meaning of a TAB in the incoming text. So I guess that on the ground of global cooperation, TABs are better avoided in fluent text. Without any kind of dependable clue about their meaning, TABs should be transported unaltered by transmission agents. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From mgarcia at cole-switches.com Fri Oct 11 14:20:29 2002 From: mgarcia at cole-switches.com (Manuel M. Garcia) Date: Fri, 11 Oct 2002 18:20:29 GMT Subject: hashability question References: Message-ID: <3a5equk4o9oi7h72aos0757empa7sl7073@4ax.com> On Fri, 11 Oct 2002 16:37:23 +0100, Gon?alo Rodrigues wrote: >def __hash__(self): > return hash(self.__time) This is the perfect way to do it. You are relying on the built in hash() function, and because it is used in every Python dictionary, it is optimized to be fast with no trivial pathological behavior. From see_reply_address at something.invalid Tue Oct 15 18:01:06 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Wed, 16 Oct 2002 11:01:06 +1300 Subject: Howto generate a metafunction? [Python 1.5.2] References: <3DAC490C.6080009@kyborg.dk> Message-ID: <3DAC9022.7080109@something.invalid> Kim Petersen wrote: > > class MListbox(Frame): > def __init__(self,master,count=1,cnf={},**args): > Frame.__init__(self,master,cnf) > self.listboxes=[] > for i in range(count): > self.listboxes.append(Listbox(self,command=self._docommand)) > self.listboxes[-1].grid(row=0,column=i) > self.yview=self.Metafun(Listbox.yview) > self.yview_fraction=self.Metafun(Listbox.yview_fraction) > ... > > def Metafun(self,fun): > # How do i generate this one - to apply this function to every > # element in self.listboxes? It looks like you're trying to synchronise the scrolling of several listboxes, right? When I needed to do this a while ago, I created the following class: class ScrollMultiplexer: def __init__(self): self.clients = [] def add(self, c): self.clients.append(c) def xview(self, *args): for c in self.clients: apply(c.xview, args) def yview(self, *args): for c in self.clients: apply(c.yview, args) You would use it like this: class MListbox(Frame): def __init__(self,master,count=1,cnf={},**args): Frame.__init__(self,master,cnf) ... # Create a ScrollMultiplexer mux = ScrollMultiplexer() # Create a scroll bar and connect it to the ScrollMultiplexer scrollbar = Scrollbar(self, orient = 'v', command = mux.yview) ... for i in range(count): listbox = Listbox(self,command=self._docommand) self.listboxes.append(listbox) # Add the listbox to the ScrollMultiplexer mux.add(listbox) ... # Finally, connect *one* of the listboxes back to the scroll bar # (it doesn't matter which one) self.listboxes[0].configure(yscrollcommand = self.scrollbar.set) In other words, the ScrollMultiplexer sits in between the scrollbar and the listboxes, pretending to be a sort of fake listbox, distributing the scrolling commands from the scrollbar to all the real listboxes. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From k.robert at gmx.de Mon Oct 7 09:26:48 2002 From: k.robert at gmx.de (Robert) Date: Mon, 7 Oct 2002 15:26:48 +0200 Subject: Searching Python Manuals References: Message-ID: <3da18bff$0$153$9b622d9e@news.freenet.de> there is a standard windows HTML help file (.CHM) for the wohle python doc. index, search, ... search for 'pythlp.chm' or so. pywin doc is already in .CHM format by default now. robert "Matt Gerrans" schrieb im Newsbeitrag news:anoikq$u6v$1 at slb2.atl.mindspring.net... > Is there some way to to search the Python manuals, other than grepping > through all the html files? I use ActiveState's help file on the Windows > platform for this purpose, but it only seems to work on certain platforms > (;-). > > From pinard at iro.umontreal.ca Tue Oct 15 15:49:02 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: Tue, 15 Oct 2002 15:49:02 -0400 Subject: International APPs / pygettext In-Reply-To: <3DAC5E22.1060102@web.de> (Ingo Linkweiler's message of "Tue, 15 Oct 2002 20:27:46 +0200") References: <3DAC5E22.1060102@web.de> Message-ID: [Ingo Linkweiler] > The download-link to (http://www.iro.umontreal.ca/contrib/po-utils/HTML/) > ist down since several days. Oh, I did not use free time to look at that site in a good while. Should find some. In any case, the `xpot' utility has not been revised to account for Unicode in Python, so for many applications, it might not be usable. > What do I need to edit the ".mo" files? `.mo' files are created by the `msgfmt' utility (part of the GNU `gettext' distribution) out of `.po' files, and those are edited by users. In case you are an Emacs user, I once wrote an Emacs mode for editing such PO files. That mode is now distributed with GNU `gettext' and maintained by Bruno Haible, best is to disregard the copy in `po-utils' on the `iro' site above. I also read, yesterday, that PO mode might become part of standard Emacs -- yet I'm not fully sure it will happen for real, some dislike the idea. You can also use `vi' to edit PO files, provided you do it with a lot of attention, as `vi' will not much help you at avoiding errors. I've heard of other specialised tools coming out of KDE or Gnome projects, one might guess they could be comfortable, but I cannot really comment on them, as I did not try these tools. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From ishambat at aol.com Mon Oct 21 15:41:27 2002 From: ishambat at aol.com (Ilya Shambat) Date: 21 Oct 2002 12:41:27 -0700 Subject: Parsing SGML document in Python program References: Message-ID: Eric Brunel wrote in message news:... > Ilya Shambat wrote: > > > Hello all, > > > > I need to be able to parse an SGML document in a Python program. I > > need to know the syntax on how to do that. The project involves using > > a DTD, passed as a command line argument, to read all the SGML files > > that exist in a directory. Does anybody know how this is done? > > There is a sgmllib module in the standard library, but it's not a full SGML > parser. SGML has a lot of funky possibilities that are quite hard to parse > and that were apparently not considered in the sgmllib module. I never used > it, but as far as I can see from the docs, it doesn't use a DTD, so it's > really not a SGML parser (XML seems to live well without a DTD, but doing > so in SGML may be considered as heretic ;-). It may however be usable if > your documents are really simple. > > I had once to do that and I couldn't find a parser directly usable in > Python. Maybe it has changed (just check the Vaults of Parnassus for it). > The solution I used at the time was to rely on an external parser that gave > easy to parse results. The one I used was nsgmls, part of James Clark's SP > project. You may find it @ http://www.jclark.com/sp/ ; just test it and > you'll see that its output is really easy to get back into Python. I have looked at the documentation for nsgmls, and I found it rather inadequate. Is it possible for anyone to post an example of how this is done? Any help on this would be greatly appreciated. From jb at yahoo.de Fri Oct 11 11:17:08 2002 From: jb at yahoo.de (JB) Date: Fri, 11 Oct 2002 17:17:08 +0200 Subject: Getting the line where an exception is raised References: <3da46065_4@news.newsgroups.com> Message-ID: <3da6e952_6@news.newsgroups.com> Steve Holden wrote: Thank you vey much, but your suggestion does not really help. Here is my code: try: exec tmp in user_name_space except: txt = str(sys.exc_info()[1]) i = traceback.tb_lineno(sys.exc_info()[2]) print '*',txt,'*',i,'*' mw.widget.text.eingabe.setCursorPosition(i,0) mw.widget.text.ausgabe.setReadOnly(0) mw.widget.text.ausgabe.setText(' '+txt+'') mw.widget.text.ausgabe.setReadOnly(1) (I use PyQt.) Now I always receive the line number 41 from traceback.tb_lineno(sys.exc_info()[2]), as the exec statement happens to be in the 41th line of my code. But the error message say somthig like "syntax error in (line 11)" and /this/ line number is ok. (tmp contains several lines of code.) -- J.... B.... -----------== Posted via Newsfeed.Com - Uncensored Usenet News ==---------- http://www.newsfeed.com The #1 Newsgroup Service in the World! -----= Over 100,000 Newsgroups - Unlimited Fast Downloads - 19 Servers =----- From wlfraed at ix.netcom.com Fri Oct 18 21:42:38 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Fri, 18 Oct 2002 18:42:38 -0700 Subject: Python's driving me mad. Invalid token? References: <5f30c71b.0210172237.28a4f847@posting.google.com> Message-ID: Jim fed this fish to the penguins on Thursday 17 October 2002 11:37 pm: > > destFile = open((dirname+"""\"""+name),'w') Very simple problem if you look at it in a syntax color-coded editor. I just loaded the file in vi under Linux and the coloring showed it right off... Mismatched " marker... \" is an escape character, the tokens are: """ \" "" <= it sees two ", so the opening triple " is still open! -- -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < From dougfort at dougfort.net Tue Oct 15 07:02:00 2002 From: dougfort at dougfort.net (dougfort) Date: Tue, 15 Oct 2002 04:02:00 -0700 (PDT) Subject: Subclassing FixedPoint Message-ID: <20021015040200.27582.h002.c001.wm@mail.dougfort.net.criticalpath.net> On Tue, 15 Oct 2002, paul at nlhas.no wrote: > > Can anyone explain why the following fails when using the subclass > (recursion problem), but work using the base class? > > It worked with the last "pre-Sourceforge" version of FixedPoint, so I > presume this might be a bug in the latest version -- I just can't for > the life of me see what could cause this! > > pm I presume it's a bug too. I'm tied up with my day job right now. I'll look into it when I get the chance. I fear it's related to the use of __slots__, which I threw in just because it sounded cool. You might want to report an official bug at the SourceForge site: that leaves less chance of it slipping through the cracks. Doug Fort http://www.dougfort.net From vincem at en.com Fri Oct 4 06:26:52 2002 From: vincem at en.com (Vincent Marchetti) Date: Fri, 04 Oct 2002 10:26:52 GMT Subject: missing methods or __getattr__ problem References: Message-ID: In article , "Uwe C. Schroeder" wrote: > > Hi, > > I'm a little stuck here and my brain turns in circles. > Here's what I'm trying to accomplish and I'm sure there is a very > simple solution to this problem: > > The caller calles a method xx.callme(objecttype, parameters) > The called object keeps a list of class instances where the > paricularly wanted object can be found via the "objecttype" > parameter. However the called object itself doesn't have the called > attribute. What I'm looking for is a way to transparently call a > method as if it was part of the called object. So the called object > has to do the following: > 1. figure out if the called attribute is a member of itself > 2. if not 1. take the first parameter and look up the object in > which the wanted method resides > 3. call the (hopefully found) method and return the results. > I think the solution here is to use a two step process in performing the call, using an intermediate Python object to store the name of the method. [Credit where credit is due -- I learned this pattern from the aetypes module in the Mac Python distribution] --- Example pseudo-python class methodNameStorer: def __init__(self,name): self.myMethod = name def __call__(self, objToCall,arguments): # see Python "Ref" Sec 3.3.4 MethToCall = objToCall.__getattr__(self.myMethod) # now we have both the called object (objToCall) and arguments, can # do any logging desired MethToCall(arguments) # finally! #then, using naming from your example class bng: def __getattr__(self, attr): if ({attr is a valid method name}): return methodNameStorer(attr) raise AttributeError Vince Marchetti From thorsten at thorstenkampe.de Fri Oct 18 18:28:55 2002 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sat, 19 Oct 2002 00:28:55 +0200 Subject: dict1 < dict2 <=> len(dict1) <= len(dict2) ? References: Message-ID: * Tim Peters > [Thorsten Kampe] >> does anyone know what "dict1 < dict2" tests? [...] >> I think it's equivalent to "len(dict1) <= len(dict2)", but I could >> be wrong. > > Partly. len(d1) < len(d2) implies d1 < d2 in recent Python releases, > but it's much more complicated if len(d1) == len(d2). [...] > It's too tedious to explain the full truth here, and it doesn't > matter (if you think it does, you're writing code nobody will > understand!). Of course I didn't understand everything you said, but in my case it doesn't matter. I just wanted to make sure that this code snippet (see above) does what I hoped it would. And with the "#" comment I hope no one will accuse me of writing perlish Python ;-) #v+ if dict0 > dict1: # loop through the shorter dict dict0, dict1 = dict1, dict0 for item in dict0: #v- Thorsten From noah at noah.org Fri Oct 18 11:34:56 2002 From: noah at noah.org (Noah) Date: 18 Oct 2002 08:34:56 -0700 Subject: What does __all__ do in a package? Message-ID: I'm designing a module. I want to make sure that I am using __all__ properly. This is how I understand the __all__ variable -- Someone please tell me if I am wrong or right: __all__ is a list of strings that limit what is exported by a package when you use: from MyPackage import * (Kind of reminds me of extern in C++) Does __all__ also limit what is visible if I reference the package by name? For example: import MyPackage print MyPackage.my_variable_not_listed_in__all__ Yours, Noah From lamb100 at korea.com Mon Oct 21 23:25:23 2002 From: lamb100 at korea.com (Seunghyun Kim) Date: 21 Oct 2002 20:25:23 -0700 Subject: How to use xmlrpc properly with Korean (non-ascii characters) Message-ID: <926d3924.0210211925.611dafe6@posting.google.com> Hi. Recently I tried xmlrpc to support Korean. In newsgroup, there are many complaint to xmlrpc from non-english, because it formally supports just ASCII. Here is solution for Korean Language support. I guess it would be properly adopted to other languages. -- First of all, you have to get xmlrpclib 0.9.9 from pythonware, and install it to your $PYTHON_PATH$/lib. surely overwrite previous files. Then open xmlrpclib.py with text editor and modify it. 1. insert "import codecs" from ------------------------------------ import re, string, time, operator import urllib, xmllib from types import * from cgi import escape ------------------------------------ to ------------------------------------ import re, string, time, operator import urllib, xmllib import codecs # codecs from types import * from cgi import escape ------------------------------------- 2. modify _decode() method from ---------------------------------------------------------------------- def _decode(data, encoding, is8bit=re.compile("[\x80-\xff]").search): # decode non-ascii string (if possible) if unicode and is8bit(data): data = unicode(data, encoding) return data ----------------------------------------------------------------------- to ----------------------------------------------------------------------- def _decode(data, encoding, is8bit=re.compile("[\x80-\xff]").search): # decode non-ascii string (if possible) if unicode and is8bit(data): UTF8_encode = codecs.lookup('UTF-8')[0] # set UTF8 codec data = UTF8_encode(unicode(data, 'mbcs'))[0] return data ------------------------------------------------------------------------ When string include non-ascii Korean characters, it is encoded with 'EUC-KR' automatically from web server. So, Client should converted it to 'UTF-8' type which Python can cope with skillfully. I think this approach could be adopted to other languages. Any comment will be appreciated. -- Sola Pro Christo From shalehperry at attbi.com Thu Oct 17 10:52:16 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Thu, 17 Oct 2002 07:52:16 -0700 Subject: newbie, dir tree parsing In-Reply-To: <3DAE98BB.3000801@shaw.ca> References: <3DAE98BB.3000801@shaw.ca> Message-ID: <200210170752.16146.shalehperry@attbi.com> On Thursday 17 October 2002 03:59, Jaqui wrote: > new to python, need to make an app to completely scan the computer for a > specific directory, take that path and insert it into a python script > for another application to use. > I know the python mods to look at and work with to get the path data, > but how to insert into another script ( opened by the app to do so )? > > literally need to pull *\poser\runtime\python where the * is the > absolute path to the specified directory. > then put the absolute path into a script opened by the app so that the > app poser can make use of the script. poser's python interpreter > requires an absolute path. > you open the file, write the line, close the file. fp = open(path, 'w') fp.write(data) fp.close() From BartolomeSintes at ono.com Thu Oct 17 16:28:23 2002 From: BartolomeSintes at ono.com (Bartolomé Sintes Marco) Date: Thu, 17 Oct 2002 20:28:23 GMT Subject: Non-ascii characters in an MSDOS window Message-ID: Hi, I am using Python 2.2.2 for Windows in a computer with a Spanish Windows 98 SE operating system. I have written the following program (sample.py) print "Spanish accents: ? ? ? ? ?" end = raw_input() If I run this program in IDLE (Ctrl+F5), Python writes the accents correctly, but if I double-click the sample.py file, an MS-DOS window opens and wrong symbols are written. I have tried to use sys.setdefaultencoding() in sitecustomize.py file, but I always get the same wrong characters in the MSDOS Windows no matter which encoding I use. Is there an easy way to make Python write the same characters in a MSDOS window than in IDLE? Thanking you in advance, Barto From marklists at mceahern.com Wed Oct 2 11:52:50 2002 From: marklists at mceahern.com (Mark McEahern) Date: Wed, 2 Oct 2002 10:52:50 -0500 Subject: bug/poor tracebacks while importing code In-Reply-To: Message-ID: [Robin Becker] > Is there some reason why we have poor code inspection during imports. Is it just me or does your attitude stink? Anyway, try this instead: traceback.print_stack() Cheers, // m From ykingma at accessforall.nl Sat Oct 5 08:27:24 2002 From: ykingma at accessforall.nl (Ype Kingma) Date: Sat, 05 Oct 2002 14:27:24 +0200 Subject: Simple lru cache? References: <3d9dfe86$0$124$e4fe514c@dreader6.news.xs4all.nl> Message-ID: <3d9ed9cc$0$124$e4fe514c@dreader5.news.xs4all.nl> Alex, > > One that I haven't seen is based on dictionaries -- may not be > best, but it's interesting, at least (it's somewhat of a > surprise that a dict is often the best way to implement a > FIFO queue in Python, for example -- now this case is a bit > different, but...). > > Say that what we want is to be able to access the X LRU items > (e.g. to remove them) and that items are hashable. Then: > > oldest = newest = 0 > item_to_age = {} > age_to_item = {} > > def use_item(IT): > newest += 1 > item_to_age[IT] = newest > age_to_item[newest] = IT > > def prune_X_items(X): > pruned = 0 > while pruned < X and oldest < newest: > oldest += 1 > IT = age_to_item.get(oldest) > if IT is not None: > del age_to_item[oldest] > del item_to_age[IT] > pruned += 1 > > Now the computational cost of "use_item" is pretty darn > close to O(1) [thanks to the performance characteristics > of Python's dicts] -- although it's harder to estimate > the computational cost of "prune_X_items", as it depends > on how much "churning" there has been (I'd guess it's > probably no good if older items are OFTEN 'used' again). I'd expect in the order of 10000 items cached of which: 20% would be used around 4 times, 20% around 3 times, 20% around 2 times, 40% used once only. I also realized that not all items take the same time to fetch from the database, 10 msec is avarage, but I've seen anything from close to 0 (hitting another cache) to 100 msecs. Needless to say that these slow outliers would be most helpfull in the cache. And off course the access pattern changes ao. by using the cache, so access times will also change. With your suggestion I now have 3 basic implementations (doubly linked list, python list, FIFO by counters in dictionaries) to try in practice. I'd normally go for the simplest one first, but they hardly differ in simplicity, so it's difficult to choose. Thanks, Ype From ajm_NO_REPLY_ at zanthan.com Tue Oct 8 22:10:52 2002 From: ajm_NO_REPLY_ at zanthan.com (Alex Moffat) Date: Wed, 09 Oct 2002 02:10:52 GMT Subject: How to restrict settable attributes for an object? Message-ID: What I want to do is restrict the attributes that can be set on an object. I want to do this for "data objects" so that I can catch typing errors in my program and more easily manage sql interfacing. My current "solution" is pasted below. Is there a better technique that I should use. I'm new to python so I'd like to try and follow the established idioms and patterns where they exist. In a file DataObject.py I have def defAllowedAttributes(clazz, attrList): """Define the attributes that are allowed for objects of a class. This consists of those passed in as attrList as any that are defined for superclasses of clazz.""" allowedAttrs = {} for a in attrList: allowedAttrs[a] = None for c in clazz.__bases__: allowedAttrsName = "_%s__allowedAttrs" % c.__name__ for a in getattr(c, allowedAttrsName): allowedAttrs[a] = None allowedAttrsName = "_%s__allowedAttrs" % clazz.__name__ setattr(clazz, allowedAttrsName, allowedAttrs) class DataObject: """A base class for objects with a restricted set of attributes.""" def _isAllowed(self, a): allowedAttrsName = "_%s__allowedAttrs" % self.__class__.__name__ if a in getattr(self.__class__, allowedAttrsName): return 1 else: return 0 def __setattr__(self, name, value): """only set values for allowed attributes""" if self._isAllowed(name): self.__dict__[name] = value else: raise AttributeError, \ "%s instance allows no attribute '%s'" % \ (self.__class__.__name__, name) def __getattr__(self, name): """if name is an allowed attribute then return None""" if self._isAllowed(name): return None else: raise AttributeError, \ "%s instance allows no attribute '%s'" % \ (self.__class__.__name__, name) # Set up DataObject with an initially empty set defAllowedAttributes(DataObject, []) In a file called TestDataObject.py import DataObject class A(DataObject.DataObject): pass DataObject.defAllowedAttributes(A, ("a", "b")) class B(A): pass DataObject.defAllowedAttributes(B, ("c", "d")) if __name__ == "__main__": a = A() a.a = "1" a.b = "2" try: a.c = "3" except AttributeError, ar: pass b = B() b.a = "1" b.b = "2" b.c = "3" b.d = "4" try: a.e = "5" except AttributeError, ar: pass From bobx at linuxmail.org Wed Oct 9 06:05:38 2002 From: bobx at linuxmail.org (Bob X) Date: Wed, 09 Oct 2002 10:05:38 GMT Subject: appending to beginning of line References: <1001ff04.0210080422.1e373e13@posting.google.com> Message-ID: Anna wrote: >> for badword in kw: >> if line.find(... >> found = '... >> print found # Print the result > > > else: > print "-" # no bad word so print a placeholder > > >> outFile.write(found) # Write the result > > > This is a question, rather than a suggestion. > > Please don't flame if I've missed something completely obvious to the > experienced folks here. Any simple explanations of why this is unworkable > would be welcome. Thank you. > > Anna Hey Anna, I am a serious newbie as well. I believe (though) I would have to test that all I would get is the hyphen and not a hypen plus the line. I can play with that and see. I don't flame. : ) From hst at empolis.co.uk Thu Oct 31 11:51:41 2002 From: hst at empolis.co.uk (Harvey Thomas) Date: Thu, 31 Oct 2002 16:51:41 -0000 Subject: Overcoming regex memory limits? Message-ID: <8FC4E7C302A6A64AAD5DB1FA0E825DEB04F42F@hendrix.empolisuk.com> It's best to avoid .*? whenever you can as, as you have found, it is defeated with long runs of matching text. Often you can use a negated character class. This is both faster and doesn't fail on long runs of matches. for example instead of '<(.*?)>' use '<([^>]*>'. Where negated character classes aren't sufficient, other more complex expressions can be used, but it's difficult to generalise. Could you post a sample of what you are trying to match? Jeffrey Friedl's "Mastering Regular Expressions" 2nd edition is an excellent book on the subject. > -----Original Message----- > From: Yin [mailto:yin_12180 at yahoo.com] > Sent: 31 October 2002 15:28 > To: python-list at python.org > Subject: Overcoming regex memory limits? > > > I am using python to parse a large text file. I am using the (.*?) > construct in regular expressions to do matching. Unfortunately, I > exceed the limit for the match size in this regular expression due to > an overflow of the stack. > > I've heard that it may be possible to match without using the (.*?) > construct and this may solve the problem. Any suggestions short of a > rewriting the parsing routine would be appreciated. > > Thanks in advance. > Yin > -- > http://mail.python.org/mailman/listinfo/python-list > > _____________________________________________________________________ > This message has been checked for all known viruses by Star Internet > delivered through the MessageLabs Virus Scanning Service. For further > information visit http://www.star.net.uk/stats.asp or > alternatively call > Star Internet for details on the Virus Scanning Service. > _____________________________________________________________________ This message has been checked for all known viruses by the MessageLabs Virus Scanning Service. From jaroslav_gresula at elixir.com Sun Oct 6 10:47:40 2002 From: jaroslav_gresula at elixir.com (Jarda Gresula) Date: Sun, 06 Oct 2002 14:47:40 GMT Subject: Which Linux distribution? References: <3da0412a@post.newsfeed.com> Message-ID: <3da0499b@post.newsfeed.com> *** post for FREE via your newsreader at post.newsfeed.com *** Please ignore this - this is my previous post that I resent by mistake. -----= Posted via Newsfeed.Com, Uncensored Usenet News =----- http://www.newsfeed.com - The #1 Newsgroup Service in the World! -----== 100,000 Groups! - 19 Servers! - Unlimited Download! =----- From =?iso-8859-5?Q?=DF=D5=DD=D3=E3=D8=DD=D8=E1=E2=D0?= at =?iso-8859-5?Q?=DC=D0=D8=DB?=.=?iso-8859-5?Q?=DD=D5=E2?=.=?iso-8859-5?Q?=DC=DA?= Thu Oct 17 18:29:16 2002 From: =?iso-8859-5?Q?=DF=D5=DD=D3=E3=D8=DD=D8=E1=E2=D0?= at =?iso-8859-5?Q?=DC=D0=D8=DB?=.=?iso-8859-5?Q?=DD=D5=E2?=.=?iso-8859-5?Q?=DC=DA?= (=?iso-8859-5?Q?=B4=D0=DC=F8=D0=DD_=B3=2E?=) Date: Fri, 18 Oct 2002 00:29:16 +0200 Subject: fork() and wait() References: Message-ID: <3daf39bb$1@news.mt.net.mk> > It appears that this code works, but I am concerned about the timing. > In the main loop, I am concerned that a job would finish before the > os.wait() call. I didn't look to much at your code, but it doesn't matter if your child exits before the os.wait() call is executed. In such a case the proccess of the child will be put in "Zombie" state, until the wait() call is executed. You can try this by deliberarely postponing the os.wait() call, and using "ps xf" to see what happens with the child processes. -- ?????? A: Because it reverses the logical flow of converstion. Q: Why is top posting frowned upon? From p41600 at hotmail.com Tue Oct 29 16:59:43 2002 From: p41600 at hotmail.com (p 4) Date: Tue, 29 Oct 2002 16:59:43 -0500 Subject: converting text file to csv Message-ID: Hi, I am new to Python and want to knwo the best way to convert the following file: to the one at the bottom (CSV file) Attached is a copy of the sample. Thanks Header1 zxc sadf sdaf asdf OCT25 09:00:00 61000 sdfgj ashsa asdkj Header1 cont Header1 cont Header 1 cont Data_Type1 Key name Tx num1 num2 Value1 value2 value3 value4 value5 value6 Value11 value12 value13 value14 value15 value16 Value33 12 sensor_1 2x 99 56 0 0 0 0 0 0 0 0 0 0 0 0 0 80 sensor_x 2m 60 190 0 0 0 0 0 0 0 0 0 0 0 0 0 58 sensor_y 2W 102 309 0 0 0 0 0 0 0 0 0 0 0 0 0 ... ... Data_Type2 Key Valu41 valu42 valu43 valu44 valu55 valu56 Value71 value82 value93 12 0 0 0 0 0 0 0 0 0 ... ... Data_Type3 Key Valu41 valu42 valu43 valu44 valu55 valu56 Value71 value82 value93 value32 value97 50 0 0 0 0 0 0 0 0 0 0 0 90 0 0 0 0 0 0 0 0 0 0 0 51 0 0 0 0 0 0 0 0 0 0 0 14 0 0 0 0 0 0 0 0 0 0 0 ... ... Header1 zxc sadf sdaf asdf OCT25 09:00:00 61000 sdfgj ashsa asdkj Header1 cont Header1 cont Header 1 cont Data_Type1 Key name Tx num1 num2 Value1 value2 value3 value4 value5 value6 Value11 value12 value13 value14 value15 value16 Value33 12 sensor_1 2x 99 56 0 0 0 0 0 0 0 0 0 0 0 0 0 80 sensor_x 2m 60 190 0 0 0 0 0 0 0 0 0 0 0 0 0 58 sensor_y 2W 102 309 0 0 0 0 0 0 0 0 0 0 0 0 0 ... ... Data_Type2 Key Valu41 valu42 valu43 valu44 valu55 valu56 Value71 value82 value93 12 0 0 0 0 0 0 0 0 0 ... ... Data_Type3 Key Valu41 valu42 valu43 valu44 valu55 valu56 Value71 value82 value93 value32 value97 50 0 0 0 0 0 0 0 0 0 0 0 90 0 0 0 0 0 0 0 0 0 0 0 51 0 0 0 0 0 0 0 0 0 0 0 14 0 0 0 0 0 0 0 0 0 0 0 ... ... and it needs to be converted to: Header1,zxc,sadf,sdaf,asdf,OCT25,09:00:00,61000,sdfgj,ashsa,asdkj,Header1,cont,Header1,cont,Header,1,cont Data_Type1 Key,name,Tx,num1,num2,Value1,value2,value3,value4,value5,value6,Value11,value12,value13,value14,value15,value16,Value33 12,sensor_1,2x,99,56,0,0,0,0,0,0,0,0,0,0,0,0,0 80,sensor_x,2m,60,190,0,0,0,0,0,0,0,0,0,0,0,0,0 58,sensor_y,2W,102,309,0,0,0,0,0,0,0,0,0,0,0,0,0 ... ... Data_Type2 Key,Valu41,valu42,valu43,valu44,valu55,valu56,Value71,value82,value93 12,0,0,0,0,0,0,0,0,0 ... ... Data_Type3 Key,Valu41,valu42,valu43,valu44,valu55,valu56,Value71,value82,value93,value32,value97 50,0,0,0,0,0,0,0,0,0,0,0 90,0,0,0,0,0,0,0,0,0,0,0 51,0,0,0,0,0,0,0,0,0,0,0 14,0,0,0,0,0,0,0,0,0,0,0 ... ... Header2,zxc,sadf,sdaf,asdf,OCT25,09:05:00,61000,sdfgj,ashsa,asdkj,Header2,cont,Header2,cont,Header2,1,cont Data_Type1 Key,name,Tx,num1,num2,Value1,value2,value3,value4,value5,value6,Value11,value12,value13,value14,value15,value16,Value33 12,sensor_1,2x,99,56,0,0,0,0,0,0,0,0,0,0,0,0,0 80,sensor_x,2m,60,190,0,0,0,0,0,0,0,0,0,0,0,0,0 58,sensor_y,2W,102,309,0,0,0,0,0,0,0,0,0,0,0,0,0 ... ... Data_Type2 Key,Valu41,valu42,valu43,valu44,valu55,valu56,Value71,value82,value93 12,0,0,0,0,0,0,0,0,0 ... ... Data_Type3 Key,Valu41,valu42,valu43,valu44,valu55,valu56,Value71,value82,value93,value32,value97 50,0,0,0,0,0,0,0,0,0,0,0 90,0,0,0,0,0,0,0,0,0,0,0 51,0,0,0,0,0,0,0,0,0,0,0 14,0,0,0,0,0,0,0,0,0,0,0 ... ... _________________________________________________________________ Unlimited Internet access -- and 2 months free!? Try MSN. http://resourcecenter.msn.com/access/plans/2monthsfree.asp -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: logexample.txt URL: From maxm at mxm.dk Fri Oct 4 06:29:04 2002 From: maxm at mxm.dk (Max M) Date: Fri, 04 Oct 2002 12:29:04 +0200 Subject: Need to download password-protected page with urllib Message-ID: I need to download a page for further automated processing. The problem is that the page is password protected. Which means I go to one page and logs in. I then get redirected to another page. Then I can go to the page I want to view. So I guess that I log in and get a cookie returned. This cookie i should then return for every request. I just cannot seem to find the cookie data in the header data I get returned from the webserver. My guess is that it has something to do with how it urllib2 handles redirects. It is rather sparsely documented :-/ Anyhoo here is some noneworking code if anybody has a pointer. ######################## import urllib, urllib2 class Browser: def __init__(self,, security={ 'USERNAME':'user','PASSWORD':'********'}): """ Goes to the login page and gets the cookie that makes us known to the system. """ post_data = { # pilfered from the form 'RET':'/projects.jsp', 'FORM_NAME':'login', 'ok':'', } post_data.update(security) login_page = 'http://www.somesite.dk/login.jsp' encoded_post_data = urllib.urlencode(post_data) connection = urllib2.urlopen(login_page, encoded_post_data) page_info = connection.info() # why no cookie here ? ###### # save cookie here self.cookie_dict = {} connection.close() def browse(self, url): "Returns content of page, after we are logged in" encoded_post_data = urllib.urlencode(cookie_dict) connection = urllib2.urlopen(login_page, encoded_post_data) page_source = connection.read() connection.close() return page_source if __name__=='__main__': browser = Browser() browser.browse('http://www.somesite.dk/page_i_really_want.jsp') regards Max M From aleax at aleax.it Mon Oct 7 12:26:42 2002 From: aleax at aleax.it (Alex Martelli) Date: Mon, 07 Oct 2002 16:26:42 GMT Subject: List slicing References: Message-ID: <6Bio9.16993$Fz.479349@news1.tin.it> Uwe C. Schroeder wrote: > > Hi guys, > > is there a slicing operation on nested lists ? Slicing is applicable to any list, nested or otherwise, but it does not do what you would like it to do here:-). > i.e. > list=[[1,2,3],[1,2,3],[1,2,3]] Avoid naming a variable the same as the type, as that will hide the type and make it unavailable. Call it 'alist'...:-) > the result of the operation should give [1,1,1] (or [2,2,2] :-)) [ sublist[0] for sublist in alist ] etc. Alex From marco at sferacarta.com Sat Oct 26 04:49:32 2002 From: marco at sferacarta.com (Marco Mariani) Date: Sat, 26 Oct 2002 10:49:32 +0200 Subject: How to Sort this array In-Reply-To: References: Message-ID: <20021026084932.GB14265@sferacarta.com> On Sat, Oct 26, 2002 at 06:23:47AM +0000, Hai Wu wrote: > How to sort an array with numbers like 021025_11441 in it? It needs to be > sorted first by the number before '_', then sorted by the number after '_'? > How to do it using a customized sort function? array = [ x.split('_') for x in array ] array.sort() array = [ '_'.join(x) for x in array ] If your list is big, it's better to avoid a custom cmp function, because the function call overhead in python is heavy. From maxm at mxm.dk Thu Oct 31 06:41:27 2002 From: maxm at mxm.dk (maxm) Date: Thu, 31 Oct 2002 12:41:27 +0100 Subject: urlparse incomplete ? Message-ID: I am writing code where I need to convert relative urls to absolute urls. For this I use the urlparse module. First of, urlparse doesn't take care of urls where there is a user and password. Shouldn't that be corrected? Also I have seen absolute urls of the form "//www.wired.com/path". The ambiguity here being caused by the "//" instead of "http://". The rfc is weak in describing if this is a legal url, but the browser handles them well and just sets the default scheme to http. So I have to handle it. Naturally urlparse cannot know that the scheme is http, but if this is indeed a legal url, shouldn't it be possible to set the default scheme when calling urlparse? regards Max M From PGDEHMKOKIMD at spammotel.com Sun Oct 20 23:10:05 2002 From: PGDEHMKOKIMD at spammotel.com (Alder) Date: Mon, 21 Oct 2002 03:10:05 GMT Subject: Build trouble: Python 2.1.3 on VMS 7.2 References: <3DB25323.2050604@spammotel.com> Message-ID: <3DB37001.6080602@spammotel.com> OpenVMS Alpha 7.2 WASD 8.0 (with OPENSSL 0.9.6E) DECC 6.5 Thanks to the kind assistance of others in c.o.v I've managed to get past the compiler issue and attempt a fresh build of Python 2.1.3. It's not the smoothest build, that's for sure. Anyone else out there manage to build and install this latest release of Python for VMS yet? I think I'm getting close to something usable, but have stalled at the point shown below. If anyone can tell why these messages are generated, please let us know! The directory that is reported 'missing' by the build process is very much where it should be. Thanks, Alder $ @PYTHON_INSTALL DISK$NET:[PYLIB] DISK$NET:[PYTHON] 7.0 . . . Building WASD module (YES/NO) [Y]? register _wasd Building Python Library Imaging Library module (YES/NO) [Y]? register _imaging Building gdchart module (YES/NO) [Y]? register gdchart %COPY-W-INCOMPAT, PYTHON_ROOT:[VMS]CONFIG_OPTIONAL_MODULES.TXT;7 (input) and PYT HON_ROOT:[VMS]CONFIG.DAT;1 (output) have incompatible attributes %AMAC-F-OPENOUT, error opening PYTHON_ROOT:[VMS.O_ALPHA.VMS] as output -RMS-E-DNF, directory not found -SYSTEM-W-NOSUCHFILE, no such file $ From edream at tds.net Thu Oct 10 08:38:38 2002 From: edream at tds.net (Edward K. Ream) Date: Thu, 10 Oct 2002 12:38:38 GMT Subject: Love "Python Cookbook" References: Message-ID: > Got the book 2 weeks ago, what a treasure trove. If you are serious about > Python then get this book. I couldn't agree more. I won't embarrass myself by telling all the things I learned in the first chapter :-) This really is an awe-inspiring book for the breadth of its coverage and the complete excellence of its presentation. The authors and especially the editors deserve the highest praise. Even when explaining the most elementary topics the editors manage to be interesting and even surprising. I have already turned down the corners dozens of pages that I want to study in detail. This book reminds me of the work of the late great musicologist Edward Downs. Shortly after his death in 2001, the Metropolitan Opera ran an appreciation of him and his work. They aired a short recording of him explaining the terms "staccato" and "legato", terms familiar to almost all musicians. Without being in the least condescending, he managed to convey clearly the meanings of both terms, while adding items of interest to me, illustrated with two gorgeous recorded examples showing the impact of the difference between the two. In short, this is just a superb job. It shows the power of a community of users enhanced by the editing of stars. Edward -------------------------------------------------------------------- Edward K. Ream email: edream at tds.net Leo: Literate Editor with Outlines Leo: http://personalpages.tds.net/~edream/front.html -------------------------------------------------------------------- From pj at engr.sgi.com Sun Oct 20 21:34:46 2002 From: pj at engr.sgi.com (Paul Jackson) Date: 21 Oct 2002 01:34:46 GMT Subject: How do I invoke IE browser from Python on Mac OS X? References: <3DB3583E.EF7B9750@alcyone.com> Message-ID: Erik wrote (of the Mac OS X open(1) command): > I presume this is just a command that can be executed from the shell. Yes - it appears so. > > ... For example, the fol- > > lowing command would open all WriteNow files in the cur- > > rent working directory: > > > > open *.wn > > ... if so, this is a curious comment in the man page, since filename > globbing is done by the shell, not the program. Not really. It's just saying that open of several file arguments will open each one. Say you had in your directory: foo.wn bar.wn then this comment is equivalent to saying that: open foo.wn bar.wn will open both foo and bar. No claim is being made here for something like DOS-style glob parsing (expansion by each command instead of by the shell). Granted - whomever wrote that man page line may well not have clearly understood this distinction. -- -- I won't rest till it's the best ... Programmer, Linux Scalability Paul Jackson 1.650.933.1373 From 2cents at yahoo.com Wed Oct 2 04:23:37 2002 From: 2cents at yahoo.com (2cents) Date: Wed, 2 Oct 2002 16:23:37 +0800 Subject: future of python vs java? Message-ID: <3d9aabec@news.starhub.net.sg> Hi, I'm an experience Java Programmer. Currently I'm looking python as alternative language for my customers to build web application. I've been building webapplication using Java and it works well. But mostly it is for high tier clients. So, at this time, I'm looking to offer solution for Small businesses. I've found out Zope application server, is a good alternative to build a web application. But it uses python. My questions: -How is the future of python? (probably as compared to Java) thanks, Heri From itamar at itamarst.DELETEorg Wed Oct 2 15:48:01 2002 From: itamar at itamarst.DELETEorg (Itamar Shtull-Trauring) Date: Wed, 2 Oct 2002 15:48:01 -0400 Subject: Ads for jhom and jhom cards References: <20021002151511.3b5b10a0.itamar@maximam.com> Message-ID: <20021002154801.2f30bdb1.itamar@itamarst.DELETEorg> ARGH. Stupid email program. Sorry, mispost... -- Itamar Shtull-Trauring http://itamarst.org/ Available for Python, Twisted, Zope and Java consulting From doug.fort at verizon.net Sat Oct 12 07:18:56 2002 From: doug.fort at verizon.net (Doug Fort) Date: Sat, 12 Oct 2002 11:18:56 GMT Subject: Ignoring comments - Parsing input file References: Message-ID: On Sat, 12 Oct 2002 09:46:24 +0100, Simon Faulkner wrote: > I am writing a script which reads it's input from a text file > > What is the easiest way to make it ignore lines that start with # or > blank lines? > > > Simon I recommend Dr. David Mertz's book "Text Processing in Python". It's available online at http://gnosis.cx/TPiP -- Doug Fort, Programmer http:/www.dougfort.net From dguo at ux1.cso.uiuc.edu Mon Oct 7 23:42:28 2002 From: dguo at ux1.cso.uiuc.edu (Carolyn) Date: Mon, 7 Oct 2002 22:42:28 -0500 Subject: Integration Message-ID: Hi, there, Now we are working on programming on integration. Can you suggest some reference on that and random number generator?? Thanks in advance. Carolyn From niemeyer at conectiva.com Wed Oct 16 08:36:20 2002 From: niemeyer at conectiva.com (Gustavo Niemeyer) Date: Wed, 16 Oct 2002 09:36:20 -0300 Subject: SOAP frustrations In-Reply-To: <3DAC6F04.2030704@mindspring.com> References: <3DAC6F04.2030704@mindspring.com> Message-ID: <20021016093620.A5329@ibook.distro.conectiva> [...] > In addition, SOAP.py has similar coding style pecularities, and there's > some bug that comes up in Python 2.2 because of changes in Python's > type/class system. (We're using Python 2.1 so it isn't yet a problem. > I also haven't tested ZSI to see if this is a problem.) > > Finally, it seems that neither SOAP.py nor ZSI are actively developed. > There hasn't been a recent release of either package, and the CVS logs > show little change. I've had the same problems when looking for a library some time ago. I ended up forking ZSI and fixing whatever I found interesting for my usage (free software is beautiful, isn't it?). The result is at http://moin.conectiva.com.br/NINZ, and is actually being used for some internal projects in the company. > It's such that the more CS-y people at my client's site believe that > web services in Python are still very immature and [...] They're right. -- Gustavo Niemeyer [ 2AAC 7928 0FBF 0299 5EB5 60E2 2253 B29A 6664 3A0C ] From RObsitnik at northropgrumman.com Thu Oct 24 12:59:19 2002 From: RObsitnik at northropgrumman.com (Obsitnik, Richard) Date: Thu, 24 Oct 2002 09:59:19 -0700 Subject: .NET Message-ID: Hey All I know that Python has extended itself to COM. Does anyone know if Python will move to the .NET platform? Rick -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: Notebook.jpg Type: image/jpeg Size: 2950 bytes Desc: not available URL: From ask.for.it at dev.null.com Wed Oct 9 00:19:28 2002 From: ask.for.it at dev.null.com (Andrew) Date: Wed, 09 Oct 2002 04:19:28 GMT Subject: Attn: Brian Lenihan - do you have a web site where I can d/l your patch for Pysol or.... References: <8u74qu0o37rhfd2srk078pnt4g9uni4t92@4ax.com> Message-ID: On 8 Oct 2002 11:55:33 -0700, brian_l at yahoo.com (Brian Lenihan) wrote: >Well, I could mail it to you, but your e-mail address does not look like >it would work. (Ever since AT&T ate @Home and forced an email name change, it's been bliss - no spam. Not posting my email address on Usenet helps. :-) >http://homepage.mac.com/brian_l Hot damn, it works - THANK YOU!!! (If I may be so bold as to suggest a couple of changes to your Readme file: 1) After applying the patch in Cygwin, you have to move the patched contents of the "src" directory into (supposing you've used the paths supplied by pysol-4.81.tar.bz2) the "pysol-4.81\data" directory in order for pysol to find its files 2) You can manually install the sound server by copying the pre-compiled dll's in "pysolsoundserver-win32\src\build\lib.win32-2.2" to "\Lib\site-packages" - no need to run setup.py 3) In order to hear music and avoid "pysolsoundserver not found" errors, check "Use DirectX for sound playing" under the "Options | Sound..." menu) (And - how much would it be worth to you to come up with a precompiled [*.pyc] version of the whole thing for Win32, your patch already incorporated, including the sound server binaries?) Thanks again, Andrew -- "That's not me, and you know it." - Karl Rove, Shrubya's chief political adviser, responding to suggestions he manufactured the Iraq debate to divert attention from the sagging economy, in Time magazine (Sure, Karl. Whatever you say.) From bloke at ii.net Wed Oct 2 03:56:28 2002 From: bloke at ii.net (Rob Hall) Date: Wed, 2 Oct 2002 15:56:28 +0800 Subject: Thread.run() does not get called. References: <3d9a9681$0$18332@echo-01.iinet.net.au> Message-ID: <3d9aa691$0$18350@echo-01.iinet.net.au> Fixed the problem. The problem was I needed the folowing line in my __init__: self.logonAddress = logonAddress When I tried refererencing logonAddress in run() it didn't exist. I assume I wasn't getting an error returned because it was in a different thread. Rob. From skip at pobox.com Thu Oct 24 11:28:10 2002 From: skip at pobox.com (Skip Montanaro) Date: Thu, 24 Oct 2002 10:28:10 -0500 Subject: Did someone turn down the volume? In-Reply-To: References: Message-ID: <15800.4490.707995.313286@montanaro.dyndns.org> Bill> The volume of messages coming from python-list (from my POV) has Bill> dropped off dramatically in the last two days. Is it just my Bill> lousy pipes, or did perl finally win ;-) ? I think the mail-news gateway must be broken. I sent a message to Barry Warsaw and Greg Ward last night, but haven't heard back yet. -- Skip Montanaro - skip at pobox.com http://www.mojam.com/ http://www.musi-cal.com/ From fredrik at pythonware.com Sun Oct 13 11:55:59 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 13 Oct 2002 15:55:59 GMT Subject: Internationalization bug?? [Python 2.2.1, RedHat 8.0, Swedish] References: <7d546104.0210120857.3f4e3857@posting.google.com> Message-ID: Paul Watson wrote: > If len() returns the number of bytes, what can Urban Anjar use to get the > number of characters? len() on a string of bytes returns the number of bytes. to get the number of characters, make sure you're using len() on a string containing characters. to convert between byte buffers and strings of characters, use the encode/decode methods, or the unicode constructor. chars = unicode(bytes, encoding) bytes = chars.encode(encoding) chars = bytes.decode(encoding) From hgg9140 at seanet.com Wed Oct 9 23:27:24 2002 From: hgg9140 at seanet.com (Harry George) Date: 09 Oct 2002 20:27:24 -0700 Subject: question on global variables References: <3da4fe61_8@goliath.newsgroups.com> Message-ID: mongo57a at comcast.net writes: > Somewhat new to Python here..... > > I want to change/use a value throughout my program - what I would normally > refer to as a "global" variable. > > I see that there is a "global" command - and I assume its use would be > global var_name. This I have coded (works) but I am unable to use it "global > name var_name is not defined". > > TIA > > mydata=0 print mydata --> 0 def myfunc1(x): mydata=x myfunc1(5) print mydata --> 0 def myfunc2(x): global mydata mydata=x myfunc2(5) print mydata --> 5 That is, "global" allows globally defined data to be modified from inside a function. Otherwise it is read only, and treated as a local variable. Of course, you should consider capturing "global" data in some object, so you can isolate it if you need to do threads. > -----------== Posted via Newsfeed.Com - Uncensored Usenet News ==---------- > http://www.newsfeed.com The #1 Newsgroup Service in the World! > -----= Over 100,000 Newsgroups - Unlimited Fast Downloads - 19 Servers =----- -- Harry George hgg9140 at seanet.com From =?iso-8859-5?Q?=DF=D5=DD=D3=E3=D8=DD=D8=E1=E2=D0?= at =?iso-8859-5?Q?=DC=D0=D8=DB?=.=?iso-8859-5?Q?=DD=D5=E2?=.=?iso-8859-5?Q?=DC=DA?= Tue Oct 8 18:02:27 2002 From: =?iso-8859-5?Q?=DF=D5=DD=D3=E3=D8=DD=D8=E1=E2=D0?= at =?iso-8859-5?Q?=DC=D0=D8=DB?=.=?iso-8859-5?Q?=DD=D5=E2?=.=?iso-8859-5?Q?=DC=DA?= (=?iso-8859-5?Q?=B4=D0=DC=F8=D0=DD_=B3=2E?=) Date: Wed, 9 Oct 2002 00:02:27 +0200 Subject: shared memory module bugs? References: Message-ID: <3da355f2$1@news.mt.net.mk> > I would like to make a working shared memory module. I could probably make > the current version work better by patching it. > My question is: is anyone actively working on the module? It appears to > have last been updated in 2000, and doesn't really have a project page. Or > are there any other such modules in existence? If I did patch it to make > it work, or make my own, would someone be interested in using it? I would use it if you can make it act like a dictionary, and also if you add the option of creating new objects in the shared memory pool. Is this possible with python? The last time I was looking you couldn't replace Python's memory manager in runtime. -- ?????? Loose bits sink chips. From xx758 at cam.ac.uk Thu Oct 17 09:15:43 2002 From: xx758 at cam.ac.uk (Xiao-Qin Xia) Date: Thu, 17 Oct 2002 14:15:43 +0100 Subject: A module's name and its functions/clasess Message-ID: Hi, anybody, Can a module know itself's name and the functions/clasess defined in the module? (in order to bind these functions/classed with psyco) Thanks from Xiao-Qin Xia From alanmk at hotmail.com Fri Oct 11 13:17:33 2002 From: alanmk at hotmail.com (Alan Kennedy) Date: Fri, 11 Oct 2002 18:17:33 +0100 Subject: Stringify object reference? References: <3DA6FB65.5D6A4AFE@hotmail.com> Message-ID: <3DA707AD.92BCF22D@hotmail.com> Alan Kennedy wrote: >> Basically, I'm looking for the python equivalent of a CORBA IOR. >> >> Any suggestions? Or am I missing something completely obvious? holger krekel wrote: > Python's id of an object 'id(obj)' won't help you at all. There > is no mechanism for reinstantiating an object by its serialized > id. You probably should look for CORBA-Orbs such as Fnorb or > OmniORB. Or maybe the Zope Object DataBase (ZODB) would fit > your needs. > > A bit more context might help us to help you . As I mentioned in my original post, I want to annotate (generic) XML tree-like object models (e.g. DOM, etc) with my own python objects. The only way I can see to do it is to to store my objects, or a reference thereto, into an XML attribute, which limits me to some ascii/charset representation. I realise I could pickle() the whole object, and put that into the attribute. But that would be highly memory inefficient, unless I delete the original object that was pickled, which would be time inefficient. I'm beginning to think I have to maintain my own namespace/dictionary for these things, indexed by id(object). Which is an acceptable solution. Is there a specific reason why id()'s can't be turned back into objects? Is it an implementation specific thing? Or is it to stop people messing with pointers, etc? Regards, alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From aleax at aleax.it Sun Oct 6 05:51:04 2002 From: aleax at aleax.it (Alex Martelli) Date: Sun, 06 Oct 2002 09:51:04 GMT Subject: PhotoImage: iterating over a list of images References: Message-ID: Ian Oeschger wrote: > Why does the example below display only img4.gif and not any of > the others. All of them are sitting in the same directory. Is there > something wrong about the way that I iterate over the list?? No, the problem is that being JUST used in an image= does not suffice to keep a PhotoImage object alive -- think of it as a weak reference (though the real underlying issue is different, it works much the same way). Simplest fix, e.g.: _images = {} def makeBtn(icon): _images[icon]=PhotoImage(file=icon) Button(root, width=24, height=24, image=_images[icon], command=sys.exit).pack(side=RIGHT, padx=5, pady=5) Alex From jkraska at san.rr.com Sat Oct 19 23:32:39 2002 From: jkraska at san.rr.com (Courageous) Date: Sun, 20 Oct 2002 03:32:39 GMT Subject: Why is Python a good first scripting language? References: Message-ID: >> (1) Clean, terse, easy-to-read syntax. All subjective terms, and everyone >[snip] > >From personal experience, in this regard python is better than anything I've >seen in ~12 years of programming with a reasonable set of languages. Personally, I agree. I'll make one aside. Some folks, mostly ones already experienced, are alienated by the lack of specific block delimiters (i.e., braces). This is, in my opinion, an issue of familiarity. problems, which is a strength and a weakness. > >Indeed. Having ditched Perl for python about a year ago, I'd say that in this >particular point python shines over perl. This is at the heart of the historical appeal of python. C// From rpw3 at rpw3.org Fri Oct 18 05:06:08 2002 From: rpw3 at rpw3.org (Rob Warnock) Date: Fri, 18 Oct 2002 04:06:08 -0500 Subject: ILC 2002 - Last Call For Participation References: Message-ID: Raymond de Lacaze wrote: +--------------- | ASSOCIATION OF LISP USERS (ALU) | INTERNATIONAL LISP CONFERENCE 2002 (ILC 2002) | HOLIDAY INN - FINANCIAL DISTRICT | SAN FRANCISCO, CALIFORNIA | SUNDAY, OCT. 27TH - THURSDAY, OCT. 31ST +--------------- For the benefit of those coming from elsewhere, the weather right now [Fri, 18 Oct 2002 02:02:42 PDT] in the San Francisco Bay Area (and forecast to remain the same for most of the Conference week) is a typical fall weather pattern: - Fog (w/ some drizzle) along the Pacific coast evening, nights, and into the late mornings, with the nightly fog penetrating into the City of San Francisco proper and spreading as a low stratus layer over most of the Bay Area (including East Bay). - The fog/stratus will burn off beginning far inland and progressing back towards the coast during each day, earlier the farther east one is. - Depending on where you are, lows will be in the 40-50 F (4-10 C) range, with highs around 50-60 F (10-15 C) on the coast, 60-70 F (15-20 C) around the Bay, and 65-80 F (18-27 C) farther inland. The City of San Francisco itself partakes of both the "coastal" and "Bay" microclimates, depending on where in the City one is. In short, dress for cool-ish (and occasionally misty) fall weather at night, and cool-to-warm weather during the day. But don't overdress. Typically a light windbreaker (and maybe a hat) will keep one warm enough, and it may suddenly turn hotter unexpectedly during the day. -Rob p.s For those who can read METAR aviation reports, the most recent reports from for the San Francisco, Oakland, San Carlos, Palo Alto, and San Jose airports (all showing 12-13 C) are: KSFO 180756Z 23006KT 10SM OVC016 13/09 A2999 RMK AO2 SLP156 T01280094 401720122 KOAK 180753Z 27008KT 10SM OVC017 13/10 A3000 RMK AO2 SLP157 T01330100 401780122 KSQL 180347Z 31010KT 10SM SCT030 12/09 A2996 RMK LAST KPAO 180347Z 30008KT 12SM FEW020 SCT200 12/08 A2995 RMK LAST KSJC 180753Z 34005KT 10SM OVC018 13/08 A2999 RMK AO2 SLP155 T01280083 401940111 The SQL/PAO reports stop at 9:00pm local, which which why they're only showing "scattered/few" clouds at ~2-3 Kft, while the others (4 hrs later) show "overcast" at 1600-1800'. Winds are light, 5-10 kts, varying from out of the the SW to NW as one moves from the north to south of the Bay. Horizontal visibility is quite good (but with only a 3-4 C difference between temp & dew point, fog developing later is possible), and the barometric pressure stands at ~30" Hg. ----- Rob Warnock, PP-ASEL-IA 627 26th Avenue San Mateo, CA 94403 (650)572-2607 From aleax at aleax.it Thu Oct 31 11:25:00 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 31 Oct 2002 16:25:00 GMT Subject: lists, performance.. References: Message-ID: gabor wrote: > hi, > > i'm working on a graphic application ( python + opengl).. > > and i have some lists of vertices... but that's not important.. > > let's say a have loooooooong ( long = 500 to 5000 ) lists of relatively > simple objects.. > > 2 questions: > > 1. is a list implemented as a vector? i mean looking up the n-th element > is done in o[1] (constant time)? Yes. > 2. i want to insert several lists into a big list.. better to say i want > to concatenate them... but i don't really like the 'extent' method, > because i want to do a deep-copy... for example: > list1 = [ ['a','b','c'], [1,2,3,4] ,[5,6,7]] > list2 = [] > list2.extend(list1) > but now if i modify an element in list1, list2 gets modified too.. > for now i'm doing: > > list1 = ... > list2 = ... > > for item in list2: > list1.append(item) How do you think this helps you? >>> list1 = [ ['a','b','c'], [1,2,3,4], [5,6,7]] >>> list2 = [] >>> for item in list1: list2.append(item) ... >>> list2 [['a', 'b', 'c'], [1, 2, 3, 4], [5, 6, 7]] >>> list1[1].append('boo!') >>> list2 [['a', 'b', 'c'], [1, 2, 3, 4, 'boo!'], [5, 6, 7]] >>> If you want a deep copy, ask for a deep copy: >>> list1 = [ ['a','b','c'], [1,2,3,4], [5,6,7]] >>> list2 = [] >>> import copy >>> list2.extend(copy.deepcopy(list1)) >>> list2 [['a', 'b', 'c'], [1, 2, 3, 4], [5, 6, 7]] >>> list1[1].append('boo!') >>> list2 [['a', 'b', 'c'], [1, 2, 3, 4], [5, 6, 7]] >>> > but maybe this is too slow.. or isn't? ideally i'd like to have > something like reserve in c++.... Unfortunately there's no "reserve" in Python, but sometimes you can get the same (very modest) kind of speedup by making the target list originally long, keeping its "actual active length" as a separate variable, and assigning to appropriate slices. However, we're talking about MICRO-optimizations here -- a few percents here and there -- and compared to the inevitable, BIG overhead of making deep copies I suspect they'll be barely measurable in your case. > so let's say i have a list which len() is 30. now i want to insert > 20elements... wouldn't it be faster to somehow resize the list directly > to 50, and then add the elements? Marginally, yes. Irrelevantly, of course...: import time def ex30_to_50_simple(list30, list20): for x in list20: list30.append(x) def ex30_to_50_smart(list30, list20): list30.extend(20*[None]) for i in xrange(20): list30[30+i] = list20[i] def timit(ex30_to_50_func): list30_org = range(30) list20_org = range(20) totim = 0.0 clock = time.clock for x in range(100000): list30_temp = list30_org[:] start = clock() ex30_to_50_func(list30_temp, list20_org) stend = clock() totim += stend-start return totim def ex30_to_50_obvious(list30, list20): list30.extend(list20) for n in range(3): for f in ex30_to_50_simple, ex30_to_50_smart, ex30_to_50_obvious: print '%.2f %s' % (timit(f), f.func_name) [alex at lancelot pyRXP]$ python2.2 -O ba.py 2.39 ex30_to_50_simple 2.28 ex30_to_50_smart 0.36 ex30_to_50_obvious 2.44 ex30_to_50_simple 2.38 ex30_to_50_smart 0.34 ex30_to_50_obvious 2.32 ex30_to_50_simple 2.43 ex30_to_50_smart 0.26 ex30_to_50_obvious the so-called 'smart' function generally beats the simple one by a few hundreds of a second over 100,000 repetitions -- of course, neither of them is anywhere close to a match for the one obvious solution. It's a bit sharper with Python 2.3, but the overall indication remains the same: [alex at lancelot pyRXP]$ python2.3 -O ba.py 2.17 ex30_to_50_simple 1.73 ex30_to_50_smart 0.37 ex30_to_50_obvious 2.22 ex30_to_50_simple 1.77 ex30_to_50_smart 0.36 ex30_to_50_obvious 2.30 ex30_to_50_simple 1.66 ex30_to_50_smart 0.27 ex30_to_50_obvious Note that all three functions have identical semantics (for lists of the indicated lengths): none of them deep-copies anything at all. Once you DO have deep copies, the overhead of that dominates, though the obvious solution remains marginally better (skipping the alleged 'smart' one here): import time import copy def ex30_to_50_deep_simple(list30, list20): for x in copy.deepcopy(list20): list30.append(x) def timit(ex30_to_50_func): list30_org = range(30) list20_org = range(20) totim = 0.0 clock = time.clock for x in range(10000): list30_temp = list30_org[:] start = clock() ex30_to_50_func(list30_temp, list20_org) stend = clock() totim += stend-start return totim def ex30_to_50_deep_obvious(list30, list20): list30.extend(copy.deepcopy(list20)) for n in range(3): for f in ex30_to_50_deep_simple, ex30_to_50_deep_obvious: print '%.2f %s' % (timit(f), f.func_name) [alex at lancelot pyRXP]$ python2.2 -O ba.py 2.46 ex30_to_50_deep_simple 2.22 ex30_to_50_deep_obvious 2.50 ex30_to_50_deep_simple 2.24 ex30_to_50_deep_obvious 2.47 ex30_to_50_deep_simple 2.23 ex30_to_50_deep_obvious [alex at lancelot pyRXP]$ python2.3 -O ba.py 2.20 ex30_to_50_deep_simple 1.96 ex30_to_50_deep_obvious 2.12 ex30_to_50_deep_simple 1.99 ex30_to_50_deep_obvious 2.11 ex30_to_50_deep_simple 1.94 ex30_to_50_deep_obvious Note that I'm doing TEN thousand repetitions here, NOT a *hundred* thousands like I did before. *Deep copying AIN'T FAST*. > i'm worried about how many times would the list resize itself to be able > to contain the additional 20elements if i would add them one-by-one I think you're worrying about the wrong things: study listobject.c in the Python sources to see why. Rather, I think you should worry about the need for deep copies. Do you REALLY need to keep and reuse the small lists that you're adding to the large list, so that the deep copy is truly needed, or could you get by in simpler, faster ways? Alex From bvdpoel at kootenay.com Fri Oct 18 12:37:12 2002 From: bvdpoel at kootenay.com (Bob van der Poel) Date: Fri, 18 Oct 2002 09:37:12 -0700 Subject: Tracking validity in tkinter widget References: <3DAF7275.3519855@kootenay.com> <20021017214902.B5043@unpythonic.net> Message-ID: <3DB038B8.7D74A33E@kootenay.com> Jeff Epler wrote: > > While the button is pressed, Tk captures mouse motion events and sends them > to the widget (or, in this case, a canvas item) where the button was first > pressed. Thanks, Jeff, for the reply. I looked into this a bit more and checked a few of the sample programs. Guido's paint.py and Matt's rubber* programs both demonstrate the same problem. I see 2 solutions (well 3): 1. Use and events to set a flag and then have the callback check the flag. This actually works fine. 2. Maintain the actual coords of the widget and have the compare the event.x, event.y to the coords. 3. Forget it. If someone wants to move the slider after the cursor has left the arena, let it move. After fooling around with this for several hours and running a bunch of demos, I see that most people are using solution 3. -- Bob van der Poel ** Wynndel, British Columbia, CANADA ** EMAIL: bvdpoel at kootenay.com WWW: http://www.kootenay.com/~bvdpoel From jdhunter at nitace.bsd.uchicago.edu Thu Oct 31 11:42:33 2002 From: jdhunter at nitace.bsd.uchicago.edu (John Hunter) Date: Thu, 31 Oct 2002 10:42:33 -0600 Subject: RFC: CmpTrue Message-ID: After reading The Python Cookbook and being inspired by all the examples where you can avoid the look before you leap paradigm with exceptions, the Null design pattern and so on, I found myself wanting to avoid the look-before-you-leap/no-good-default-at-init problem discussed in the doc string below. class CmpTrue: """ Return true on any comparison. This is useful when you want to set a default variable at initialization that will be overridden on first comparison, as in minVal = None for seq in allSeqs: minSeq = min(seq) if minVal is None: minVal = minSeq break if minSeq < minVal: minVal = minSeq This song and dance can be simplified in CmpTrue to minVal = CmpTrue() for seq in allSeqs: minSeq = min(seq) if minSeq < minVal: minVal = minSeq With the arithmetic functions defined to return a CmpTrue object, you can use the CmpTrue object in arithmetic computations lastTime = CmpTrue() def somefunc(): global lastTime """This function will ignore repeated calls if the intercall interval is less than 1 second. (inspired when pygtk repeatedly called my expose_event function on window resize)""" tnow = time.time() if tnow - lastTime > 1.0: print 'OK' lastTime = tnow else: print 'Go Away, Monster' for i in range(10): somefunc() time.sleep(.3) Use with caution! """ __returnTrue = ['__lt__', '__le__', '__eq__', '__ne__', '__gt__', '__ge__', '__cmp__', '__rcmp__'] __returnSelf = ['__add__', '__sub__', '__mul__', '__div__', '__mod__', '__divmod__', '__pow__', '__lshift__', '__rshift__', '__rsub__', '__rmul__', '__rdiv__', '__rmod__', '__rdivmod__', '__rpow__', '__rlshift__', '__rrshift__'] def __init__(self): for func in self.__returnTrue: self.__dict__[func] = self.__return_true for func in self.__returnSelf: self.__dict__[func] = self.__return_self def __return_self(self, arg=None): return self def __return_true(self, arg=None): return 1 def __str__(self): return "It's true, really" c = CmpTrue() print 2*c-2 print 2*c-2 > 1 So the general problem I am trying to solve is when you have a numeric variable where it is difficult to come up with an acceptable default value at initialization, such as when you want to keep a running minimum. For a while, I used minVal = inf which can be used in code with if minSeq < minVal: minVal = minSeq but this requires that inf is defined. Using 1e300 at initialization will get the job for most practical applications, but not all and could represent a bug waiting to happen. These are the kinds of default value/look before you leap problems CmpTrue tries to solve. Comments? Perhaps the reduction of all arithmetic operations to self if a gotcha waiting to happen, and is a bit heady handed... Thanks, John Hunter From Oschler at earthlink.net Tue Oct 15 09:23:39 2002 From: Oschler at earthlink.net (Robert Oschler) Date: Tue, 15 Oct 2002 13:23:39 GMT Subject: Commercial: Python part of speech tagger, text categorization References: Message-ID: "Mark Watson" wrote in message news:B9C46BAC.94E2%markw at markwatson.com... > Greetings, > > I have released my NLP tools in Python versions (originally > written in Common LISP). If you are interested, check out > the commercial products page at: > > http://www.markwatson.com > > Thanks, > Mark > How does it compare to the Link Grammar package by Don Sleator and his group? thx From jeremy at jdyallop.freeserve.co.uk Mon Oct 21 16:01:22 2002 From: jeremy at jdyallop.freeserve.co.uk (Jeremy Yallop) Date: 21 Oct 2002 20:01:22 GMT Subject: Spell-check engine? References: <20021018200007.12387.54659.Mailman@mail.python.org> <3DB33B40.5080003@rogers.com> <2259b0e2.0210210835.791de298@posting.google.com> Message-ID: * Michele Simionato | I take the occasion for a simple question about ispell/aspell. : | $ echo "hello worldd" | ispell -a : | @(#) International Ispell Version 3.1.20 (but really Aspell .33.7 | alpha) | * | & worldd 17 6: world, worlds, wold, whorled, would, wooled, wield, | world's, weld, wild, whirled, wolds, worded, Wilda, Wilde, wiled, word : | But what is the meaning of the first number, 17 in this case ? Did you consider reading the manpage? ISPELL(1) The -a option is intended to be used from other programs through a pipe. [...] If the word is not in the dictionary, but there are near misses, then the line contains an '&', a space, the misspelled word, a space, the number of near misses, the number of characters between ^^^^^^^^^^^^^^^^^^^^^^^^^ the beginning of the line and the beginning of the misspelled word, a colon, another space, and a list of the near misses separated by commas and spaces. Jeremy. From anandpillai6 at yahoo.com Mon Oct 7 11:07:48 2002 From: anandpillai6 at yahoo.com (Anand) Date: 7 Oct 2002 08:07:48 -0700 Subject: Function GetData() in wxImage Message-ID: <41c203e.0210070707.15595d94@posting.google.com> Hi I am writing an image viewer in wxPython using the wxImage class. I want to manipulate the image data for effects. I tried to use the GetData() method of the wxImage class which returns a const char *(wxWindows documentation). How do I manipulate this object. Is it a python object or a C unsigned char * stream ? Can i apply std 'C' calls on it or do I need to use methods of python ? Concerned code... def myfunc: ... self.img = wxImage(fileName) chunk = self.img.GetData() # What is this chunk ? pass Thanks Anand From hwlgw at hotmail.com Tue Oct 15 11:41:54 2002 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 15 Oct 2002 08:41:54 -0700 Subject: realtime design References: <8fvfoa.t14.ln@ix.netcom.com> Message-ID: > [Dennis Lee Bieber] > ... > Will Stuyvesant fed this fish to the penguins on Monday 14 October > ... Yay, and the fish turns out to be a whale. Oh no, thats not a fish, that is a mammal. A shark then. > ... > import Queue > ... Much better to use Queue. Thank you for showing your code. > def testFunctionC(a): > # takes about 4 seconds with a == 19 on my computer, > # keeps the cpu very busy > tmp = 2L > for t2 in range(a): > tmp = tmp * 2L > while tmp > 0: > t2 = 2L * t2 > tmp = tmp - 1 > return t2 <> 12345L I have been looking for some kind of function that keeps the cpu doing C stuff **very** busy (demonstrates treading.Tread.join(timeout) failure), with a parameter that gives a linear behavior in time, so testFunction(2*a) would take twice as long. But such a test function is hard to find isn't it. > ... > # your exponential equation, apparently the function took 12743msec > ... Not mine...I think I found the equation in a Tim Peters posting. And it turns out this notebook is doing that function about 3 times faster than yours. *grin* > ... > IMPORTANT NOTICE -- Even though ALL cases resulted in a TIMEOUT > return, the program itself cannot exit until thread-4 finishes its > calculation! > ... That was expected. Unless that thread can be killed, but it just is not listening and even keeps the caller from doing things! What I thought was possible was to have the main program executing statements at least every 200ms, or 500ms, or even 5000ms for that matter. And that is just not to be. Not using threads anyway. So for now it is byebye to my idea for modeling realtime software this way. But...it has been fun experimenting and I guess we did learn a thing or two. Thanks! ''' QOTD, about experiment Bowie's Theorem: If an experiment works, you must be using the wrong equipment. ''' From tjreedy at udel.edu Thu Oct 31 09:57:47 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 31 Oct 2002 09:57:47 -0500 Subject: Windows Backdrop References: <41c203e.0210310318.30e6d349@posting.google.com> Message-ID: "Anand" wrote in message news:41c203e.0210310318.30e6d349 at posting.google.com... > Does wxWindows define a function to set an image, say an instance of wxImage > as the current window backdrop. Try wxWindows mailing list for this and other question. From max at alcyone.com Mon Oct 21 16:46:20 2002 From: max at alcyone.com (Erik Max Francis) Date: Mon, 21 Oct 2002 13:46:20 -0700 Subject: python script question References: Message-ID: <3DB4679C.F151DA99@alcyone.com> Ken wrote: > Hi all, just like to ask if python CGI script can be mix with python > Shell > script? > > I.e. if: > file1 is CGI (#!/usr/local/bin/python) > and file2 is shell script (#!/bin/sh) > > can I have "import file2" inside file1 and use the functions inside > file2? No. You want os.system or some variant. The import statement in Python is _only_ for importing Python modules. > Also, does the shell script have *.py extension? If it did and tried to import it you'd get some interesting syntax errors. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ I want a martini that could be declared a disaster area. \__/ Capt. Benjamin "Hawkeye" Pierce Alcyone Systems' Daily Planet / http://www.alcyone.com/planet.html A new, virtual planet, every day. From BC at energy.com Mon Oct 21 14:19:42 2002 From: BC at energy.com (Bill Carter) Date: Mon, 21 Oct 2002 11:19:42 -0700 Subject: Help with MySQLdb Please Message-ID: I have a problem that I just can't figure out. I have a mysql table that has a few columns in it the column in question is a "varchar(8)" type. If I issue the commands directly it work as expected but when I use python and MySQLdb I get strange results. Command line that works outside python is as follows SELECT t.col1, t.col2, t.col3 from test as t where t.col2 LIKE "%123%" That work just like I want it to work, But the same example in python returns "errortype" errors. Python: userinput = "123" cursor.execute(" SELECT t.col1, t.col2, t.col3 from test as t where t.col2 LIKE '%%%s%%', (userinput)) if I convert "int(userinput)" it will work as long as I don't put in any non numeric characters, even those the column is a text / string column. I just can't figure out what I am doing wrong. Any help would be great BC From jgresula at .no.spam.seznam.cz Sun Oct 6 10:11:39 2002 From: jgresula at .no.spam.seznam.cz (Jaroslav Gresula) Date: Sun, 06 Oct 2002 14:11:39 GMT Subject: Which Linux distribution? Message-ID: <3da0412a@post.newsfeed.com> *** post for FREE via your newsreader at post.newsfeed.com *** I've installed RH 7.3 recently and I'm pretty frustrated from their approach to Python packages. It is almost impossible to switch to Python 2.x version since majority of their scripts is based on 1.5.x. I've already read some guides how to accomplish that but it is PITN. I'm about to switch to different distribution and that's my question. What is your experience? What distribution would you recommend to me? My primary requirement on the distrubution is to have a nice Pyton environment with easy maintenance of multiple python versions. -----= Posted via Newsfeed.Com, Uncensored Usenet News =----- http://www.newsfeed.com - The #1 Newsgroup Service in the World! -----== 100,000 Groups! - 19 Servers! - Unlimited Download! =----- From threeseas at earthlink.net Mon Oct 21 00:32:28 2002 From: threeseas at earthlink.net (Timothy Rue) Date: Mon, 21 Oct 2002 04:32:28 GMT Subject: Looking to hire a python programmer. Message-ID: <574.59T1791T294629threeseas@earthlink.net> The project is listed on http://www.rentacoder.com , just do a search on "3seas" for information. I do prefer to go thru a middle party such as rentacoder and am interested in any other such sites. --- *3 S.E.A.S - Virtual Interaction Configuration (VIC) - VISION OF VISIONS!* *~ ~ ~ Advancing How we Perceive and Use the Tool of Computers!* Timothy Rue What's *DONE* in all we do? *AI PK OI IP OP SF IQ ID KE* Email @ mailto:timrue at mindspring.com >INPUT->(Processing)->OUTPUT>v Web @ http://www.mindspring.com/~timrue/ ^<--------<----9----<--------< From ianb at colorstudy.com Tue Oct 8 16:40:42 2002 From: ianb at colorstudy.com (Ian Bicking) Date: 08 Oct 2002 15:40:42 -0500 Subject: getattr on objects In-Reply-To: <3DA2B669.7070204@gazeta.pl> References: <3DA2B669.7070204@gazeta.pl> Message-ID: <1034109642.4609.153.camel@dsl-65-184-205-5.telocity.com> On Tue, 2002-10-08 at 05:41, bromden wrote: > I wanted to make a class which would pretend to have any > method you can call on it (returning some default value). > Defined a class: > >>> class C: > ... def hasattr(self, name): return 1 > ... def getattr(self, name): return self.default > ... def default(self): return 'default' [snip] More generally, there's a bunch of "magic" methods in Python to do this sort of thing, described here: http://www.python.org/doc/current/ref/specialnames.html Ian From max at alcyone.com Fri Oct 18 23:16:21 2002 From: max at alcyone.com (Erik Max Francis) Date: Fri, 18 Oct 2002 20:16:21 -0700 Subject: Private variables References: Message-ID: <3DB0CE85.21815ED@alcyone.com> "Timothy J. Wood" wrote: > As a script writer you will be able to make scripts available for > people to download -- but you won't be able to 'dynamically install' > them on someone else's machine. But the distinction is moot, really, > since most game players will be ignorant of the security implications > of various constructs and shouldn't be expected to do a security audit > of some code to play a new game type. But how would these security implications be any different from such a user downloading and installing _any_ old software on their machine? Software is software, if you're downloading, installing, and running software on your own machine you have to take some responsibility for it. After all, someone could (by other means) have a compromised system where the Python interpreter has been replaced such that innocuous scripts turn malicious. That's hardly something you should take into account when writing Python software, however. > Sure -- all the resource-based DoS problems will still exist, but > these at least don't corrupt or expose any of the user's information. > They can kill the application, uninstall that game type and never play > it again. As I said, if you're looking for some minimal protection, see the rexec module. I suspect you're chasing a ghost, though. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ Sit loosely in the saddle of life. \__/ Robert Louis Stevenson Alcyone Systems / http://www.alcyone.com/ Alcyone Systems, San Jose, California. From dave at boost-consulting.com Sun Oct 13 15:42:05 2002 From: dave at boost-consulting.com (David Abrahams) Date: 13 Oct 2002 15:42:05 -0400 Subject: building extensions with gcc and python 2.2 References: Message-ID: Ken Seehof writes: > I'm developing a tool that involves dynamic compilation of python extensions. > Since I do not want to require my windows users to buy MSVC, I can no > longer use it build my extensions (i.e. the user needs to be able to > recompile). > > Therefore, I am experimenting with using gcc as my compiler. > > Should I use Cygwin or Mingw? MinGW produces code that can be commercially redistributed, so it's a better replaceement for MSVC if you care about that. It's very odd about its interpretation of __declspec(dllexport) in some cases, though, so if that matters to you, you might consider Cygwin. Cygwin uses the Unix model of exporting all symbols by default, so you won't have to worry about that. MinGW-2.0 is now using gcc-3.2, which is a very conformant C++ compiler. I don't know if you get that automatically with a Cygwin download, though you could certainly build one (as I have done) if you're willing to wait a few hours for it to complete. the-choice-is-yours-ly, -- David Abrahams * Boost Consulting dave at boost-consulting.com * http://www.boost-consulting.com From a at b.c Thu Oct 10 12:49:13 2002 From: a at b.c (Daniel T.) Date: Thu, 10 Oct 2002 16:49:13 GMT Subject: No tabs in post PLEASE!!! (was Re: partial list sort) References: <20021009094141.GA852@jsaul.de> <2Rep9.19819$ne4.8631@fe05> Message-ID: "Terry Reedy" wrote: > "Fran?ois Pinard" wrote: > > Somewhat tongue in cheek, I wrote > > >> > > Tabs are bad for Usenet posting if you want stupid people > like me who > > >> > > use Outlook Express to read posted code. > > >I've seen > > a constant push, for years, by recipients using broken software, > asking the > > whole planet to be polite and help them cope with their > brokenedness. That > > push should be considered unwelcome, and politeness is misplaced > here. > > Since I started this subthread, please note that I did *not* push (and > intentionally so). Is that why the subject line says "PLEASE!!!" that's a pretty loud shout. At any rate, I'm sorry. Normally I successfully ignore/avoid these religious debates, but I'm somewhat frustrated right now because I'm finding my job difficult. You see, I'm in the business of taking things other people did with no regard to a wider audience, and trying to make it work for a niche. Yes, I get paid to make things portable. Kind of ironic when you think about it. :-) -- In early 1955, Sammet recalled, her boss, Arthur Hauser, asked her if she wanted to be a programmer. Sammet replied, "What's a programmer?" Hauser said he did not know, but he knew the computer project would require a programmer... "That's how I became a programmer," Sammet explained, smiling at the memory. -- Steve Lohr "Go To" From peter at engcorp.com Thu Oct 3 18:48:29 2002 From: peter at engcorp.com (Peter Hansen) Date: Thu, 03 Oct 2002 18:48:29 -0400 Subject: Deleting the first element of a list References: <3d9b72c0_5@news.newsgroups.com> <3d9b8082$1@news.sentex.net> <3D9BC6F0.4080500@cygnus-software.com> Message-ID: <3d9cc939$1@news.sentex.net> Chad Netzer wrote: > On Wednesday 02 October 2002 21:26, Bruce Dawson wrote: > >>Highly applicable to this thread. Deleting the first item of a Python >>list or C++ vector is an O(n) operation - proportional to the number >>of items in the list. If you do that for every item in the list it is >>O(n^2) - proportional to the square. > > Here are the results on my machine: ... > avg time to delete list of length 4096: 0.0555817842484 secs ... > > And if I change the 'del l[ 0 ]' to 'del l[ -1 ]': ... > avg time to delete list of length 4096: 0.0080970048904 secs ... > Here a doubling of list length leads more or less to a doubling of > running time (ie. O( N )). > > So, no real surprises, but illustrative for those who have never > compared O( N^2 ) to O( N ) algorithms before (hmmm, maybe that should > be phi( N ) or even o( N )? ) I didn't dare do a longer list for 'del > l[ 0 ]', whereas 'del l[ -1 ]' scales easily to much longer lists. Nice analysis. I find it equally illustrative, for those who always jump to optimization too quickly, to note that for any value of N up to at least 4096 in your example, the difference could well be completely below the threshold of noticability for anything involving, for example, human response times. Depending entirely on the particular case in which it is going to be used, it is quite possible that spending more than ten seconds on the whole issue ends up being wasted time. Maybe the list will never have more than 100 items, or maybe it has 16000 but it runs once a day and nobody will be sitting waiting for it. All the emphasis on algorithmic performance improvements is interesting, but practically none of this should ever be an issue until somebody is actually *bothered* by the performance once the system is running, at least in testing. (Well, that might be overstating it a little: in some environments making changes that late in the game is dangerous, but I guess I'm coming from an agile environment and optimization just doesn't seem to be an issue these days, even with Python.) -Peter From pj at engr.sgi.com Sun Oct 20 20:35:37 2002 From: pj at engr.sgi.com (Paul Jackson) Date: 21 Oct 2002 00:35:37 GMT Subject: How do I invoke IE browser from Python on Mac OS X? Message-ID: How do I invoke Internet Explorer (or other package) from Python (or from a shell prompt for that matter) on Mac OS X. It seems that IE and other major apps on OS X are not single executable files, but a directory subtree called a package or bundle, as described for example at: http://developer.apple.com/technotes/tn/tn2015.html Technical Note TN2015 Locating Application Support Files under Mac OS X http://developer.apple.com/technotes/tn/tn1188.html Technical Note TN1188 Packages in Mac OS 9 -- -- I won't rest till it's the best ... Programmer, Linux Scalability Paul Jackson 1.650.933.1373 From pinard at iro.umontreal.ca Thu Oct 17 16:33:13 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: Thu, 17 Oct 2002 16:33:13 -0400 Subject: Python daemon In-Reply-To: (claird@starbase.neosoft.com's message of "25 Jun 2002 07:38:42 -0500") References: Message-ID: [Cameron Laird] > Roman Suzi wrote: >>3. restarting of the program if it fails, or the watchdog doesn't trigger >>Run the program from the /etc/inittab - if it terminates, init will >>restart it for you. > From everything I know, Roman's exactly right, that /etc/inittab is the > right way to set up a process that you truly want to keep running. > However, many, MANY Unix hosts have all kinds of ugly home-brewed hacks to > duplicate this functionality. I don't have an explanation, beyond the > rather tautologous observation that init(1) simply isn't as widely > understood as it deserves to be. For an application that you never turn off, `init' might be perfect indeed. It will re-spawn your application whenever it terminates, and even protect you against thrashing, if your application is broken and does not start. But you may want your application off at times, for maintenance say, maybe, without putting the whole system in maintenance mode. `init' is a bit limited as far as run levels are concerned, and that might be a reason why it is not much used for various persistent applications which are not close to the operating system itself. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From marklists at mceahern.com Sat Oct 5 08:41:37 2002 From: marklists at mceahern.com (Mark McEahern) Date: Sat, 5 Oct 2002 07:41:37 -0500 Subject: Which Linux distribution In-Reply-To: <77841980.1033828693@[10.10.1.2]> Message-ID: > I don't understand what your problem is since you > can install different versions of Python into distinct > locations. I run at least four or five different Python > versions under RH 7.3 without any problems. The key > to your success is to compile Python on your own and > use the configure --prefix=.... Doesn't `make altinstall` do the trick? // m From logistix at zworg.com Fri Oct 4 14:52:53 2002 From: logistix at zworg.com (logistix) Date: 4 Oct 2002 11:52:53 -0700 Subject: Windows NT remote registry import References: Message-ID: > Can Python import a registry file into a remote Windows NT machine? (I > have admin rights over the domain, so that isn't an issue.) > > If so, can anyone give me an example? > The win32 extentions list all of the registry functions under the win32api module. You use RegConnectRegistry() to grab a handle to the remote registry and then you can use the other Reg* functions to query and modify it. If you've never edited remote registries before, you'll also want to note that the only two "real" root keys are HKEY_LOCAL_MACHINE and HKEY_USERS. HKEY_CLASSES_ROOT is actually an alias to HKLM\Software\Classes and HKEY_CURRENT_USER is an alias to an entry under HKEY_USERS. So if you are trying to modify values under these keys, you'll need to adjust accordingly. From mikeb at mitre.org Fri Oct 18 15:03:51 2002 From: mikeb at mitre.org (Mike Brenner) Date: Fri, 18 Oct 2002 15:03:51 -0400 Subject: Win32 and Excel ranges Message-ID: <3DB05B17.CE84473@mitre.org> Larry Whitley wrote: > I've been going through Mark Hammond's book doing > his Python/Excel examples. It's working nicely but > I'm dissapointed with the performance of storing a > lot of data in the spread sheet cell by cell. It would be nice to access the spreadsheet a cell at a time, because that is our primary paradigms of spreadsheets, but the current COM implementation in Python makes that prohibitively expensive. One would have thought that it would have the same cost for Visual Basic and for Python, but Python has about the same cost for extracting one number from an Excel spreadsheet as it does for extracting 50,000 numbers, so you might as well take the whole spreadsheet at one time and do all the processing in Python. It is worse for extracting colors than than for extracting numbers because ranges can't be used. To extract the colors, I had python generate the following Visual Basic macro to place the colors (as numbers) into the cells, 100 columns to the right of the spreadsheet itself. After running this macro, a single Python call can extract the colors from those second hundred columns. (I used "rip" in the code at the bottom of this message. Sub Macro1() Dim offset As Integer Dim row As Integer Dim col As Integer Sheets("Artificial Placenta Electrophersis").Select Range("CU1:HA2100").Select Selection.ClearContents offset = 100 last_row = 1171 last_col = 75 For row = 1 To last_row For col = 1 To last_col Cells(row, col + offset).Value = Cells(row, col).Interior.Color Next col Next row End Sub Paul Casteels wrote: > This is something that works for me (using NumPy for the arrays) : > > xlApp = Dispatch("Excel.Application") > xlApp.Workbooks.Add() > xSheet = xlApp.ActiveWorkbook.ActiveSheet > xSheet.Range(xSheet.Cells(row,col), \ > xSheet.Cells(row+aLen-1,col+1)).Value = array > > My array is 2*8196 and the speed of this 1 line is also very low. > Does someone have other suggestions for speeding this up ? Here is the code that shows it also works with ordinary Python arrays. The RANGE is much faster than doing it one cell at a time. # junk1.py # create a dummy excel file called C:\\junk1.xls before running this from win32com.client import Dispatch xLApp = Dispatch("Excel.Application") xLBook = xLApp.Workbooks.Open("c:\\junk1.xls") xLBook.Worksheets("Sheet1").Select() xSheet=xLBook.ActiveSheet row=1; col=1; aLen=5 array=(("row 1 col A","row 1 col B"), ("row 2 col A","row 2 col B"), ("row 3 col A","row 3 col B"), ("row 4 col A","row 4 col B"), ("row 5 col A","row 5 col B")) xSheet.Range(xSheet.Cells(row,col), \ xSheet.Cells(row+aLen-1,col+1)).Value = array xLBook.Close(SaveChanges=1) # end of junk.py ================================================== # COMtools.py # import string import traceback import tools import types def com_project_saveas_example(directory): """ com_project_saveas_html_example saves the PROJECT files in a directory as html """ log("attempting to bring up PROJECT") global pApp from win32com.client import Dispatch pApp=Dispatch("MSProject.Application") log("brought up Project") pApp.Visible=1 os.chdir(directory) # pApp.ChangeFileOpenDirectory(directory) # for the button for pFile in os.listdir(os.getcwd()): if string.find(pFile,"mpp")>1: csvFile=pFile+".csv" pApp.Add(pFile) # pApp.Documents.Add(pFile) also fails pApp.ActiveDocument.SaveAs(csvFile,17) pApp.ActiveDocument.Close() print "Saved "+pFile+" as "+csvFile pApp.Quit() def com_word2html(directory, files): """ This works for Word 2000, but Word 2000 gives all sorts of complex htmls and xmls instead of a simple, naive html like Word 97 does. If you have both installed, then you have to use VB to get W97. """ # e.g. 3.5 inches=216 points from win32com.client import Dispatch import os os.chdir(directory) W = Dispatch("Word.Application") W.visible=1 W.ChangeFileOpenDirectory(directory) for file in files.keys(): infile,outfile,shortName=files[file] print "saving",file,"in=",infile,"out=",outfile Doc = W.Documents.Open(infile, ReadOnly=1) Doc.SaveAs(FileName=outfile, FileFormat=8) # web format print " SAVED AS WEB PAGE" Doc.Close() W.Quit() def com_word_saveas_html_example(directory): """ com_word_saveas_html_example saves the WORD files in a directory as html """ log("attempting to bring up Word") global wApp from win32com.client import Dispatch wApp=Dispatch("Word.Application") log("brought up Word") wApp.Visible=1 os.chdir(directory) wApp.ChangeFileOpenDirectory(directory) # for the button for WordFile in os.listdir(os.getcwd()): if string.find(WordFile,"doc")>1: htmlfile=WordFile+".html" wApp.Documents.Add(WordFile) wApp.ActiveDocument.SaveAs(htmlfile,17) wApp.ActiveDocument.Close() print "Saved "+WordFile+" as html "+htmlfile wApp.Quit() def com_zz_done(): from win32com.test.util import CheckClean CheckClean() import pythoncom pythoncom.CoUninitialize() from win32com.client import Dispatch import os class pyExcel: def __init__(self): self.filename=None self.currentSheet="No Sheet" try: self.xL = Dispatch("Excel.Application") except: raise "could not dispatch Excel.Application" def openFile(self,thisFile=None,closeFirst=1,visible=1, tracingCloses=0,tracingOpens=0): if self.filename!=None: if self.filename==thisFile: return elif closeFirst: if tracingCloses: print "closing Excel file",self.filename self.closeFile() if thisFile: self.filename=thisFile try: print "opening ",self.filename self.xLBook=self.xL.Workbooks.Open(thisFile) except: raise "could not open Excel workbook ["+thisFile+"]" else: self.filename="" try: self.xLBook=self.xL.Workbooks.Add() self.filename="unsaved, unnamed Excel Workbook" except: raise "could not open a blank Excel sheet" self.xL.Visible = visible def selectSheet(self,thisFile,thisSheet): self.openFile(thisFile) self.mbo(); self.currentSheet="" try: self.xLBook.Worksheets(thisSheet).Select() if 0: self.xL.Sheets(name).Select() except: traceback.print_stack() raise "problem selecting Excel sheet "+thisSheet+" in "+thisFile self.currentSheet=thisSheet def closeFile(self): self.mbo() if self.filename: try: self.xLBook.Close(SaveChanges=0) except: print "problem closing Excel file "+self.filename self.filename=None del self.xLBook def close(self): if self.filename!=None: self.closeFile() self.xL.Quit() del self.xL # # Utility Methods # def mbo(self): if self.filename==None: raise "must be open: Open a spreadsheet first" # # Spreadsheet Operations # def cell(self,row,col): # WARNING: This is VERY slow. Use rip to get # a whole block at a time. This procedure takes # the same amount of time on ONE cell as # RIP takes on a whole spreadsheet with 10,000 # cells, because the COM overhead is constant # and VERY high. self.mbo() try: u=self.xL.ActiveSheet.Cells(row,col).Value except: traceback.print_stack() print print "COULD NOT GET CELL(row=",row,", col=",col,\ "from sheet",self.currentSheet raise return self.strip(u) def setCell(self,row,col,value): self.mbo() self.xL.ActiveSheet.Cells(row,col).Value=value if 0: self.xL.ActiveWorkbook.ActiveSheet.Cells(row,col).Value = value def cell_color(self,row,col): # WARNING: EXTREMELY slow. Instead, use a VB macro # to put the COLORS into a different block of cells # as the VALUE of those new cells. Then read in the # values of those new cells in a single block using rip. self.mbo() return self.xL.ActiveSheet.Cells(row,col).Interior.Color def cell_border(self,row,col): # WARNING: EXTREMELY slow. Instead, use a VB macro # to put the BORDERS into a different block of cells # as the VALUE of those new cells. Then read in the # values of those new cells in a single block using rip. self.mbo() return self.xL.ActiveSheet.Cells(row,col).Borders(9).Color def rip(self, fileName, sheetName, rectangle): row1, col1, row2, col2=rectangle self.selectSheet(fileName, sheetName) self.mbo() S=self.xL.ActiveWorkbook.ActiveSheet x=S.Range(S.Cells(row1,col1),S.Cells(row2,col2)).Value2 # Value2 turns data objects into floating point numbers try: L=len(x) except TypeError: print print "COMtools.rip: Got a TypeError taking len(x)," print " the array coming back from Range.Value" print "type(x)=",type(x) traceback.print_stack() print "x=",x raise y=[] for row in range(len(x)): R=[element for element in x[row]] y.append(map(tools.phrase_unicode2string, R)) if row1==row2: return y[0] # one-dimensional array (a row) if col1==col2: return [y[i][0] for i in range(len(y))] # one_dimensional array (a column) return y # two_dimensional array def save(self): self.mbo() self.xLBook.Save() def saveAs(self,filename): self.mbo() self.filename=filename self.xLBook.SaveAs(filename) From tim.one at comcast.net Wed Oct 2 21:21:54 2002 From: tim.one at comcast.net (Tim Peters) Date: Wed, 02 Oct 2002 21:21:54 -0400 Subject: [Python-Dev] PEP239 (Rational Numbers) Reference Implementation and new issues In-Reply-To: <200210030020.g930KBT06090@pcp02138704pcs.reston01.va.comcast.net> Message-ID: [Andrew Koenig] > Much as I like APL, I'd rather use Scheme's numeric model. [Guido] > I've heard that before, but I've also heard criticism of Scheme's > numeric model. "It works in Scheme" doesn't give me the warm fuzzy > feeling that it's been tried in real life. We've been thru this before too , but it doesn't even work in Scheme -- the Scheme std is too permissive in what it allows conforming implementations to get away (rationals aren't required; unbounded ints aren't required; ints *period* aren't required; while an "exact" flag is required, it has no portable mandatory semantics outside the (also undefined) range of numbers needed to index vectors; etc). Real number-crunchers have no use for it even in a full implementation, as it doesn't have a way to force precision-vs-space tradeoffs without extending the language. There's a reason the NumPy folks never bug you for Scheme features . From johnroth at ameritech.net Thu Oct 10 07:40:49 2002 From: johnroth at ameritech.net (John Roth) Date: Thu, 10 Oct 2002 07:40:49 -0400 Subject: Why is del(ete) a statement instead of a method? References: <3DA3EBE8.2030008@Linux.ie> Message-ID: "Tim Roberts" wrote in message news:hg6aqug7cubnsg45tf1cadtdia9vql2gjk at 4ax.com... > Padraig Brady wrote: > > > >Being a python newbie myself this strck me as a little inconsistent. > > > >why can't you do: > > > >l=[1,2,3] > >s="123" > >i=123 > > > >l[1].del() > >l.del() > >s.del() > >i.del() > > The way I see it, THOSE are inconsistent. Think about it in an > object-oriented way. It doesn't make sense to ask an object to "delete" > itself, because the object isn't in control of where it is stored. You > have to ask the OWNER of the object to do the delete. It's the OWNER that > has to take an action. Thus, something like "l.del([1])" would be a bit > more consistent. It isn't even an OO issue. It's a binding issue. If you let an object delete itself, you risk having dangling pointers all over the place. So the first example is legitimate: it's asking the container object to delete one of the elements in the container. The other two examples aren't. However, there's another issue here, although it's also an inconsistency. Delete in the first example is the inverse of insert or append, right? Insert is done with special assignment syntax that also allows deletion. Append, however, is a method that does one very strange thing: it returns None instead of the object, so it can't be chained properly. Adding a .delete method would simply exascebrate this assymetry. John Roth From vtail at yandex.ru Tue Oct 1 03:53:13 2002 From: vtail at yandex.ru (vtail) Date: 1 Oct 2002 00:53:13 -0700 Subject: McMillian installer + win32com.client.constants - how to use them together? References: <9ff6b66.0209300856.5fcdf961@posting.google.com> Message-ID: <9ff6b66.0209302353.7181f16b@posting.google.com> "Steve Holden" wrote in message news:... > Gordon MacMillan reads this list when he has time, but you should be aware > that there is a mailing list just for the users of the installer package -- > see > > http://trixie.triqs.com/mailman/listinfo/installer > > for details. Thank you for the link, Steve, I will crosspost my message to this list. I've studied full archive of this list but was unable to find anything related to my problem. > I'm *guessing* that the installer hasn't been able to define that the > win32com.client package's submodules need to be included. To verify this is > the error you might try including an explicit > > import win32com.client.constants > > in the appropriate module and see if the error goes away. There are things > you can do in installer if that's the case, but I'm not the best person to > advise. I think about it, but constants is not a subpackage actually - it's an instance of Constants class defined in module win32com/client/__init__.py. So your suggestion doesn't work. Anyway, thank you very much for your help. Victor. From cnetzer at mail.arc.nasa.gov Tue Oct 8 16:02:31 2002 From: cnetzer at mail.arc.nasa.gov (Chad Netzer) Date: Tue, 8 Oct 2002 13:02:31 -0700 Subject: strange option menu behavior In-Reply-To: References: Message-ID: <200210082002.NAA18430@mail.arc.nasa.gov> On Tuesday 08 October 2002 03:15, Heiner Litz wrote: > HI there! > > I implemented a option menu like this: > > var=Tkinter.StringVar() > var.set("adjective") > option=Tkinter.OptionMenu(framenewentry3, var, "adjective", "adverb", > "compound", "conjunction") > option.pack() Works for me: ~~~~~~~~~~~~~~~ import Tkinter root=Tkinter.Tk() var=Tkinter.StringVar() var.set("adjective") option=Tkinter.OptionMenu(root, var, "adjective", "adverb", "compound", "conjunction") option.pack() root.mainloop() ~~~~~~~~~~~~~~~~ You are running the mainloop(), right? -- Chad Netzer cnetzer at mail.arc.nasa.gov From gerhard.haering at opus-gmbh.net Thu Oct 31 05:29:37 2002 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 31 Oct 2002 10:29:37 GMT Subject: Python documentation in DocBook References: <3dbc45dc$0$63807$e4fe514c@dreader1.news.xs4all.nl> <3dbc51df@news.sentex.net> <87y98f566d.fsf@zamazal.org> Message-ID: Martin v. L?wis [2002-10-31 10:15 GMT]: > Milan Zamazal writes: > >> Much less painful conversion to the other very useful formats, like >> Info? > > Not if it is DocBook. You would need a custom processor for that. I don't quite understand what you mean by a custom processor. There already are many of these for the various formatas, including TexInfo, Windows Help, RichText, PDF, PostScript and HTML. [http://docbook2x.sourceforge.net/] | docbook2X converts DocBook documents into man pages and Texinfo documents. Only HTML can be created without any "custom processor" - it's possible to use the XML stylesheets for that. -- Gerhard From pu at myRealBox.com Sun Oct 20 15:48:45 2002 From: pu at myRealBox.com (pu) Date: Sun, 20 Oct 2002 21:48:45 +0200 Subject: pymqi build for W2K-MQ5.2 Message-ID: <3db307c7_2@news.vo.lu> Hi all, as I don't have a C compiler installed, has anybody done this build so that I could download it? Many thanks in advance, -PU From jepler at unpythonic.net Sat Oct 5 09:20:55 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Sat, 5 Oct 2002 08:20:55 -0500 Subject: isFloat: Without Exception-Handling In-Reply-To: <200210050319.UAA03364@mail.arc.nasa.gov> References: <200210050105.SAA23038@mail.arc.nasa.gov> <20021004213126.D10850@unpythonic.net> <200210050319.UAA03364@mail.arc.nasa.gov> Message-ID: <20021005082045.A941@unpythonic.net> On Fri, Oct 04, 2002 at 08:19:44PM -0700, Chad Netzer wrote: > On Friday 04 October 2002 19:31, Jeff Epler wrote: > > On Fri, Oct 04, 2002 at 06:05:19PM -0700, Chad Netzer wrote: > > > > def isFloat(s): > > > try: return float(s) or True > > > except (ValueError, TypeError), e: return False > > > > You mean > > def isFloat(s): > > try: return (float(s), True)[1] > > except (ValueError, TypeError), e: return False > > Is there any instance when these will be different? I assume float() will > always return type< float >, and so not overload the 'and'. In which case, > my version doesn't have to construct a tuple (so possibly it's faster). > > Just curious; for the specific case and'ing with a float, I can't think where > mine might go wrong (not off the top of my head, anyway). The short-circuiting "and" and "or" operators cannot be overloaded. For 'or', the LHS is evaluated. If it is not false, then that is the result of the expression. Otherwise, the RHS is evaluated and is the result of the expression. So 'isFloat(math.pi) or True' will return a non-false value, but it won't return True. Let's compare the version with try: return float(s) or True # if1 3 LOAD_GLOBAL 0 (float) 6 LOAD_FAST 0 (s) 9 CALL_FUNCTION 1 12 JUMP_IF_TRUE 4 (to 19) 15 POP_TOP 16 LOAD_GLOBAL 2 (True) >> 19 RETURN_VALUE to the version with try: # if2 float(s) return True 3 LOAD_GLOBAL 0 (float) 6 LOAD_FAST 0 (s) 9 CALL_FUNCTION 1 12 POP_TOP 13 LOAD_GLOBAL 2 (True) 16 RETURN_VALUE This second version doesn't try to be clever, but it will always return True (never values like 'math.pi') and the code is also an instruction shorter than your clever code above. Of course, in the common case (s represents a nonzero float) your version executes one less bytecode instruction. So, on with the timings: [jepler at anchor jepler]$ python t.py # function / argument / time 0.0 13.2162970304 1.0 13.1347409487 0.0 13.0910500288 1.0 13.0951679945 [jepler at anchor jepler]$ python -O t.py # function / argument / time 0.0 12.3858759403 1.0 12.3613350391 0.0 12.4040540457 1.0 12.3739790916 Jeff From eugene1977 at hotmail.com Sun Oct 13 22:00:45 2002 From: eugene1977 at hotmail.com (eugene kim) Date: Mon, 14 Oct 2002 02:00:45 +0000 Subject: improved hyperlink parser in python? References: Message-ID: forgot to mention this site doesn't even get reached with error http://radio.weblogs.com/0106346 Traceback (most recent call last): File "bloglog.py", line 36, in ? p.feed(file.read()) File "/usr/local/lib/python2.2/sgmllib.py", line 95, in feed self.goahead(0) File "/usr/local/lib/python2.2/sgmllib.py", line 161, in goahead k = self.parse_declaration(i) File "/usr/local/lib/python2.2/markupbase.py", line 66, in parse_declaration decltype, j = self._scan_name(j, i) File "/usr/local/lib/python2.2/markupbase.py", line 313, in _scan_name self.error("expected name token") File "/usr/local/lib/python2.2/sgmllib.py", line 102, in error raise SGMLParseError(message) sgmllib.SGMLParseError: expected name token From aleax at aleax.it Thu Oct 10 05:29:07 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 10 Oct 2002 09:29:07 GMT Subject: [OT} How to un-GPL parts of a GPL'd module. References: Message-ID: Lulu of the Lotus-Eaters wrote: ... > if you don't realize it immediately. It's always *things* that we are > interested in utilizing for various purposes--even if those things have > the fairly ethereal form of charges on a platter. Nope, it's always _services_ -- even if those services are cheapest or most practical to purchase as embodied in 'things'. You can't really frame, in terms of "it's always *things*", such "utilizing" as enjoying a theatrical performance, a haircut, etc; the alternative framing of "it's always _services_" has its sticky spots (when "things" are _consumed_ in the process of "utilizing" -- bottle of wine being the classic example) but requires a tad less mirror-climbing than "it's always *things*" if you're keen for a GUT one way or another. The key difference is in how you frame gray areas: the services-frame helps you view "I purchase a car" as "I purchase a bundle of services (embodied, for cheapness/practicality, in a thing)" and analyze the bundle -- e.g. focusing just on transportation services, "convenient transportation of self, others and goods from point A to point B at any time without needing pre-arrangements in each case" might then be further analyzed in terms of possible unbundling (would abundant taxis available at any time supply a superior service, by avoiding the chore of driving, or an inferior one, by removing the joy of driving? -- etc). While framing every purchase (&c) as one of services is clearly an oversimplification, albeit somewhat of a lesser one wrt that of framing every purchase (&c) as one of things, I think it's far more fruitful for most purposes -- particularly when you're trying to design and put together novel bundles and/or market then, but not only then... _My_ criticism of A. Smith is that he could not conceive of services in such a generalized way -- as the core of all economic activity, the true Wealth of Nations. But considering how many, 230 years later, STILL have problems with the notion, it has to be a very muted and respectful criticism:-). Alex From =?iso-8859-5?Q?=DF=D5=DD=D3=E3=D8=DD=D8=E1=E2=D0?= at =?iso-8859-5?Q?=DC=D0=D8=DB?=.=?iso-8859-5?Q?=DD=D5=E2?=.=?iso-8859-5?Q?=DC=DA?= Thu Oct 10 15:29:11 2002 From: =?iso-8859-5?Q?=DF=D5=DD=D3=E3=D8=DD=D8=E1=E2=D0?= at =?iso-8859-5?Q?=DC=D0=D8=DB?=.=?iso-8859-5?Q?=DD=D5=E2?=.=?iso-8859-5?Q?=DC=DA?= (=?iso-8859-5?Q?=B4=D0=DC=F8=D0=DD_=B3=2E?=) Date: Thu, 10 Oct 2002 21:29:11 +0200 Subject: which outgoing network device/IP is used? References: <3da4ac9b$0$169$9b622d9e@news.freenet.de> Message-ID: <3da5d4fc$1@news.mt.net.mk> > if a computer has more network devices I want to know which one (IP) is used > for a outgoing socket connection to a certain remote host. (in order to > 'bind/accept' later on that IP for an incoming connection request) sc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sc.connect(('www.google.com', 80)) sc.getpeername() # google's IP and port sc.getsockname() # yours IP and port -- ?????? There are three kind of lies: lies, damn lies and benchmarks. From mhammond at skippinet.com.au Tue Oct 8 08:32:32 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Tue, 08 Oct 2002 12:32:32 GMT Subject: PyErr_Occurred() and debugging References: Message-ID: Max wrote: > Hi! > I try to debug a python script embedded in a vc++ win32 app. > I need to catch exceptions and print the error message with the traceback. > > if(PyErr_Occurred()){ > PyErr_Print(); > return; > } > > Now, I have two questions... > How can I redirect the error to the vc debug panel? It is a PITA from C++ code. I can direct you to c++ which could do it, but a better way is to get Python itself to do it. Have your main entry point function do something like: try: do_the_real_thing() except: file=StringIO.StringIO() traceback.print_exc(file=file) win32api.OutputDebugString(file.get_value()) > Is it possible to debug the python script in plain text, like in PythonWin? > I mean... I have the Update method called by c++ code: Nope :( Mark. From paul at boddie.net Thu Oct 10 06:26:31 2002 From: paul at boddie.net (Paul Boddie) Date: 10 Oct 2002 03:26:31 -0700 Subject: DBI cursor behaviour with multiple statements? References: <7e964d1d.0209270137.568a3f3@posting.google.com> <23891c90.0209300554.5b37c195@posting.google.com> <7e964d1d.0210010652.5b8768de@posting.google.com> <23891c90.0210020458.e69b4fd@posting.google.com> <7e964d1d.0210090210.724589c5@posting.google.com> Message-ID: <23891c90.0210100226.67411f7a@posting.google.com> Henrik.Weber at sys.aok.de (Henrik Weber) wrote in message news:<7e964d1d.0210090210.724589c5 at posting.google.com>... > > In the last few days I have made some experiments with ADO and the Jet > OLE DB provider. They seem to understand several syntax styles for > parameters more or less directly. For the rest I think it is possible > to reformat the query string. Alright, I'll make the paramstyle user > configurable. It was just a suggestion, but the pyformat paramstyle is misleading, in my opinion, and should not have been proposed by the DB-API specification. [...] > No reason to apologise. Basically I was under that illusion. I hadn't > given much thought to parameters when I posted my first message. Well, > I got answers for two questions by posting only one. That's pretty > efficient ;-) Usually I give no answers and people somehow work it out by themselves, so you've made me work harder than usual. ;-) > > SELECT * FROM table WHERE column IN :1 > > Would you also expect the database module to know to place parentheses > around the placeholder? The Jet Provider complains about them missing, > so the user at least has to write: > > SELECT * FROM table WHERE column IN (:1) That's an interesting point, but it could well be an artifact of the SQL parser used in the Jet stuff. I would expect parentheses to be used to indicate an expression or a sequence, where the sequence would possibly have more than one comma-separated value. Perhaps, the Jet implementation specifically treats the content of the parentheses as a sequence in this particular case, but the binding mechanism only supports single values. There are certainly many possible explanations, but only one of them is correct. ;-) > The Jet OLE DB provider does not like lists or tuples as parameters > directly. What might work is to try to bind the parameter. When the > attempt fails determine if the parameter is a sequence and if so > replace the placeholder with a number of new placeholders depending on > the length of the sequence. Then the elements of the sequence could be > bound one by one to the new placeholders. Yes, this would be a good fallback technique that could be useful in other database modules, too. (Weak hint to other module maintainers!) > Thanks for your input. It will help me address some issues I'm just > now starting to come across. I've never actually written a proper database module, but I have modified and debugged one or two, and I did once start an iODBC wrapper. In these days of Pyrex, it's tempting to give it another shot instead of using SWIG. Still, it's good that you find this discussion useful. Paul From daniel0603 at me-barie.de Mon Oct 14 15:14:39 2002 From: daniel0603 at me-barie.de (=?ISO-8859-15?Q?Daniel_Bari=E9?=) Date: Mon, 14 Oct 2002 21:14:39 +0200 Subject: string to float, putting in list/tuple Message-ID: <3DAB179F.6070200@me-barie.de> Hello, when programming in Python, I stumbled over the following: Let's assume, I've got four strings, Sl = '0.03169', SS31 = '-3.01', SS41 = '-3.01'. Now I want to convert these to float, using the builtin float() function. The results are quite as expected: float(Sl) = 0.03169, float(SS31) = -3.01, float(SS41) = -3.01. But when stuffing a list with these floats the result is not as I expect it to be: [0.031690000000000003, -3.0099999999999998, -3.0099999999999998] What happened? Cheers, Daniel Bari? P. S.: Python 2.2 (#1, Apr 12 2002, 15:29:57) [GCC 2.96 20000731 (Red Hat Linux 7.2 2.96-109)] on linux2 From kp at kyborg.dk Tue Oct 15 12:57:48 2002 From: kp at kyborg.dk (Kim Petersen) Date: Tue, 15 Oct 2002 18:57:48 +0200 Subject: Howto generate a metafunction? [Python 1.5.2] Message-ID: <3DAC490C.6080009@kyborg.dk> The below code should give an idea of what i want? from Tkinter import * class MListbox(Frame): def __init__(self,master,count=1,cnf={},**args): Frame.__init__(self,master,cnf) self.listboxes=[] for i in range(count): self.listboxes.append(Listbox(self,command=self._docommand)) self.listboxes[-1].grid(row=0,column=i) self.yview=self.Metafun(Listbox.yview) self.yview_fraction=self.Metafun(Listbox.yview_fraction) ... def Metafun(self,fun): # How do i generate this one - to apply this function to every # element in self.listboxes? # - please no listcomprehensions and no def in def # since i'm bound in this one to 1.5.2 # # . metafun should take any amount of args (*arg) # . metafun applies fun to every element in self.listboxes pass From aleax at aleax.it Wed Oct 2 10:50:31 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 02 Oct 2002 14:50:31 GMT Subject: Love "Python Cookbook" References: <3d9b05b5$0$220$4d4ebb8e@news.nl.uu.net> Message-ID: Gumuz wrote: > is this a printed version of the Activestate Python Cookbook or is this > something different? It's a _vastly edited_ printed version of recipes from the online Cookbook, with corrections and updates to the programs, much added discussion, many additional recipes, AND fourteen chapter intros by thirteen different authors (Tim Peters did two chapter intros). I think the printed version (or the online one on Safari -- same thing, though I personally prefer paper) has substantial added value wrt the online one... or I wouldn't have spent about 9 months of my life as a co-editor helping to make it happen (I'd have been content to be among the most prolific contributors of recipes to the online one:-). We had to set a cut-off date to get recipes from the online site for the book, and of course the site has accumulated many more recipes since (even though I didn't contribute any more there as I was too busy with co-editing &c:-). Thus, both the book and the site can be now considered to be "added value" wrt each other in different ways:-). Alex From max at alcyone.com Wed Oct 9 19:37:32 2002 From: max at alcyone.com (Erik Max Francis) Date: Wed, 09 Oct 2002 16:37:32 -0700 Subject: How to logout from a Python Program? References: Message-ID: <3DA4BDBC.27FA2B20@alcyone.com> Saqib Ali wrote: > How can I force a logout from a python program? > > I tried os.system("exit") but this only terminates the shell within > which my application is running (which starts with the #! on the first > line). Is it possible for me to logout "all the way" in python? sys.exit() -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ When you talk to her / Talk to her \__/ India Arie CSBuddy / http://www.alcyone.com/pyos/csbuddy/ A Counter-Strike server log file monitor in Python. From cnetzer at mail.arc.nasa.gov Fri Oct 4 23:19:44 2002 From: cnetzer at mail.arc.nasa.gov (Chad Netzer) Date: Fri, 4 Oct 2002 20:19:44 -0700 Subject: isFloat: Without Exception-Handling In-Reply-To: <20021004213126.D10850@unpythonic.net> References: <200210050105.SAA23038@mail.arc.nasa.gov> <20021004213126.D10850@unpythonic.net> Message-ID: <200210050319.UAA03364@mail.arc.nasa.gov> On Friday 04 October 2002 19:31, Jeff Epler wrote: > On Fri, Oct 04, 2002 at 06:05:19PM -0700, Chad Netzer wrote: > > def isFloat(s): > > try: return float(s) or True > > except (ValueError, TypeError), e: return False > > You mean > def isFloat(s): > try: return (float(s), True)[1] > except (ValueError, TypeError), e: return False Is there any instance when these will be different? I assume float() will always return type< float >, and so not overload the 'and'. In which case, my version doesn't have to construct a tuple (so possibly it's faster). Just curious; for the specific case and'ing with a float, I can't think where mine might go wrong (not off the top of my head, anyway). -- Chad Netzer cnetzer at mail.arc.nasa.gov From massimo.lamanna at cern.ch Thu Oct 3 05:48:42 2002 From: massimo.lamanna at cern.ch (Massimo) Date: 3 Oct 2002 02:48:42 -0700 Subject: execfile question: name of the files being executed Message-ID: Hi, I'm trying to get the equivalent information I have in Perl with the $0 or $PROGRAM_FILE variable: the name (full path) of the script I'm executing via execfile() from inside the script itself. Thanx, Massimo From phr-n2002b at NOSPAMnightsong.com Tue Oct 8 17:10:44 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 08 Oct 2002 14:10:44 -0700 Subject: [OT} How to un-GPL parts of a GPL'd module. References: Message-ID: <7xofa463hn.fsf@ruckus.brouhaha.com> anton at vredegoor.doge.nl (Anton Vredegoor) writes: > how can I use a class or a function from a GLP'd module (cut-and-paste > style) in a module with BSD or public domain style release? Release the modified BSD-licensed module under the GPL. The BSD license allows you to do that. > I guess I could e-mail the author for permission but if I would have > to wait for them to answer, it would slow my coding process down to a > snail's pace, and there's always the possibility of the author being > unwilling. Correct. Also, if there are multiple contributors, you have to get permission from all of them. > So that's not an option for me. I would rather rethink the problem and > start writing a new script. That is the correct thing to do if you can't or won't release the combined result under the GPL. > But here's where the problem begins. Having seen the algorithm it's > almost impossible for me to forget it and write code as if I had never > seen it. On the other hand, is it enough to just cut and paste, change > maybe a few variable names, credit the author for the original concept > in the sourcode, send some email to inform the author and go on with > life? No. > I know a lot of people rely on writing sourcecode for a living but I > have been unemployed as a programmer for so long know that the concept > of owning sourcecode or getting payed for producing it is completely > alien to me. I think I'll be writing free sourcecode till I die just > hoping some pieces of my code will survive into eternity. Me too, which is why I GPL the free code that I write. I want the source code to be available to all users. It is not up to anyone else to substitute their decision for mine in that matter. If someone takes GPL code that I wrote and re-licenses it without my permission, I'm going to have a big problem with it. At first it sounded like you wanted to use a GPL'd component in a non-free program. But now I see you're writing a free program, so why not use the GPL? From mwh at python.net Wed Oct 2 10:31:14 2002 From: mwh at python.net (Michael Hudson) Date: Wed, 2 Oct 2002 14:31:14 GMT Subject: newbie: find position of item in a list References: <3D9B01B4.4000700@stacom-software.de> Message-ID: Alexander Eisenhuth writes: > Hallo Again, > > i wonder weather there is no expression of finding the position of a element is a list like: > > l = ['a', 'b', 'c', 'd', 'e'] > > l.find('b') > >> 1 > > Have I overseen something in the documentation to python ? .index()? M. -- I have no disaster recovery plan for black holes, I'm afraid. Also please be aware that if it one looks imminent I will be out rioting and setting fire to McDonalds (always wanted to do that) and probably not reading email anyway. -- Dan Barlow From chris.gonnerman at newcenturycomputers.net Tue Oct 1 21:21:09 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Tue, 1 Oct 2002 20:21:09 -0500 Subject: Decimal arithmatic, was Re: Python GUI app to impress the boss? References: <7xd6qwqtgz.fsf@ruckus.brouhaha.com> <7xvg4mlat2.fsf@ruckus.brouhaha.com> <7xu1k57nrn.fsf@ruckus.brouhaha.com> Message-ID: <002701c269b2$05c532a0$ba01010a@local> ----- Original Message ----- From: "Paul Rubin" > I haven't yet seen a complete definition of "right", so I > have no way to prove or disprove that the rounding function > above always gives the "right" answer. How complete do you need? All arithmetic rounding, whenever it is performed, must produce results entirely and exactly equal to the results achieved when doing the same arithmetic *in decimal*, by hand, on paper, following one of the standard rounding rules. There are two such rules used in the US, "classic" and "banker's." For most business purposes, "classic" rounding ( >= 0.5 up, < 0.5 down) is the expected mode, but in an ideal world either should be available. In other words, 0.7 * 0.05 should always be 0.035, and never 0.034999... It's really simple. For monetary purposes, anyone with a (successful) eighth-grade education or equivalent should be able to do the math on paper (or do they even teach that anymore?) and not be surprised by the computer's results. If this isn't a good enough definition of "right" for you, please tell me what, exactly, is wrong with it. What do you need to understand the problem? Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From martin at v.loewis.de Tue Oct 15 02:53:11 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 15 Oct 2002 08:53:11 +0200 Subject: mod_python and xml.dom.minidom problem References: <3DAB182B.9000201@remove.yahoo.co.uk> <3DAB2C4D.5040602@remove.yahoo.co.uk> <3DAB41F8.1080308@remove.yahoo.co.uk> Message-ID: Tom writes: > > xml.parsers.expat.pyxml_expat_version > > this doesn't appear to exist but, That seems to be the problem: You somehow have an old pyexpat module. Please make sure you recompile pyexpat from the sources that are included in PyXML 0.8 (or whatever version you are using). Regards, Martin From donkan7 at yahoo.com Wed Oct 16 07:29:56 2002 From: donkan7 at yahoo.com (Richard Bow) Date: Wed, 16 Oct 2002 04:29:56 -0700 Subject: How to print an integer with commas; E.g., 3,056,789 Message-ID: Given any integer n, how can I convert str(n) to a string with commas in the appropriate places? For example, if n is 3056789, I'd like to convert str(3056789) to "3,056,789", for better readability of output. Thanks, Richard Bow From jeremy at alum.mit.edu Wed Oct 16 13:07:44 2002 From: jeremy at alum.mit.edu (Jeremy Hylton) Date: 16 Oct 2002 10:07:44 -0700 Subject: instance introspection and __slots__ References: Message-ID: mertz at gnosis.cx (David Mertz, Ph.D.) wrote in message news:... > I'm probably just being daft here... but would you show me an object > that has both __dict__ and __slots__? Python2.3: >>> class Foo(object): ... __slots__ = "slot" ... >>> class Bar(Foo): ... pass ... >>> b = Bar() >>> b.__slots__ 'slot' >>> b.slot = 2 >>> b.frob = 1 >>> b.__dict__ {'frob': 1} >>> import pickle >>> pickle.dumps(b) Traceback (most recent call last): File "", line 1, in ? File "/usr/local/lib/python2.3/pickle.py", line 1063, in dumps Pickler(file, bin).dump(object) File "/usr/local/lib/python2.3/pickle.py", line 167, in dump self.save(object) File "/usr/local/lib/python2.3/pickle.py", line 241, in save tup = reduce() File "/usr/local/lib/python2.3/copy_reg.py", line 68, in _reduce dict = getstate() TypeError: a class that defines __slots__ without defining __getstate__ cannot be pickled From john.burton at jbmail.com Fri Oct 18 16:30:16 2002 From: john.burton at jbmail.com (John Burton) Date: Fri, 18 Oct 2002 21:30:16 +0100 Subject: Idiom for 'the lesser of the two'? References: Message-ID: "Gordon Airport" wrote in message news:A6udnSqYRcfk-C2gXTWcqA at comcast.com... > There's got to be something simple I'm missing... > You obviously can't do > a < b ? a : b > and this > a if a < b else b > is a syntax error. I started playing with lambda functions > but I didn't have any luck there either. min(a,b) From jepler at unpythonic.net Fri Oct 4 22:31:26 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Fri, 4 Oct 2002 21:31:26 -0500 Subject: isFloat: Without Exception-Handling In-Reply-To: <200210050105.SAA23038@mail.arc.nasa.gov> References: <1033778288.319397@smirk> <200210050059.RAA19373@mail.arc.nasa.gov> <200210050105.SAA23038@mail.arc.nasa.gov> Message-ID: <20021004213126.D10850@unpythonic.net> On Fri, Oct 04, 2002 at 06:05:19PM -0700, Chad Netzer wrote: > On Friday 04 October 2002 17:59, I wrote: > > > This works better, but does extra work: > > Duh, Chad! Just change "and" to "or": > > def isFloat(s): > try: return float(s) or True > except (ValueError, TypeError), e: return False > You mean def isFloat(s): try: return (float(s), True)[1] except (ValueError, TypeError), e: return False Jeff From thorsten at thorstenkampe.de Mon Oct 7 08:55:41 2002 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Mon, 7 Oct 2002 14:55:41 +0200 Subject: Merging lists has made my brain hurt. References: <3D9B1953.3030109@moving-picture.com> Message-ID: * Alex Martelli > Thorsten Kampe wrote: >> Treating lists a priori as sets for reasons of speed is definitely >> not the way to go because you're "losing information". I think it's >> better > > Of course, you have to know which information matters. I meant this: in a real world scenario it's often not practical to say: use this program, but beware, it's relies on an input without duplicates or relies on all items to be hashable, because you can't tell in advance whether the conditions will be met. Not for the example you were answering of course but for a general purpose 'intersection program'. >> to treat them as tuples (in a mathematical sense) whereby you can >> always delete 'duplicates' afterwards if you don't care about them. > > If you don't care about duplicates you're much better off > normalizing first, and if you care about COUNT of duplicates but not > ordering (i.e., a bag) you're generally still better off normalizing > first. What do you mean exactly by "normalizing"? >> Example: What's the intersection between [2, 1, 2, 3, 2] and [0, 1, >> 2, 3, 2, 4]? An intersection (union, symmetric difference) of >> tuples can only be meaningful for the /corresponding/ items of the >> tuples/lists, so it's neither [2, 1, 3] nor [2, 1, 2, 3, 2] but [2, >> 1, 2, 3]. > > But why not [1, 2, 3, 2] instead? I know of no algebras defining > operations called intersection &c that are not commutative. Sorry, I wrote quite imprecisely. My interpretation of 'tuple' was contradictory to the traditional mathematical meaning 'order and repetition counts' but it meant "repetition counts, order doesn't". > What you mean by "corresponding" there is rather mysterious to me, > but wouldn't it mean "same item in the SAME position"? I was asking myself: what would be a sensible generalization for the common set operations (intersection, union, etc.) for tuples? Precisely: what is (or should be) the intersection of [2, 2] and [2, 2, 2]? Treat them as sets? Then the result is '[2]'. Treat them as tuples? The most common algorithm is: for each item in first seq: if it is in second seq, then add it to the intersection. But then: intersect([2, 2], [2, 2, 2]) = [2, 2] intersect([2, 2, 2], [2, 2]) = [2, 2, 2] You "connect" the "corresponding" items (the first '2' in seq1 with the first in seq2, the second '2' in seq1 with the second '2' in seq2, the third '2' in seq1 with the third '2' in seq2 ... *ooops*) [1, 2, 2, 2, 3] | | | | <- "non proportional font required" [0, 1, 2, 2, 3, 4] So the intersection should contain all the items that can be "paired"/"connected". The last '2' of seq2 has no 'partner' so it shouldn't be part of the intersection. >> I tried to write a reliable (though maybe slow) program that takes >> care of this issue (especially that intersection is _commutative_): > > But it's NOT -- [1, 2, 3, 2] != [2, 1, 2, 3]. You're losing > information, specifically order information. A correct definition > should be: > > def intersect(seq1, seq2): > return [ x for x, y in zip(seq1, seq2) if x == y ] This is correct for "if first item of seq1 = first item of seq2" but I had never use for such an "intersection". I could not see any "real use" for intersect([1, 2, 3], [3, 1, 2]) = []. > If what you want is to treat sequences as BAGS, then they're better > represented by dicts again -- order is the only information present > in a list and not in a dict, [...] Well, usually not: >>> {1: 2, 1: 2} == {1:2} 1 >>> [2, 2] == [2] 0 > So to do extensive processing of seqs-as-bags have converter funcs: > > def seqToBag(seq): > bag = {} > for item in seq: bag[item] = 1 + bag.get(item, 0) > > def bagToSeq(bag): > return [ x for key in bag for x in [key]*bag[key]] > > and for example "intersection" of bags then becomes, e.g: > > def intersectBags(bag1, bag2): > result = {} > for item in bag1: > count = min(bag1[item], bag2.get(item, 0)) > if count>0: result[item] = count ^^^^^^^^^^^ <- this is superfluous IMO > return result Yes, definitely better than my "append to result, remove from original list to prevent item being counted twice" version. And a lot faster (except for the abnormal "very large seq0, very small seq1" case). This is what I made of your code (it's a little optimized compared to my previous version so that the loop goes always through the smaller sequence.) I didn't change the 'union' and "symmetric difference" part because you have to loop through count0 *and* count1. #v+ def boolean(seq0, seq1, boolean_modus): """" perform 'and', 'not', 'or', or 'xor' operation on sequences """ ## auxiliary functions def tocount(seq): # convert to dict where key is the hashable representation count = {} # of the object and value is the object count for item in seq: count[repr(item)] = count.get(repr(item), 0) + 1 return count def toseq(count): # convert back to sequence return [item for key in count for item in [eval(key)] * count[key]] if boolean_modus == 'and': # intersection count0 = tocount(seq0) count1 = tocount(seq1) if count0 > count1: # loop through the shorter list count0, count1 = count1, count0 for item in count0: count0[item] = min(count0[item], count1.get(item, 0)) return toseq(count0) elif boolean_modus == 'not': # set difference count0 = tocount(seq0) count1 = tocount(seq1) if count0 < count1: # loop through the shorter list for item in count0: count0[item] = count0[item] - count1.get(item, 0) else: for item in count1: count0[item] = count0.get(item, 0) - count1[item] return toseq(count0) elif boolean_modus == 'or': # union return seq0 + boolean(seq1, seq0, 'not') elif boolean_modus == 'xor': # symmetric difference return boolean(boolean(seq0, seq1, 'or'), boolean(seq0, seq1, 'and'), 'not') #v- Thorsten From martin at v.loewis.de Wed Oct 16 09:21:19 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 16 Oct 2002 15:21:19 +0200 Subject: question about python extension with c/c++ References: Message-ID: "Zhen Zhang" writes: > If my module requires additional headerfiles to include (qstring.h for > example) and additional libraries (qtlibraies for example) to link with, > please tell me how to do. Just add -I and -l options in the Setup line; see _tkinter for an example. HTH, Martin From gerhard.haering at gmx.de Fri Oct 11 11:43:59 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 11 Oct 2002 15:43:59 GMT Subject: Is there a "reset" in Idle? References: <0rc7qu4l03ga7cdpifce8je632mlcju1fi@4ax.com> Message-ID: Dale Strickland-Clark wrote in comp.lang.python: > Michael Hudson wrote: >>Dale Strickland-Clark writes: >> >>> If I had any influence in the development of Python as a whole, I'd >>> urge the developers to divert their attention away from sexy new >>> language features and concentrate for a couple of releases on >>> addressing shotcomings that shag the IDEs. >> >>A couple of points: >> >> 1) what shortcomings are these? > > Only a few but critical to the re-usability of the debugging > environment. I don't remember the technical details but I'm sure > Google will find the issues if you're really interested. > >> 2) this isn't how OS development works, and you surely know this. >> > Who mentioned OSes? I don't understand the relevence of this. OS is also used as an abbrev. for Open Source. > >>The only people paid to work on Python are at PythonLabs, who are paid >>by ZC, who in turn probably don't have an overriding interest in >>interactive debugging. Everyone else works on Python because it's fun >>and to scratch an itch, basically. If you try to make us do what you >>want rather than what we want, we stop. > > I'm aware of this. However, surely some of the enjoyment comes from > knowing others are using your efforts? Can you imagine the boost > Python would get in the programming comminity if a killer IDE appeared > on the scene? > >> >>OTOH, if you can come up with concrete suggestions, I'm all ears. > > Suggestion: Address the problem in Python that prevents IDEs from > reloading modules and re-using a debuggin environment. That'd be the job of the import-SIG, which was founded for this very purpose, I think. Another solution is to run the interpreter in a seperate process. AFAIK WingIDE does exactly this, and they have even published the open-source framework that makes this possible. -- Gerhard From mgarcia at cole-switches.com Tue Oct 22 13:12:06 2002 From: mgarcia at cole-switches.com (Manuel M. Garcia) Date: Tue, 22 Oct 2002 17:12:06 GMT Subject: New to python References: <3db2fcc9$0$5803$fa0fcedb@lovejoy.zen.co.uk> Message-ID: <871bru8nn7sphp8tcc3cttjf9lelvjb61u@4ax.com> This is one of the shortest and best summaries of Python programming I have ever read! Perfect for people coming to Python from other languages. We have to get it on python.org or pythonquotes! On Tue, 22 Oct 2002 09:47:24 -0400, mwilson at the-wire.com (Mel Wilson) wrote: >In article , >Bob Koss wrote: >>I'm a very experienced C++/Java programmer. Can anyone recommend papers or >>books that will help me avoid programming C++ using Python syntax and to >>learn to do things the "Python way". > > I dunno, I found the docs supplied with the Python >release to be very, very good. I ditched the O'Reilly books >(for the first time in my life) and just learned from the >docs. > > I only know a little C++ and Java, but it seemed that >there was a pretty direct mapping of the useful parts. > > Lose the braces, as you know them, and most of the >semicolons, obviously. > > Where you would use ``, use lists, or tuples ,, >that is [] or () . Where you would use ``, use >dictionaries ,, that is {} . > > The semantics of iterators is available, but most of the >syntax goes away. `for item in alist:` iterates over all >the items in alist, one by one .. where `alist` is a >sequence, i.e. a list, tuple, or string. To iterate over a >sublist, use slices: `for item in alist[1:-1]:` does as >above, but omits the first and last items. > > For trickier iterations, read and re-read the Library doc >on the topic of general-purpose functions. There are some >functions that apply to sequences: map, filter, reduce, >zip. that can work wonders. Hidden somewhere under the >documentation for sequences there is a description of string >methods that you'll want to read. > > Hidden under the docs for 'Other Types' are the >descriptions of all the file methods. There are no >iostreams per se, but the class method __str__ can get some >of the effect for your own classes, and there are surely >other angles I haven't thought of. > > Forget polymorphism. You can define a function, and call >it with anything you want, but if it has to behave >differently for different type operands, you have to use the >run-time type identification `type` function explicitely >within the single definition of the function. Default >arguments to functions are just as powerful a tool as in >C++. > > In class definitions the equivalents of operator methods >are covered in a chapter in the Python Language Reference. >(Look for the double-underscore methods like __cmp__, >__str__, __add__, etc.) > > In C, the gotcha for new users is probably about >pointers; they're tricky and they can't be avoided. The >gotchas in Python are situations when you use different >references to a single object, thinking you are using >different objects. I believe the difference between mutable >and immutable objects comes into play. I have no clear >answers here .. I still get caught once in a while .. keep >your eyes open. > > Read the Tutorial once, skim the Library Reference .. at >least the table of contents, then skim the Language >Reference and you will probably have encountered everything >you need. > > Regards. Mel. From bfordham at socialistsushi.com Wed Oct 23 09:07:12 2002 From: bfordham at socialistsushi.com (Bryan L. Fordham) Date: Wed, 23 Oct 2002 09:07:12 -0400 Subject: [Python-Dev] tamper-evident logs References: <20021022225332.P88383-100000@the.whole.net> <20021022221302.A3091@unpythonic.net> Message-ID: <3DB69F00.10807@socialistsushi.com> Jeff Epler wrote: >On Tue, Oct 22, 2002 at 10:55:54PM -0400, Bryan L. Fordham wrote: > > >>here's a question for y'all: >> >> > >This is not a question for python-dev. Redirected to python-list. > Whoops. Thanks. Sorry about that. >The simplest idea that comes to mind would be to store a hash of the >log combined with a "secret". (Of course, since it'll necessarily be >stored on the same computer, it's not really a "secret", but it can be >obfuscated as much as you like) > > I'd considered something like this, but for some reason the idea of adding the date and a secret didn't jump into my mind. Maybe I need more caffiene. 8) I think that's a workable solution, though I'm open to other suggestions. This isn't for anything that requires high-security, nor and I worried about someone trying to make the software think it's been tampered with then it has not been. --B From Greg.Lindstrom at acxiom.com Tue Oct 8 14:40:43 2002 From: Greg.Lindstrom at acxiom.com (Lindstrom Greg - glinds) Date: Tue, 8 Oct 2002 13:40:43 -0500 Subject: Installing pyMySQL Message-ID: Hi, all- I am having a world of trouble installing pyMySQL on my Windows NT 4.0 box (ActiveState Python 2.2.1). My current problem occurs when I am trying to execute setup.py install when the linker complains about not being able to find mysqlclient_r.lib (sure enough...I can't fine it, either :-). Can any of you help me out? Or is there a more windows friendly database interface to use? Thanks! --greg ********************************************************************** The information contained in this communication is confidential, is intended only for the use of the recipient named above, and may be legally privileged. If the reader of this message is not the intended recipient, you are hereby notified that any dissemination, distribution, or copying of this communication is strictly prohibited. If you have received this communication in error, please re-send this communication to the sender and delete the original message or any copy of it from your computer system. Thank You. From eugene1977 at hotmail.com Wed Oct 9 03:34:23 2002 From: eugene1977 at hotmail.com (eugene kim) Date: Wed, 09 Oct 2002 07:34:23 +0000 Subject: apache+ python ? References: Message-ID: thank you for quick answer.. well what i'll be doing is db access, file uploading, xml generate/parsing speed doesn't matter .. but if using mod_python is not too much complicated,(it all depends how fast i can learn & use.. well that's the purpose of using python, isn't it?) i want to try it. i think i 've succeeded installing mod_python.. i have question though, maybe i have to ask this to apache forum, what's 'PythonHandler' in httpd.conf? i could access and print something with welcome_test.py(shown below) but i can't access other *.py files... ---------------------- from mod_python import apache def handler(req): welcome = "

mod_python welcomes you!

" req.content_type = "text/html" req.send_http_header() req.write(welcome) return apache.OK =================================== AddHandler python-program .py PythonHandler welcome_test PythonDebug On thank you From its1louder at yahoo.com Tue Oct 8 14:03:40 2002 From: its1louder at yahoo.com (Tom) Date: 8 Oct 2002 11:03:40 -0700 Subject: [Q] Python + NCAR Graphics References: <0iro9.12890$525.886576@twister.southeast.rr.com> Message-ID: <90f2d9db.0210081003.13fe7636@posting.google.com> "sdhyok" wrote in message news:<0iro9.12890$525.886576 at twister.southeast.rr.com>... > Is there any program linking NCAR Graphics with Python? > > Daehyok Shin I've been interested in that too. there are a some people working together to get an NCL extension to python - pyncl I think. I think this would be a neat thing that I would use eventually but right now I've got plenty of other things to do and no pressing use for it. Also, I have very little experience with NCARG/NCL (i.e., I 've run some sample code). A python module that calls it would probably be the impetus that gets me to dive into it more. I have a version of NCARG that runs under cygwin on my Win2K machine. look here: http://webdoc.ucar.edu/fred/extending_with_ncl.html and here http://ngwww.ucar.edu/ncl/dev/archives/pyncl/2002/ From sismex01 at hebmex.com Fri Oct 11 09:21:07 2002 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Fri, 11 Oct 2002 08:21:07 -0500 Subject: time and thread modules. Message-ID: > From: hansgeunsmeyer at earthlink.net > > sismex01 at hebmex.com wrote in message > news:... > > > [..snip..question about sleep() and GIL...] > > If you look at the implementation of time.sleep in timemodule.c, > you'll see that before actually calling Sleep (or select, or whatever > the function is, depending on your platform), Python uses the > Py_BEGIN_ALLOW_THREADS macro which > saves the current thread state, and releases the GIL (MacIntosh code > is a bit different here, but I suppose the effect is the same). Once > the GIL is released some other thread may grap it. > > Hans Thanks Hans, that's exactly what I needed to know. :-) -gustavo From dougfort at dougfort.net Wed Oct 2 04:49:33 2002 From: dougfort at dougfort.net (dougfort) Date: Wed, 02 Oct 2002 01:49:33 -0700 (PDT) Subject: Decimal arithmatic, was Re: Python GUI app to impress the boss? Message-ID: <20021002014934.8247.h012.c001.wm@mail.dougfort.net.criticalpath.net> "Tim Peters" wrote: > > Then please help Doug do that, including *defining* the rounding disciplines This is a surprisingly hot topic. We were going to put it off to a later release, but now I'd like to get something out before people lose interest. Joe and I are supposed to get together for pair programming Thursday night (if my day job cooperates). We'll try to have something out on CVS then. (Joe doesn't know about this yet). I'll be watching this list and fixedpoint.sourceforge.net for suggestions and test cases. Doug Fort http://www.dougfort.net From gerhard.haering at gmx.de Tue Oct 1 15:55:51 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 1 Oct 2002 19:55:51 GMT Subject: finding the mail server of a domain References: Message-ID: Gillou wrote in comp.lang.python: > Hi pythonistas, > > I'm looking for a pythonic way to find the hostname/IP of the mail server > for a given domain. (that's not for spamming :) but to check the members > database of a customer). > > Any hint ? Using http://pydns.sourceforge.net/ >>> import DNS >>> DNS.ParseResolvConf() >>> print DNS.mxlookup("nerim.net") [(10, 'brinstar.nerim.net'), (20, 'metroid.nerim.net'), (30, 'aline.noc.nerim.net')] If you want to use this to check for valid email adresses, forget it. Any properly configured SMTP server won't return useful data (because of spammers). -- Gerhard From chris.gonnerman at newcenturycomputers.net Wed Oct 9 21:00:13 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Wed, 9 Oct 2002 20:00:13 -0500 Subject: PEP239 (Rational Numbers) Reference Implementation and new issues References: <20021002221421.GA29958@thyrsus.com> <3D9B7DB5.4000702@tismer.com> <005f01c26a8c$fe2fb3e0$ba01010a@local> <3DA4C654.5060806@tismer.com> Message-ID: <00b101c26ff8$67709840$ba01010a@local> ----- Original Message ----- From: "Christian Tismer" > Chris Gonnerman wrote: > [snipped all the other good stuff] [snipped all the other good stuff again] > > Yeah, I'm the one who has been arguing in favor of a > > decimal arithmetic type in the standard library. Ask > > me to support rationals in the standard library, and I'll > > back you up. Heck, I'll even accept (optional) rational > > literals, like the way we do longs. (As long as you > > support (optional) decimal literals in return... :-) > > Ok, we have a deal. Excellent! [ hack hack hack ] > Naa, this is slightly different. > I don't think al too many people asked for an integer > in the first place when they wrote > > 1/3 Ahhh... you are thinking, "1/3 as a literal" and I am seeing it as an EXPRESSION. So to you, this: 1/3 is not the same as this: n = 1 m = 3 n/m Or have I misunderstood? Because if you give me a rational for the second option I'll be royally ticked off. For the first option, giving me a rational serves me right. > Now suddenly for some reason out of this thread's scope > Python reconsiders and thinks it should change this. > So the target of this whole thing is (AFAIK) to figure > out which type to return as the result of integer division? I was against changing the integer division rules (I still am) but I only have one module affected negatively by it, so I stopped whining. (Except when someone brings it up...) > So you would suggest to stick with 1/3 == 0, or return > a float, or a rational? 1/3 as an expression; whether I get 0 or 0.333... depends on the Python version. I just don't want a THIRD option (gah). > The latter makes no sense, since this would save the R. (I don't understand that statement) > Personally, I don't like the idea to change 1/3 at all > not very much. I see Python doing too much adjustments > at the moment. My reason for not liking automatic insertion of rationals. > Making 1/3 return a float felt like a bad idea, after it > had been int for so many years. Enforcing the float > has become a habit where it's needed. I agree on both counts. > Now, returning a true fraction instead sounds exciting. > Having fractions in the language is exciting as well, > after I had them in Mathematica for long years. ... let's not get too excited here ... > Finally, if I had to choose, I would either stick with > the old truncation, or use rationals. > Rationals would be welcome, even if there were just > an extension module. Now that idea I can get behind. I'd never use them, but (IMHO) you can never have too many tools in the box. What I was proposing wasn't actually 1/3R as a rational literal; THIS is a rational literal: 3R and since math operations involving a rational and an int or float would "promote" the int or float to rational, this: 1/3R would return a rational one-third value. In other words, the R suffix would make a literal integer "n" into a rational of the form "n/1". Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From gmcm at hypernet.com Sat Oct 12 09:06:17 2002 From: gmcm at hypernet.com (Gordon McMillan) Date: 12 Oct 2002 13:06:17 GMT Subject: McMillan Installer and threads References: Message-ID: Robin Becker wrote: > Gordon McMillan's new installer stuff starts locking its internal state > when it sees that the thread module is imported. > > Does the use of thread.acquire/release imply we are getting the overhead > of multi-threading or does start_new_thread actually have to be called? It's just the presence of the thread module. Conceivably, C code could create a situation where threads are active without start_new_thread ever being called. Perhaps even without the thread module being imported, but there doesn't seem to be a way to tell from pure Python whether threads have been initialized at the C level. -- Gordon http://www.mcmillan-inc.com/ From Patrick.Surry at quadstone.com Mon Oct 21 12:29:37 2002 From: Patrick.Surry at quadstone.com (Patrick Surry) Date: Mon, 21 Oct 2002 12:29:37 -0400 Subject: Unicode strings -> xml.dom.minidom Text elements? Message-ID: <3DB42B71.38C2A568@quadstone.com> I've got a unicode string like: a = u'ABC\u03A3DEF' and am stuffing it into an xml.dom.minidom Text() element. But when I serialize the document with doc.writexml(), it turns into: ABC?DEF rather than: ABCΣDEF as I was hoping. This seems to be because writexml() effectively does writer.write('%s' % a) making the unicode character turn into a '?' Am I doing something dumb and/or is there a workaround I could use other than writing my own XML unicode character escaper... Cheers, Patrick -- _________________________________________________________________________ Patrick Surry, PhD Tel 617 753 7393 Fax 617 457 5299 www.quadstone.com - With the breadth of our knowledge grows the boundary of our ignorance - From engsol at teleport.com Thu Oct 31 15:08:49 2002 From: engsol at teleport.com (engsol at teleport.com) Date: Thu, 31 Oct 2002 20:08:49 GMT Subject: Newbie: Where are SetCommMask, GetCommState, etc? Message-ID: <3dc18be0.13484039@news.earthlink.net> The crime scene: Win NT, Python222, Mark Hammond's book on Win32, and win32comport_demo.py The problem: I connected my machine to another machine running Hyperterminal, using a null-modem cable, then fired up the demo. Works just fine. Now I want to learn in detail how it works. The demo script refers to SetCommMask, SetupComm, GetCommState, etc., but I can't find an explanantion how they work. I want to poke and prod my com ports, including the UART registers. Any pointers? Thanks.... Norm From falkoNOSPAM at ostrakon.de Tue Oct 15 08:27:05 2002 From: falkoNOSPAM at ostrakon.de (Falko Spiller) Date: Tue, 15 Oct 2002 14:27:05 +0200 Subject: server not accepting second connect Message-ID: hello, just learning python, and my toy project shall do something like a very simple chat (or mud). so if somebody connects with a telnet like applikation, she can chat with other connected people. i started with code for server and requesthandler from the http server application, throwing out everything i didnt need. in the request handler there is this handle() method. the problem is (or seems to be): if the handle() method does not return, the server doesnt accept new connections. if the handle message returns, the connection seems to get destroyed. at least i get an error message: Unhandled exception in thread: Traceback (most recent call last): File "server.py", line 68, in run line = self.fileToServer.readline() File "C:\Python22\lib\socket.py", line 238, in readline new = self._sock.recv(self._rbufsize) AttributeError: 'int' object has no attribute 'recv' server.py is my file. currently i have to start a server for every single client that wants to connect, and, well, knowing this topic from java, i think thats not state of the art :-) anybody able to suggest a way? or to provide/point to example-code? thank you regards, falko ----------------------------------------- platform: python 2.2.1, M$ Windos 2000 source fragments: class Server(SocketServer.TCPServer): allow_reuse_address = 1 # Seems to make sense in testing environment def server_bind(self): """Override server_bind to store the server name.""" if len(labyrinth)<1: makeRooms() SocketServer.TCPServer.server_bind(self) host, port = self.socket.getsockname() self.server_name = socket.getfqdn(host) self.server_port = port serverName.append(self.server_name) serverName.append(self.server_port) class RequestHandler(SocketServer.StreamRequestHandler): """request handler base class. The various request details are stored in instance variables: - client_address is the client IP address in the form (host, port); - rfile is a file object open for reading positioned at the start of the optional input data part; - wfile is a file object open for writing. """ def handle(self): print self.client_address, 'connected.' self.wfile.write("Hello Stranger, welcome to "+serverName[0]+' (port '+str(serverName[1])+')\n') self.wfile.write("The first word you utter will be your name.") player = Player(self, self.rfile,self.wfile) player.room = labyrinth[0][0] player.room.players.append(player) player.name = None# self.client_address[1] player.run() # thread.start_new_thread(player.run,()) the two different ways are the two last lines. the player.run(9 anth the comment, starting the new thread. the player tries to do a readline at requesthandler.rfile, and that crashes in the new thread. From coo_t2 at I-hate-spam-yahoo.com Mon Oct 21 23:09:34 2002 From: coo_t2 at I-hate-spam-yahoo.com (ed) Date: Mon, 21 Oct 2002 23:09:34 -0400 Subject: best way to learn Message-ID: Hey all. I'm a python newbie, but I have experience in other very high level languages, mainly php. I was wondering what is the best way to become proficient in python quickly? I'm actually a pretty decent php programmer, so I don't think I need something that spends too much time on the basics(ie loops and if statements). I just need to know how things work in python. I've tried the main tutorial that comes with the distro, and to be honest I was kind of disappointed. It don't seem to have the linear quality and cohesiveness that a good tutorial should. Hope I don't make anyone mad by saying that. Should I get a book, if so which one? "Learning python", "programming python", "python cookbook"? Or can I get pretty much everything I need on the web, like a lot of good tutorials and some good language references? If I get a book I'd like to get one that works as a newbie tutorial but by the end of the book deals with some advanced topics and will also work somewhat well as a reference. Is that asking too much? Should I trust the reviews at amazon.com? :) Any guidance appreciated. tia, --ed From sienkiew at ncbi.nlm.nih.gov Fri Oct 25 09:52:29 2002 From: sienkiew at ncbi.nlm.nih.gov (Mark Sienkiewicz) Date: Fri, 25 Oct 2002 09:52:29 -0400 (EDT) Subject: CGI docs Message-ID: <200210251352.g9PDqTN11006@mailbox.nlm.nih.gov> >I want to send parameters to my CGI programmes in the URL, not in any html >form. I am looking for a way to read in the parameters from the URL. > >For example, I have the following link in a webpage: > >name > >I want my script "hello.py" to be able to pick up the >"name:Catalin" pair. Maybe you are missing some of the background on how CGI works. CGI has two ways of passing parameters in: GET and POST. If the form uses POST, your cgi program sees the parameters on standard input. The details of how that happens are not important - the web server handles it. If the form uses GET, the browser constructs a URL that looks exactly like the one you used in your example. The parameters come to your CGI program as environment variables. The library recognizes whether the browser used GET or POST to send the data, and does the right thing. Because you wrote the URL that way, it thinks the browser used GET. You can handle the data in the same way as you would handle form data. The interesting documentation is in "Python Library Reference" section 11.2. Just pretend your input is form data. From looking over the documentation, I think the interface in section 11.2.3 is a little easier to use. For most reasonable CGI programs, you would use import cgi f = cgi.FieldStorage() name = f.getfirst("name") otherthing = f.getfirst("otherthing") # if you have another parameter From robin.siebler at corp.palm.com Tue Oct 15 20:35:29 2002 From: robin.siebler at corp.palm.com (Robin Siebler) Date: 15 Oct 2002 17:35:29 -0700 Subject: Most efficient method to search text? Message-ID: <886c5e4b.0210151635.123359bb@posting.google.com> I wrote a script to search a slew of files for certain words and names. However, I am sure that there has to be a faster/better way to do it. Here is what I am doing: 1. Load words to exclude into a list. 2. Load names to exclude for into a list. 3. Load words to include into a list. 4. Remove any duplicates from the name list. 5. Generate a list of files to search. 6. Open the 1st file. 7. Search each line: a. For a word (line.find(word)). If I get a hit, I then use a RE to perform a more exact search (the pattern I am using is '\w+word|word\w+|word'). i. Compare any matches against the include/exclude list. If it is a match, keep searching. Otherwise, log the line. b. For a name (line.find(name)). If I get a hit, I then use a RE to perform a more exact search (the pattern that I am using is '\bname\b'. If I get a hit, log the line. The reason that I first search using line.find() is that in the past I have done some searches for simple strings and found that line.find() was much faster than an RE, so I am only using an RE when I need to. I am including my code below (unforunately, Google screws the formating up). Any suggestions to improve it would be appreciated. LinesFound = []; LinesFound = FunkyList(LinesFound); msg = "" LineNum = 0; Header = 0 LogFile = var['LogFile'] print '\nGenerating file list...' #Let user see that script is running FilesToSearch = listFiles(var['SearchPath'], var['SearchExt'], var['Recurse']) if len(FilesToSearch) == 0: print 'No Files Found!' clean_up(var) else: print 'Number of files to search: ' + str(len(FilesToSearch)) print 'Processing files...', #Let user see that script is running while FilesToSearch: FileBeingSearched = FilesToSearch.pop() #Get/remove last file name open_file = open(FileBeingSearched) print "\nProcessing " + FileBeingSearched, for line in open_file.xreadlines(): LineNum += 1 #Let user see that script is running if LineNum >24 and LineNum % 100==0: print ".", for word in var['ExcludeWords']: #Search line for proscribed words #Perform a case insensitive search for word *anywhere* in the line if line.lower().find(word.lower()) != -1: pattern = '\w+word|word\w+|word' pattern = pattern.replace('word', word.lower()) s_word = re.compile(pattern, re.IGNORECASE) #If the phrase was found, get a list containing the matches match_found = unique(s_word.findall(line)) for match in match_found: #If the word contains an underscore if match.find('_') != -1: words = '\w+' w_find = re.compile(words, re.IGNORECASE) words = '' for item in w_find.findall(line): if item.find('_') != -1: words = words + ' ' + str(item.split('_')) else: words = words + ' ' + item m_found = unique(s_word.findall(words)) for item in m_found: if item in var['ExcludeWords'] and item not in var['IncludeWords']: msg = '\tLine ' + str(LineNum) + ': The word "' + \ word + '" was found in: "' + line.strip() + '"' LinesFound.append(msg) break; elif match not in var['IncludeWords']: #Is the word in IncludeWords? msg = '\tLine ' + str(LineNum) + ': The word "' + \ word + '" was found in: "' + line.strip() + '"' LinesFound.append(msg) break; for name in var['Names']: #Search line for names if line.lower().find(name.lower()) != -1: #Perform a case insensitive search pattern = '\bname\b' pattern = pattern.replace('name', name) s_word = re.compile(pattern, re.IGNORECASE) match_found = unique(s_word.findall(line)) #If the phrase was found, get a list containing the matches for match in match_found: if match in var['Names']: msg = '\tLine ' + str(LineNum) + ': The name "' + name + \ '" was found in: "' + line.strip() +'"' LinesFound.append(msg) break; if len(LinesFound) > 0: if not Header: LogFile.write('Proscribed words were found in ' + FileBeingSearched + '\n') LogFile.write('\n') Header = 1 for line in LinesFound: LogFile.write(line + '\n') LogFile.write('\n') LinesFound = [] open_file.close() LineNum = 0; Header = 0; hit = 0 print '\nProcessing Complete.' From teaandbikkie at aol.com Fri Oct 11 10:54:38 2002 From: teaandbikkie at aol.com (TeaAndBikkie) Date: 11 Oct 2002 14:54:38 GMT Subject: Amazon review (was Re: Love "Python Cookbook") References: Message-ID: <20021011105438.17002.00000301@mb-fd.aol.com> Edward K. Ream wrote: >I've just submitted a slightly revised review to Amazon. According to (Following the hoofprints and horse dung piles after finding an open door and an empty stable) Would the quotes sound more authentic with the author of each quote attached, like you see on the back of novels? This book is sounding better and better, its already on my birthday wishlist, so I'd like to officially move up my birthday to next week :) -- Misha From lists at andreas-jung.com Thu Oct 24 12:31:41 2002 From: lists at andreas-jung.com (Andreas Jung) Date: Thu, 24 Oct 2002 18:31:41 +0200 Subject: CGI docs In-Reply-To: References: Message-ID: <124240228.1035484301@SUXLAP> Python Library Reference - where else!? Look on Python.org in the Documentation section on checkout the docs for the cgi module. -aj --On Donnerstag, 24. Oktober 2002 17:09 +0200 Doru-Catalin Togea wrote: > Hi! > > Where do I find documantation for CGI scripting with Python? I am > particularly interested in how to get the arguments passed to the script > in an URL. > > Thanks in advance, > Catalin > > > > <<<< ================================== >>>> > << We are what we repeatedly do. >> > << Excellence, therefore, is not an act >> > << but a habit. >> > <<<< ================================== >>>> > > > -- > http://mail.python.org/mailman/listinfo/python-list --------------------------------------------------------------------- - Andreas Jung http://www.andreas-jung.com - - EMail: andreas at andreas-jung.com - - "Life is too short to (re)write parsers" - --------------------------------------------------------------------- From hennie at sabinet.co.za Thu Oct 17 03:43:38 2002 From: hennie at sabinet.co.za (Hennie Rautenbach) Date: Thu, 17 Oct 2002 09:43:38 +0200 Subject: Pythin-2.2.1 install on Solaris question. Message-ID: <3DAE6A2A.5060109@sabinet.co.za> Hi there, I am having difficulty installing Python-2.2.1 on a Solaris 8 system uisng the Gnu-C compiler. I ran configure and make without any problems. During "make install" the following errors are displayed for all modules: (using the pwd module as example) building 'pwd' extension /usr/local/bin/gcc -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -fPIC -I. -I/usr/local/src/Python-2.2.1/./Include -I/usr/local/include -IInclude/ -c /usr/local/src /Python-2.2.1/Modules/pwdmodule.c -o build/temp.solaris-2.8-sun4u-2.2/pwdmodule.o /usr/local/bin/gcc -shared build/temp.solaris-2.8-sun4u-2.2/pwdmodule.o -L/usr/local/lib -o build/lib.solaris-2.8-sun4u-2.2/pwd.so WARNING: removing "pwd" since importing it failed Why is this happening ? What am I doing wrong ? Any pointers will be much appreciated. Best regards, Hennie -- =================================================================== Hennie Rautenbach Work: http://www.sabinet.co.za 082-556-1191 Play: http://www.overland.co.za It's choice, not chance, that determines your destiny. -- Jean Nidetch =================================================================== ##################################################################################### This e-mail message has been scanned for Viruses and Content and cleared by MailMarshal For more information please visit www.marshalsoftware.com ##################################################################################### From r.l.richardson at verizon.net Tue Oct 1 11:53:20 2002 From: r.l.richardson at verizon.net (Rick Richardson) Date: Tue, 01 Oct 2002 08:53:20 -0700 Subject: __call__ question References: Message-ID: <3D99C4F0.9020207@verizon.net> >>> def callfunc(self, arg): print "hello, " + arg >>> class testclass(object): def testfunc(): print "testing" >>> blah = testclass() >>> blah <__main__.testclass object at 0x009336E8> >>> blah() Traceback (most recent call last): File "", line 1, in ? blah() TypeError: 'testclass' object is not callable >>> blah.__call__ = callfunc >>> blah("test") Traceback (most recent call last): File "", line 1, in ? blah("test") TypeError: 'testclass' object is not callable >>> blah.__call__(blah, "test") hello, test >>> testclass.__call__ = callfunc >>> blah("test") hello, test >>> Your example gave me another variant that I should have tried but didn't expect to work, that is adding the function to the Class, not the instance :). It is interesting to note that the actual function call works for either the instance or the class, but the shortcut only works for the object if the assignment was made to the class. Michael Hudson wrote: >Works the same with new-style classes too. What goes wrong for you? > >Cheers, >M. > > > From tjreedy at udel.edu Thu Oct 10 11:59:06 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 10 Oct 2002 11:59:06 -0400 Subject: No tabs in post PLEASE!!! (was Re: partial list sort) References: <20021009094141.GA852@jsaul.de><2Rep9.19819$ne4.8631@fe05> Message-ID: "Fran?ois Pinard" wrote in message news:mailman.1034258856.31237.python-list at python.org... Somewhat tongue in cheek, I wrote > >> > > Tabs are bad for Usenet posting if you want stupid people like me who > >> > > use Outlook Express to read posted code. >I've seen > a constant push, for years, by recipients using broken software, asking the > whole planet to be polite and help them cope with their brokenedness. That > push should be considered unwelcome, and politeness is misplaced here. Since I started this subthread, please note that I did *not* push (and intentionally so). I simply informed the OP that *if* he wanted me to read his code without having to guess at indentation, then he should avoid tabs. Since I had provided him, free of charge, two solutions to his problem, he wrote back that he would try to do so (avoid) in the future. Another person prefers, for whatever reason, to post his text as mime attachments to an empty body. I sent him the same sort of information. He replied that he thinks that leaving attachments as attachments until explicitly opened instead of autoconverting them to body text is a brokenness he does not with to cater to. Fine. I skip all his stuff. Terry J. Reedy From newt_e at blueyonder.co.uk Wed Oct 9 18:05:55 2002 From: newt_e at blueyonder.co.uk (Newt) Date: Wed, 09 Oct 2002 22:05:55 GMT Subject: Tkinter Query Message-ID: <7L1p9.484$su4.7497873@news-text.cableinet.net> Hi, I'm trying to build a form with some rows. Each row consists of a down button, a label, and an up button. When the down button is pressed, I want the value in the label to go down, and if the up button is pressed then the value goes up. The code looks like (I haven't done the up button yet, and I know I'm only changing the value of the label from 10 to 9 (if it worked...)). class SelectSkills: def __init__( self, parent ): pos = 0 svals = [] allskills = ['Skill 1','Skilll 2','Skill 3','Skill 4'] for skill in allskills: sval = Label(wskill, text = "10").grid(row=pos+2,col=2) dbut_callback = curry( self.down, pos, parent ) dbut = Button(wskill, text='<', command=dbut_callback ).grid(row=pos+2,col=1) rbut = Button(wskill, text='>').grid(row=pos+2,col=3) svals.append(sval) pos = pos + 1 return def down( self, i, *crap): global svals showinfo('Down','In Down:'+str(i)) sval = svals(pos) sval.configure(text = '9') return In the code above, I'm trying to use svals to hold the values of sval as they are created. When I run this, I get an error that svals is not a global. So two questions: 1. How do I make svals into a global? 2. What is the correct way to implement what I'm trying to do? Thanks in advance, Newt From psimmo60 at hotmail.com Thu Oct 10 05:37:36 2002 From: psimmo60 at hotmail.com (Paul Simmonds) Date: Thu, 10 Oct 2002 09:37:36 +0000 Subject: OOing in Tkinter - help Message-ID: Henry Baumgartl wrote: >def onSelectAll(self, event=None): > self.textfield.tag_add(SEL, '1.0', END+'-1c') > self.textfield.mark_set(INSERT, '1.0') > self.textfield.see(INSERT) > >etc. However, now i need more than one Text widget in the same >container >frame, and it seems a waste re-writing the methods to work with each > >widget. > >How can i adjust the above so it will respond to whatever text widget >the >call comes from. You can use the event object that's created in the call. Swap your specific text widget call for the calling widget so the code becomes: def onSelectAll(self, event=None): event.widget.tag_add(SEL, '1.0', END+'-1c') event.widget.mark_set(INSERT, '1.0') event.widget.see(INSERT) ... The event object contains a lot of data on the calling widget. If this function is never called from anything other than a text widget (which it doesn't look like it will) then there'll be no problems. HTH, Paul ********************************************** I used to have a handle on life, but it broke. ********************************************** _________________________________________________________________ Chat with friends online, try MSN Messenger: http://messenger.msn.com From paul at boddie.net Tue Oct 1 11:56:55 2002 From: paul at boddie.net (Paul Boddie) Date: 1 Oct 2002 08:56:55 -0700 Subject: DBI cursor behaviour with multiple statements? References: <23891c90.0209300554.5b37c195@posting.google.com> Message-ID: <23891c90.0210010756.7ec21b94@posting.google.com> mark.charsley at REMOVE_THIS.radioscape.com (Mark Charsley) wrote in message news:... > In article <23891c90.0209300554.5b37c195 at posting.google.com>, > paul at boddie.net (Paul Boddie) wrote: > > > "SELECT * FROM table WHERE column IN %s" > > Does that work? I've never been able to pass in a list of things like that > in either ODBC or ADO from C++. Which means: > a) the python library isn't cacheing the execution plan, and is just > building a new building a new SQL statement with each call (which is going > to have serious consequences), or The only DB-API module that I've tried with "IN" that seemed to support it was psycopg (out of that one and pyPgSQL). I don't know how the psycopg people have implemented it, though, and from certain conversations I've had, I don't think PostgreSQL supports/-ed proper parameter binding anyway. > b) it's possible to make DB calls from python that can't be made from C++, > or > c) I've been an idiot Ruling out the last one, ;-) I would suspect that everything depends on the database library or DB-API module concerned, given that database vendors won't have overlooked this one. Have you tried using mxODBC to see if this kind of thing is supported there? Paul From esr at thyrsus.com Wed Oct 2 18:14:21 2002 From: esr at thyrsus.com (Eric S. Raymond) Date: Wed, 2 Oct 2002 18:14:21 -0400 Subject: [Python-Dev] PEP239 (Rational Numbers) Reference Implementation and new issues In-Reply-To: References: Message-ID: <20021002221421.GA29958@thyrsus.com> python-pep at ccraig.org : > I just uploaded a reference implementation of how rationals might look > in Python as patch 617779 [1]. I do have some new issues for > discussion that I'd like to get some comments on before I change the > PEP. > > 1) Should future division return rationals rather than floats. I had > sort of assumed this would happen, but I just had a discussion with > Kirby Urner and couldn't convince him it was a good idea, so I guess > it isn't so clear. > > Arguments for: > - you don't lose precision on divides > - It provides a really nice way to specify rationals (i.e. 1/3) > - It allows you to eventually unify int/long/rationals so that > rationals with a denominator of 1 are automagically upcast. > > Arguments against: > - people who have already changed their code to expect floats will > have to change it again > - rationals are slow +1 for returning rationals. It's the right thing -- and if it fails, it will fail noisily, right? > 2) Should floats compare equal with rationals only when they are > equal, or whenever the are the closest float? (i.e. will .2 > compare equal to rational(1, 5)) > > 3) Should rationals try to hash the same as floats? My leaning on > this is that it will be decided by (2). If they compare equal when > 'close enough' then they should hash the same, if not then they should > only hash the same when both are integral. I would rather not see .5 > hash with rational(1, 2) but not .2 with rational(1, 5). APL faced this problem twenty-five years ago. I like its solution; a `fuzz' variable defining the close-enough-for-equality range. -- Eric S. Raymond From max at malva.com.uaREMOVE.IT Wed Oct 9 03:43:18 2002 From: max at malva.com.uaREMOVE.IT (Max Ischenko) Date: Wed, 9 Oct 2002 10:43:18 +0300 Subject: Accessing dyn modules from embedded python Message-ID: Hi. I'm trying to embed Python into my application. The smoke test already works, I've managed to call a pure python function from my C++ code. But, an error occurred when I tried this: # -- my python module used by C++ program -- def translate(data): return unicode(data, 'koi8-r').encode('cp1251') $ PYTHONPATH=`pwd` ./translator Traceback (most recent call last): File "/home/max/projects/e2u/express2u.py", line 2, in ? import codecs File "/usr/lib/python2.2/codecs.py", line 10, in ? import struct, __builtin__ ImportError: /usr/lib/python2.2/lib-dynload/struct.so: undefined symbol: PyString_Type Aborted (core dumped) The translator is build with PY_CONFIG = /usr/lib/python2.2/config PY_CFLAGS = -I/usr/include/python2.2/ -g PY_LDFLAGS = -lpthread -ldl -lutil translator: translator.cpp TranslationService.o $(CXX) $(PY_LDFLAGS) -g -o $@ $^ $(PY_CONFIG)/libpython2.2.a TranslationService.o: TranslationService.cpp TranslationService.h $(CXX) $(PY_CFLAGS) -Wall -c TranslationService.cpp -o TranslationService.o Another related question: I want to deploy my C++ app with embedded Python on machines where no Python is installed. How should bundle other modules I'm interested in (like locale, codecs, etc.)? Btw, If I doesn't specify PYTHONPATH the translator can't find the module. Why is this? -- In most countries selling harmful things like drugs is punishable. Then howcome people can sell Microsoft software and go unpunished? (By hasku at rost.abo.fi, Hasse Skrifvars) From cnetzer at mail.arc.nasa.gov Wed Oct 9 16:43:41 2002 From: cnetzer at mail.arc.nasa.gov (Chad Netzer) Date: Wed, 9 Oct 2002 13:43:41 -0700 Subject: infinity In-Reply-To: <3DA48D14.4090007@aon.at> References: <3DA48D14.4090007@aon.at> Message-ID: <200210092043.NAA23120@mail.arc.nasa.gov> On Wednesday 09 October 2002 13:09, Gregor Lingl wrote: > Is there a token or a name to input > this strange float object, > __repr__esented by 1.0#INF > directly? Well, you can make a global (or module global), to use as a label: INF = 1e999999999 # This should always be big enough This should even be portable to most "mainstream" systems (ie. Not raise an exception, coredump, etc.). Can more knowledgeable people say for sure? Also, you can (usually) get a NaN out of it, too: NaN = INF - INF which has interesting (and important) properties: NaN == NaN NaN == 0.0 NaN == 1.0 NaN == NaN == INF NaN + NaN == NaN NaN - NaN == NaN NaN + INF == NaN etc... Note that Python typically relies on the underlying behavior of the machines floating point (rather than enforcing its own, portable implementation), so relying on specific floating point behavior isn't always portable. (It's a long standing comp-sci problem that is improving, however) -- Chad Netzer cnetzer at mail.arc.nasa.gov From jepler at unpythonic.net Fri Oct 11 15:07:51 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Fri, 11 Oct 2002 14:07:51 -0500 Subject: Stringify object reference? In-Reply-To: <3DA707AD.92BCF22D@hotmail.com> References: <3DA6FB65.5D6A4AFE@hotmail.com> <3DA707AD.92BCF22D@hotmail.com> Message-ID: <20021011190751.GB20043@unpythonic.net> On Fri, Oct 11, 2002 at 06:17:33PM +0100, Alan Kennedy wrote: > Is there a specific reason why id()'s can't be turned back into objects? > Is it an implementation specific thing? Or is it to stop people messing > with pointers, etc? Consider: >>> o = object() >>> del o You want the storage for 'o' to be freed, since nothing can reference o anymore. (nothing else still holds a reference to 'o') now consider >>> o = object() >>> i = id(o) >>> s = str(i) >>> del i >>> del o >>> i = int(s) >>> o = unid(i) now you have taken the id of o, turned it into a string, deleted the object (and the integer id, for good measure). It's been garbage collected. How could unid() possibly work in this case? On the other hand, if you don't mind that 'id(o)' makes o immortal, you will have a program with unlimited growth in memory usage. That's not terribly useful either. The only sane solution would be through a dictionary, where you have some good way to clean out stale entries. The way you do this will probably be specific to your application. Jeff persmap = {} def pid(o): persmap[id(o)] = o return id(o) def pobj(id): return persmap[id] From nmarais at hertz.ee.sun.ac.za Thu Oct 31 08:31:41 2002 From: nmarais at hertz.ee.sun.ac.za (Neilen) Date: Thu, 31 Oct 2002 15:31:41 +0200 Subject: Redirecting Output from a Long Running Python app Message-ID: Hi. I wrote some numeric code in python (using numpy, etc.), that often needs to run for a while. Therefore I wanted to use nohup, to ensure it does not get accidentally killed if I close an xterm or something similar. The only problem is, no output seems to be redirected to nohup.out, nor is anything printed to the terminal. My program is quite verbose, and I would have liked to tail -f nohup.out, to see how its doing. I created the output of my program just using standard print statements. Intermingled, are some outputs of the date program. I used this to print the time now and again, before I read up on the os module ;) Anyhow, when python's output is redirected, (using nohup, or just plain >) that is all I see in the output! Initially I thaught this was some oddity due to running on IRIX (6.5.13), with Python 2.1.3 I compiled, but the same happes with the latest debian packaging of Python 2.1.3. Any suggestions? Thanks Neilen From donn at u.washington.edu Mon Oct 21 13:07:04 2002 From: donn at u.washington.edu (Donn Cave) Date: 21 Oct 2002 17:07:04 GMT Subject: Why is Python a good first scripting language? References: <1fkeime.1r79iww9k4r9gN%news@agapow.net> Message-ID: Quoth Roy Smith : | news at agapow.net (Paul-Michael Agapow) wrote: |> Ruby is cool and solid, but the developer community is still |> small. It's at the point where Python was 3 or 4 years ago. | | I find it fascinating that people who know neither Python nor Ruby seem | th think Ruby is the cooler language. ... | If Perl is to Python as Windows is to Macintosh, then I guess Python is | to Ruby as Macintosh is to BeOS :-) Which seems to illustrate a corollary: people who only know Python are sure it's cooler than some other language they don't know. I'm typing this on a Macintosh running BeOS (Macintosh is a kind of computer, MacOS and BeOS are operating systems), so to me it seems like you're trying to make a case for Ruby. It's actually an interesting way to look at the question. My computer here is a Power Macintosh 7500, original 1gb disk, memory upgraded to 64Mb and CPU upgraded to 132Mhz PPC604. The way I see it, my options are a) run BeOS on it, or b) throw it away and ask for a new computer. Macintosh hardware has gotten a lot bigger and faster since '96 or whenever it was, and Apple's software has followed along. BeOS 5 is pretty fast on this hardware, even with only 1/3 Gb disk and therefore no swap space. MacOS 8.1 is not lightning fast, but bearable if you don't use a terminal emulator as much as I do. MacOS X struggles on twice the hardware. Does your parallel work here? I don't know a thing about Ruby, is it fast and lean? I know lots of very hard and talented work has been done to improve Python's performance, but I'm sure it is not the fastest interpreted language (look at interpreted OCaml for example - not counting the compiled version, though of course that's how you'd probably use it.) How about the programming API? Whatever the reasons (you might excuse Apple because the APIs are a lot older, but Amiga programmers would object), it's a lot simpler to write a simple BeOS application. Memory management is simpler and more conventional. The whole API is documented in a single thick book. Is that Ruby? A simple natural API, compared to Python's burgeoning repertoire of list incomprehensions, generators and general obfuscators? Hm, I'm hearing a lot of good things about this Ruby. Donn Cave, University Computing Services, University of Washington donn at u.washington.edu From anandpillai6 at yahoo.com Wed Oct 9 10:19:17 2002 From: anandpillai6 at yahoo.com (Anand) Date: 9 Oct 2002 07:19:17 -0700 Subject: Function GetData() in wxImage References: <41c203e.0210070707.15595d94@posting.google.com> Message-ID: <41c203e.0210090619.3ce05461@posting.google.com> Hi Mike How do I create a PIL Image instance from a wxImage instance. In your code you have done the reverse, ie creating a wxImage instance from a PIL image. img = Image.open(file,'r') self.wxImg.SetData( img.convert( "RGB").tostring() ) How do I use the GetData() on wxImage() to create a PIL image. I tried, img = Image.open(str(self.wxImg.GetData())) But python runtime complains that the data is NULL padded which is correct. since the chunk is binary. Do I need to call 'encode()' on the chunk to use the above ? If so what encoding? Thanks Anand "Mike C. Fletcher" wrote in message news:... > http://wiki.wxpython.org/index.cgi/WorkingWithImages > > BTW: It's generally more efficient to use the wxPython users mailing > list for these kinds of questions. > > Enjoy, > Mike > > Anand wrote: > > >Hi > > > > I am writing an image viewer in wxPython using the wxImage class. > >I want to manipulate the image data for effects. I tried to use the > >GetData() method of the wxImage class which returns a const char *(wxWindows > >documentation). > > > > How do I manipulate this object. Is it a python object or a C unsigned char * > >stream ? Can i apply std 'C' calls on it or do I need to use methods of > >python ? > > > >Concerned code... > > > > def myfunc: > > > > ... > > self.img = wxImage(fileName) > > chunk = self.img.GetData() # What is this chunk ? > > pass > > > > > >Thanks > > > >Anand > > > > From falkoNOSPAM at ostrakon.de Wed Oct 16 03:13:04 2002 From: falkoNOSPAM at ostrakon.de (Falko Spiller) Date: Wed, 16 Oct 2002 09:13:04 +0200 Subject: server not accepting second connect References: Message-ID: hello all, i found a code example that runs fine. http://mail.python.org/pipermail/edu-sig/2000-April/000320.html falko From tismer at tismer.com Tue Oct 1 22:56:06 2002 From: tismer at tismer.com (Christian Tismer) Date: Tue, 01 Oct 2002 19:56:06 -0700 Subject: Decimal arithmatic, was Re: Python GUI app to impress the boss? References: <7xd6qwqtgz.fsf@ruckus.brouhaha.com> <7xelbcgo56.fsf@ruckus.brouhaha.com> <7x65woks0i.fsf@ruckus.brouhaha.com> Message-ID: <3D9A6046.1090905@tismer.com> Paul Rubin wrote: > "Chris Gonnerman" writes: > >>>What do you mean by "right"? What do you mean by "all >>>cases"? >> >>The original subject is *business* arithmetic. There is no >>choice but to use decimal arithmetic if you want your math >>results to match good-old-fashioned pen and paper math. > > > No, I'm still not convinced. Is business arithmetic well-defined > enough that you can never do the same calculation two ways and get > different results? > > Example: bunches are three for a dollar. How much do you pay if you > buy nine bananas? > > Answer #1: > price_per_banana = 1.00 / 3 > number_of_bananas = 9 > total_price = number_of_bananas * price_per_banana > print total_price > > Answer #2: > price_per_bunch = 1.00 # three bananas > number_of_bunches = 3 > total_price = number_of_bunches * price_per_banana > print total_price Sorry, this is an argument I cannot accept. A discussion about decimal or floating arithmetic doesn't give the right to break basic rules of numeric computation. It is a known fact that division by a number that contains a prime factor relatively prime to the number base produces an error. I would fire such a programmer in any case, whether the error shows up in decimal math, or wether it hides due to graceful rounding rules in floating point. > With floating point and rounding on output, you get the same answer > both ways. Exercise: Find the extremes where this claim is proven wrong. Finally I see a big advantage in decimal math: Doing wrong numeric shows up earlier :-) ciao - chris -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 pager +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From fperez528 at yahoo.com Wed Oct 2 15:03:03 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Wed, 02 Oct 2002 13:03:03 -0600 Subject: bug/poor tracebacks while importing code References: Message-ID: Robin Becker wrote: > The underlying problem is that I want to determine the python machine > instruction that caused a bootstrap __init__.py to be imported as I wish > to transparently cause a different package to be substituted. I can do > this if the import is of the form 'import a', but not obviously if it is > 'import a.sub_a' or 'from a import sub_a' etc as I require to repeat the > required import with my __import__ magic in place. [snipped details...] Well, you seem to have a trickier problem in hand than I originally interpreted from the first posting. Probably others here can come up with better solutions. Good luck, f. From phr-n2002b at NOSPAMnightsong.com Tue Oct 8 17:13:59 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 08 Oct 2002 14:13:59 -0700 Subject: Integration References: Message-ID: <7xk7ks63c8.fsf@ruckus.brouhaha.com> Carolyn writes: > Now we are working on programming on integration. Can you suggest some > reference on that and random number generator?? Umm, the Numerical Recipes books by Teukolsky et al treat those subjects pretty well. Can you say more about the situation? Are you taking a numerical methods class with integration exercises? What algorithms are you supposed to use? Are you trying to use random numbers as part of your integration algorithm? Random numbers are used in some integration methods ("monte carlo methods"), usually for multi-dimensional problems. But normally in an intro numerical analysis class you won't do it that way. From aleax at aleax.it Sat Oct 5 08:09:55 2002 From: aleax at aleax.it (Alex Martelli) Date: Sat, 05 Oct 2002 12:09:55 GMT Subject: Which Linux distribution References: <814a0eba.0210050348.452ed9ab@posting.google.com> Message-ID: Jaroslav Gresula wrote: ... > What is your experience? What distribution would you recommend to me? > My primary requirement on the distrubution is to have a nice Pyton > environment with easy maintenance of multiple python versions. I use Mandrake (now 8.2, plan to switch to 9.0 come November, mostly for KDE upgrades) and always install Python from sources (multiple versions). It appears to me (from direct attempts with Mdk's RPM, and mostly from watching things at Strakt where Debian is used) that pre-packaged Python installs don't make it anywhere as easy to keep multiple versions, each with many add-ons. Alex From admin at e-tones.co.uk Sun Oct 20 14:56:56 2002 From: admin at e-tones.co.uk (e-tones.co.uk) Date: Sun, 20 Oct 2002 19:56:56 +0100 Subject: New to python Message-ID: <3db2fcc9$0$5803$fa0fcedb@lovejoy.zen.co.uk> Hi all, im new to python, i have an oriely book on order, should get me going. Are there any decent reference sites I can peek at (im a seased programmer btw, so the fundamentals will be fine). I see that if you want to use a function you have to import it from the library at the top (grr :P), anyhow, are there any more 'quirks' such as this I should know about ? Also, whats the easiest way to see what data type is help in a variable? eg string, integer etc. And last but not least, whats the best place to find the different exception handling techniques, the python.org site is obismal when compared to php.net and the likes :( About as much use as a dead dog :( Thanks to all who can help Cheers, Taz From marvelan at hotmail.com Thu Oct 10 15:17:47 2002 From: marvelan at hotmail.com (M) Date: 10 Oct 2002 12:17:47 -0700 Subject: How to stop a thread? Message-ID: How can I stop a thread that is waiting to handle a TCP socket? As there is no kill thread function in Python my first idea was to do a handle_request until I set a global magical_flag. But then I realised that this works only when I have a steady flow of connections comming in. Otherwise it will just hang (as it should) in handle_request and thus the thread would never stop. So, how can I stop the thread in the example below? I would like to stop it when user presses the "stop" button in some way. class Foo(Thread): def run(self): self.server = SocketServer.ThreadingTCPServer(addr, h) while not magical_flag: self.server.handle_request() From "gkrohnXvolucris.8m.com".replace Thu Oct 10 03:37:09 2002 From: "gkrohnXvolucris.8m.com".replace (Greg Krohn ("X", "@")) Date: Thu, 10 Oct 2002 02:37:09 -0500 Subject: [Newbie] Need help with quick text proggy. References: <24d8090a.0210091854.725f4c9f@posting.google.com> Message-ID: "Greg Krohn" <"gkrohnXvolucris.8m.com".replace("X", "@")> wrote in message news:ao39el02bel at enews1.newsguy.com... > > "Corey Woodworth" wrote in message > news:24d8090a.0210091854.725f4c9f at posting.google.com... > > I havn't programmed in python in a while (not since 2.0) but I just > > found myself in a predicament where I really need to write a program > > and write it fast. Python still seems to be the best choice even > > though I'm very rusty and wasn't to good to start with. Here is my > > problem. I've got a text file that is a list of elements. a time > > followed by a number on each line. Like this for example: > > > > 1:46p 65 > > 5:45a 99 > > 2:36p 88 > > 10:53a 79 > > 5:10a 86 > > 2:43p 169 > > 10:14a 55 > > > > I just found out that all my times are 6 hours off. (AARGH!) and I > > need some help writing a program that will update all those timestamps > > for me. Any help at all is appreciated, wheter it be links, some > > source, or whatever. Thank a bunch. > > > > Corey > > How's this: > [ SNIP My original crappy code.] That worked with your sample data, but not in all cases. Try this: fin = file('your/source/file', 'r') fout = file('your.output.file', 'w') for line in fin: try: colon = line.find(':') hour = int(line[:colon]) except ValueError: print 'Invalid hour: %s' % line continue try: space = line.find(' ') minute = int(line[colon + 1: space - 1]) except ValueError: print 'Invalid minute: %s' % line continue ampm = line[space - 1: space] if ampm == 'p': hour += 12 elif ampm != 'a': print 'Invalid am/pm indentifier: %s' % line continue value = line[space + 1:] hour += 6 hour = hour % 24 if hour > 12: hour -= 12 ampm = 'p' else: ampm = 'a' if hour == 0: #This is what I added hour = 12 #the second time around. fout.write('%d:%d%s %s' % (hour, minute, ampm, value)) fin.close() fout.close() From edream at tds.net Mon Oct 14 09:43:35 2002 From: edream at tds.net (Edward K. Ream) Date: Mon, 14 Oct 2002 13:43:35 GMT Subject: What I learned from the Cookbook (was...) References: Message-ID: In my first post on this thread I said I wouldn?t embarrass myself by telling all I learned in the first chapter. In this post I?ll tell instead what I discovered for myself after being inspired by the cookbook. Recipe 1.6, dispatching using a dictionary, discusses using a dictionary in lieu of, say, a C++ switch statement. Inspired by the Cookbook, I recast the main loop of my app?s colorizer as follows: while i < sLen: func = state_dict[state] i,state = func(s,i) This is a whole lot clearer, and probably faster than the old code. However, it probably wouldn?t have been interesting enough to do if I hadn?t been thinking of something more. I was thinking of the loop above in vague way, without having written it, and I was musing about state_dict as a (dynamic) data structure. I suddenly thought that Python allows us to _compute_ switch statements. In fact, this isn?t really correct: without heroic efforts we can?t really compute the contents of state_dict. That is, it wouldn?t be worth the effort to generate the state handlers themselves on the fly. But the intuition behind this first (slightly erroneous) thought is correct. We can compute _other_ data structures (dictionaries or lists) used by the state handlers. The effect is to compute what the state handlers do. Moreover, all the special case code that used to be in my app?s state handlers can be moved into the computation of the dicts and lists used by the state handlers. Of course, this isn?t really anything new: data-driven code should be a staple of any programmer?s repertoire. But Python makes it so much more natural and easy to do. For example, the jEdit editor contains XML files describing how to syntax color almost 70 different languages. I?d like my app to be able to use those descriptions. Here is a very brief description of what I plan to do. The known_languages dict will contain all the data structures needed to handle a particular language. This dict is created dynamically. Its keys are the names of each language; its values are tuples of other data structures. If known_languages were created statically it would look something like: known_languages = { "c" : (d1,...,dn), "python" : (d1,...,dn), ... } The members of each tuple, i.e., d1,...,dn are created by the initialization routine, something like this: # Get the data structures for language, the language to be colored. data = known_languages.get(language) if not data: # Parse the description file, creating the data structures. data = parse_xml_file(language) if data: known_languages[language] = data if data: # unpack the data for convenience of the state handlers. d1,...,dn=data Actually, most of the methods and data would be members of the colorizing class, and I?ve omitted all the "self" prefixes for clarity. This is about as elegant description of the problem as can be imagined. It rivals mathematical notation in its conciseness, power and generality, while being real Python code, except for the ellipses. It doesn?t get much better than this. Edward P.S. In theory, this scheme could be transliterated into C or C++. In practice, few C++ programmers would discover it: the implementation details would obscure everything, especially the thoughts that lead to the scheme in the first place. EKR -------------------------------------------------------------------- Edward K. Ream email: edream at tds.net Leo: Literate Editor with Outlines Leo: http://personalpages.tds.net/~edream/front.html -------------------------------------------------------------------- From Doc at goodweb.de Fri Oct 4 07:20:55 2002 From: Doc at goodweb.de (Thomas Korb) Date: 04 Oct 2002 13:20:55 +0200 Subject: McMillan / Tk / encoding problem Message-ID: Hi! I have a strange problem with an application written in Python using Tk as GUI. I do use the Tk text-widget (as a simple editor) and wrote some encoding functions for transforming iso-8859-1 to Unicode and the other way round (when loading text to the widget or when pasting from the clipboard etc. etc.). When running the application as a normal Python-script, everything works just fine. But after building a standalone executable (for MS Windows) with Gordon McMillan's Installer (newest version 5.x) this does not work any more. E.g. when saving text from the text-widget to a file, I end up with a Unicode-file and not with an iso-8859-1 encoded file. (This is always an issue when using Tk; but my transforming- functions are OK (on Linux and Windows) when running the script directly via Python; the problem only occurs when using McMillan's Installer.) I am *not* using the new --ascii switch of McMillan's installer; moreover, I think the problem comes from the Tk-side of the script (as some tests with 'pure Python' applications indicate). Does someone know this problem? Any help highly appreciated! (I googled for this problem and found one person who had the same problem when using the text-widget for a non iso-8859-1 language. But I could not find a solution to the problem.) -- ________________________________________________________________________ Dr. Thomas Korb / GOODWEB.DEsign / www.goodweb.de / Doc at goodweb.de From xx758 at cam.ac.uk Wed Oct 16 06:29:57 2002 From: xx758 at cam.ac.uk (Xiao-Qin Xia) Date: Wed, 16 Oct 2002 11:29:57 +0100 Subject: What is the class of myobj? References: Message-ID: I guess the following code is what you want: Class MyClass: pass myobj = MyClass() if myobj.__class__.__name__ == "MyClass": print "OK!" if myobj.__class__ == MyClass: print "OK!" Cheers, Xiao-Qin Xia JXStern wrote: > I want to write something like: > > If ClassOf(myobj) == "MyClass": print "OK!" > or > If ClassOf(myobj) == MyClass: print "OK!" # no quotes on class > > The best I've found in Python is based on str(myobj.__class__). > > What's the official way? > > Thanks. > > Newbie still, > Joshua Stern From rossi at earthling.net Sun Oct 13 04:57:44 2002 From: rossi at earthling.net (Thorsten Roskowetz) Date: Sun, 13 Oct 2002 10:57:44 +0200 Subject: Amazon review (was Re: Love "Python Cookbook") References: <%Dfp9.35332$cS4.1385227@news2.tin.it> Message-ID: Matthias Huening wrote: > By the way: Amazon has just reduced the price of the Cookbook > (EUR 48,12 > EUR 36,10 / $39.95 > $27.97). Considering that as of today a EUR is $0,9876 its quite a difference in pricing - is this all due to taxes? Thorsten From mlh at furu.idi.ntnu.no Mon Oct 14 18:49:43 2002 From: mlh at furu.idi.ntnu.no (Magnus Lie Hetland) Date: Mon, 14 Oct 2002 22:49:43 +0000 (UTC) Subject: [OT} How to un-GPL parts of a GPL'd module. References: Message-ID: In article , Steve Holden wrote: >"Anton Vredegoor" wrote in message >news:anujeq$qdk$1 at news.hccnet.nl... >> Hello All, >> >> how can I use a class or a function from a GLP'd module (cut-and-paste >> style) in a module with BSD or public domain style release? >> >You can't, without explicit permission from the copyleft holder. that's the >whole point of copyleft. But, clearly, this is a matter of how much code is copied, no? I mean, it's easy to make the case for minimal amounts (such as a single character, a language keyword, etc.) Where is the line drawn? I guess a "substantial amount" would have to be copied for it to be covered by the license, but since IANAL, I don't know how much that is. Depends on the functionality, I'd assume. -- Magnus Lie Hetland Practical Python The Anygui Project http://hetland.org http://ppython.com http://anygui.org From gmuller at worldonline.nl Sun Oct 13 16:18:47 2002 From: gmuller at worldonline.nl (GerritM) Date: Sun, 13 Oct 2002 22:18:47 +0200 Subject: experiments Message-ID: oops same mistake again, hit the send button before setting the correct address. Somehow the message appeared as header in my OE newsreader, but was flagged as non existing, so I did not yet cancel the message myself. apologies Gerrit -- www.extra.research.philips.com/natlab/sysarch/ "GerritM" schreef in bericht news:... > #attachement experiment.py only = fraction of apache logfile analyzer. From andrew.thompson at ashecastle.com Fri Oct 11 07:52:27 2002 From: andrew.thompson at ashecastle.com (Andrew Thompson) Date: Fri, 11 Oct 2002 12:52:27 +0100 Subject: newbie : removing recurring element from lists In-Reply-To: <79ca3316d31c4b96acf1edf99af926f9@Mark> Message-ID: <011101c2711c$b04e7530$4802a8c0@blair> But then it's not good English! Maybe we can have 'whilst' to be identical to 'while'! Andrew -----Original Message----- From: python-list-admin at python.org [mailto:python-list-admin at python.org] On Behalf Of Mark Rowe Sent: 11 October 2002 11:15 To: python-list at python.org Subject: RE: newbie : removing recurring element from lists On 2002-10-11 11:03:45 +0100 Andrew Thompson wrote: > Much better to let the machine do the work : > ' > > while aList.__contains__(yourValue): > aList.remove(yourValue) > > ' Its probably a bit cleaner to phrase that as while yourValue in aList: aList.remove(yourValue) HTH, Mark -- http://mail.python.org/mailman/listinfo/python-list From huaiyu at gauss.almadan.ibm.com Wed Oct 30 17:29:20 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Wed, 30 Oct 2002 22:29:20 +0000 (UTC) Subject: Find offsets and lengths from re References: Message-ID: Bengt Richter wrote: >On Tue, 29 Oct 2002 19:00:00 +0000 (UTC), huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) wrote: > >>Given a list of substrings, how to efficiently return a list of offsets and >>lengths of all occurances of these substrings in a piece of text? >> >>I can use string find, looping over substrings and locations. But this is >>too slow for a large number of texts. >> >>The speed of re.findall appears adequate, but I have not found a way to let >>re return offsets. What it returns is a list of substrings that matches. I >>can use this list in a loop of string.find. This reduces the original >>double loop into a single loop. This still takes quite some time. >> >>It would be more efficient if re can return offsets directly. Is there a >>way to do that? >> >Does this help? > >http://www.python.org/doc/current/lib/match-objects.html Thanks. This helps somewhat. I assume you mean using finditer and loop over the the match objects. This reduces the total running time of the program from 8m40s to 7m31s, the bulk of its time spent on finding these positions. If there is a way to return positions without using a Python for loop, I guess the running time can be halved. I'm willing to patch the re module if someone can point me to the right direction. Huaiyu From steve at ferg.org Thu Oct 10 10:14:32 2002 From: steve at ferg.org (Stephen Ferg) Date: 10 Oct 2002 07:14:32 -0700 Subject: OOing in Tkinter - help References: Message-ID: > How can i adjust the above so it will respond to whatever text widget the > call comes from. You might want to look at "Thinking in Tkinter" http://home.att.net/~stephen_ferg/thinking_in_tkinter/index.html tt077.py and the next couple of programs might be especially relevant. From gerrit.muller at philips.com Tue Oct 8 03:20:38 2002 From: gerrit.muller at philips.com (Gerrit Muller) Date: Tue, 08 Oct 2002 09:20:38 +0200 Subject: Is there a "reset" in Idle? References: Message-ID: <3DA28746.8793696F@philips.com> JXSternChangeX2R wrote: > > Another newbie question. > > After I've run a python program a few times and fixed a few bugs, it > seems that the name spaces are polluted with old values. Is there any > kind of a "reset" that clears everything without exiting and > restarting the process? > > Python 2.2 on XP Pro. > > Thanks. > > Joshua Stern This issue has been discussed here before. Especially new or naieve users do not over see the consequence of the ever increasing historic context. I just finished an e-mail conversation with a potential new user, who ran into the problem that import only works once and of course he didn't know the reload magic yet. This is also a problem which would be solved by a "reset". regards Gerrit -- -------------------------------------------------------------------- Gerrit Muller Philips Research Laboratories Eindhoven Building: WDC 2 - 007 Prof. Holstlaan 4 Phone: +31 40 27 45242 5656 AA Eindhoven Fax: +31 40 27 45033 The Netherlands mailto:gerrit.muller at philips.com http://www.extra.research.philips.com/natlab/sysarch/index.html From ykingma at accessforall.nl Sat Oct 5 08:54:57 2002 From: ykingma at accessforall.nl (Ype Kingma) Date: Sat, 05 Oct 2002 14:54:57 +0200 Subject: Simple lru cache? References: <3d9dfe86$0$124$e4fe514c@dreader6.news.xs4all.nl> Message-ID: <3d9ee06d$0$16087$e4fe514c@dreader4.news.xs4all.nl> Guido Goldstein schreef: > > Hi! > > On Fri, 04 Oct 2002 22:52:06 +0200 > Ype Kingma wrote: >> Hello, >> >> Does anyone know of a good lru cache implementation in python? >> I tried google, and found some things in zope, but these are >> more complicated than what I need. > > You might have a look at > http://www.a-nugget.org/downloads/LRUCache.py > > It's a time based lru-cache with manual or automatic shrink. > I think it's commented enough to get a rough understanding of how it > works. > > Of course, comments and suggestions are welcome. In my first attempt with the doubly linked list I store a doubly linked list element together with the user data. Such an element can be removed quite easily from the (lru) list it is in, after which it can be inserted in front. Also the final element can be removed when the cache fills up. For this the key needs to be stored in the doubly linked list element. You store a timestamp together with the user data in a dictionary so shrinking can be based on age. Such shrinking needs an extra effort periodically but it's probably more efficient. Thanks, Ype From stephane_klein at yahoo.fr Mon Oct 21 09:16:55 2002 From: stephane_klein at yahoo.fr (=?iso-8859-1?q?St=E9phane=20KLEIN?=) Date: Mon, 21 Oct 2002 15:16:55 +0200 (CEST) Subject: error in httplibs Message-ID: <20021021131655.72754.qmail@web13604.mail.yahoo.com> Hello, I use httplibs and I see one bug : when I use httplibs.request with headers parameter, I have one error at 714 lines in httplibs.py, it says : "'in ' requires character as left operand" I would like resolve this problem Thank you ___________________________________________________________ Do You Yahoo!? -- Une adresse @yahoo.fr gratuite et en fran?ais ! Yahoo! Mail : http://fr.mail.yahoo.com From robin at jessikat.fsnet.co.uk Wed Oct 2 11:09:39 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Wed, 2 Oct 2002 16:09:39 +0100 Subject: bug/poor tracebacks while importing code Message-ID: Is there some reason why we have poor code inspection during imports. b.py isn't mentioned in the traceback obtained in c.py in the following noddy example and this is limiting my ability to do nasty import tricks. This is with stock win32 2.2.1. C:\Python\tmp>cat b.py ''' BBBBBBBB ''' a=4 import c b=6 c=7 d=8 C:\Python\tmp>cat c.py ''' CCCCCCCC ''' a=4 b=5 c=6 d=7 def xxx(): import traceback, sys try: raise ValueError except: traceback.print_exc() xxx() C:\Python\tmp>b.py Traceback (most recent call last): File "C:\Python\tmp\c.py", line 11, in xxx raise ValueError ValueError C:\Python\tmp>rem no mention of the importing module WHY? -- Robin Becker From rajarshi at presidency.com Fri Oct 4 16:09:31 2002 From: rajarshi at presidency.com (Rajarshi Guha) Date: Fri, 04 Oct 2002 16:09:31 -0400 Subject: making a class return None from __init__ Message-ID: Hi, I have a class which makes some basic error checks in the __init__ function. Ideally, if the parameters passed to the __init__ function fail the checks I would like to return a None. But this does'nt seem to happen: class Graph: def __init__(self,v): if SOME_TEST: return None However when I test it out as: g = Graph(v) print g (where v will fail) I always get <__main__.Graph instance at 0xXXXXXX> Is there any way to make the constructor return a None object? Thanks, From melbohince at attbi.com Thu Oct 31 11:47:34 2002 From: melbohince at attbi.com (Mel Bohince) Date: Thu, 31 Oct 2002 16:47:34 GMT Subject: Newbie want Python CGI on Mac OS X10.2 Message-ID: I have a problem (many really), didn't really get too far, hope someone can help. Maybe you can reminisce when your problems were this easy. I got Apache/1.3.26 to run the http://127.0.0.1/cgi-bin/test-cgi that comes preinstalled. But when I put a very simple python script: #!/usr/lib/python print """Content-type: text/html hello world""" and I point to http://127.0.0.1/cgi-bin/simple.py the browser replies with an "Internal Server Error". Any clues for the clueless? -: -: -: -: -: -: -: -: \|/ -: -: -: -: -: -: -: -: cU Mel Bohince Pjt Mgr, Arkay Packaging Corporation feet at att.net http://home.att.net/~melbohince/ From claird at lairds.com Mon Oct 21 18:04:14 2002 From: claird at lairds.com (Cameron Laird) Date: Mon, 21 Oct 2002 22:04:14 -0000 Subject: Reports, PDF, and grid widget for Python? References: <3db41988@monitor.lanset.com> <87iszverj0.fsf@flibuste.net> <3db464b8@monitor.lanset.com> Message-ID: In article <3db464b8 at monitor.lanset.com>, Adams-Blake Co. wrote: . . . >2.What are the advantages of using the wxPython library? Is it more >cross-platform than Tkinter? More widgets? Easier to use? What? . . . People write whole articles on this subject. In fact, I'm one of those people: Briefly, wxWindows looks more modern, and has a LOT more widgets. The answers to the other questions are more complex--that is, am- biguous. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From aleax at aleax.it Sun Oct 6 16:09:06 2002 From: aleax at aleax.it (Alex Martelli) Date: Sun, 06 Oct 2002 20:09:06 GMT Subject: How to use the exec statement References: <3d9eca56_3@news.newsgroups.com> <3da02072_7@news.newsgroups.com> <020o9.15370$cS4.608697@news2.tin.it> <3da093bc_5@news.newsgroups.com> Message-ID: JB wrote: ... >> can avoid the worst problems: build an artificial >> namespace (i.e., a suitably prepared dictionary) in which >> these statements are to execute -- populate it with >> whatever set of names you think the user will need (module >> r_exec is also a possibility). > > How can I do this? namespace = {} # populate dict namespace with whatever you want, e.g.: import math namespace.update(math.__dict__) # etc etc Now, when it comes time to exec the user-given statement X, exec X in namespace This way the namespace will be the same from one such statement to the next. If you DON'T want that, e.g.: new_namespace = namespace.copy() exec X in new_namespace Now, if needed, you can examine namespace or new_namespace for any significant changes (settings/un-settings) that you want to take into account. BTW, you wouldn't have to write a parser anyway -- there are some you can use already in the Python standard libraries, and others you can download. But exec isn't too bad if [a] Python is the right language for the user to be using and [b] you use exec in a well-controlled manner. You'll probably want to have a try/except around the exec statement, for more precise error messages than just a program-crash, and if you need to exec the same statement repeatedly, look into built-in "compile" (you can compile the statement once, getting a code-object, then exec the code-object repeatedly). Alex From rjones at ekit-inc.com Thu Oct 17 01:41:43 2002 From: rjones at ekit-inc.com (Richard Jones) Date: Thu, 17 Oct 2002 15:41:43 +1000 Subject: Emulating a = x.y and x.y = a, when 'y' is a string In-Reply-To: <3DAE4B05.8010903@cygnus-software.com> References: <3DAE4B05.8010903@cygnus-software.com> Message-ID: <200210171541.43785.rjones@ekit-inc.com> On Thu, 17 Oct 2002 3:31 pm, Bruce Dawson wrote: > I want to do dynamic access to member variables in Python - reading from > and writing to object member variables based on a member name stored in > a string. If the member is stored in __dict__ it is easy enough, but > what if it is emulated with __getattr__, or a property, or > __getattribute__? Use the builtin function getattr() [and setattr() for setting] Richard From elwis at linuxmail.org Fri Oct 11 09:07:12 2002 From: elwis at linuxmail.org (stefane) Date: Fri, 11 Oct 2002 15:07:12 +0200 Subject: which GUI? Message-ID: <3da6cd00.0@d2o947.telia.com> Hello everybody! I've recently started to learn Python, really like the simplicity, and I would like to get some feedback to a question. Which GUI would be best considering platform independence, easy deployment, and the fact that a "rookie" is going to use it in his code ;) I played a little with Tkinter, noticed that a lot of tutorials on the web doesn't work anymore, and noticed that building a .exe on windows made "Hello World" grow to almost 5 M since it included the whole of Tk. Any thoughts are appreciated! regards /S From newsfroups at jerf.org Wed Oct 30 21:49:09 2002 From: newsfroups at jerf.org (Jeremy Bowers) Date: Thu, 31 Oct 2002 02:49:09 GMT Subject: Asking a user for the root password and executing root only commands... References: Message-ID: On Wed, 30 Oct 2002 14:02:17 +0000, Axel Vandevenne wrote: > It does require root access, (the program needs to be able to execute > /usr/sbin commands and edit root only files) but I don't want them to open > a shell, su, and then open this program in that shell -> and icon on their > taskbar should do the trick. > Also I don't want them to install/configure sudo (as suggested on #python). Use one of these solutions anyhow, despite your objections. You do not do the user a favor by trying to hide this *particular* bit of complexity of running a Linux machine, because it's *critical* to understanding what is going on in the box. I understand the impulse to simplify, and usually it's quite laudable, but this is a significant exception. Furthermore, you mention in a later reply this is for a Gentoo installer. This reinforces this point all the more; Gentoo is designed for people who know what they are doing. While I would love to see a better installer for it, understanding the importence of the sanctity of the root password is even MORE critical, and should not be smoothed over by any program. I would not be surprised that the Gentoo developers, who know their stuff, would also choke on this and might refuse to include this in the standard install, no matter how technically good the rest of the program might be, on this point alone. From jkraska at san.rr.com Sun Oct 13 13:10:58 2002 From: jkraska at san.rr.com (Courageous) Date: Sun, 13 Oct 2002 17:10:58 GMT Subject: [OT} How to un-GPL parts of a GPL'd module. References: Message-ID: >Since the BSD technology was published, any patents issued to Microsoft >which use the same technology are invalidated by the existence of "prior >art". Prior art has no legal power. It takes a case, and probably a good $10 million in legal fees, to get the legal power you're thinking of. Patents are real humdingers, even when prior art _ought_ to invalidate them. C// From hancock at anansispaceworks.com Fri Oct 18 16:57:56 2002 From: hancock at anansispaceworks.com (Terry Hancock) Date: Fri, 18 Oct 2002 13:57:56 -0700 Subject: Spell-check engine? In-Reply-To: <20021018200007.12387.54659.Mailman@mail.python.org> References: <20021018200007.12387.54659.Mailman@mail.python.org> Message-ID: On Friday 18 October 2002 01:00 pm, python-list-request at python.org wrote: > Anyone have a fairly standard spell-check engine available for use from > Python? ?That is, something with an interface something like this: I don't know of any ready-made solutions, and could use one myself, so if you find something, please post. I immediately imagine using a wrapper for ispell or aspell or the pspell library though I am ignorant of how to do that. I was able to find a few interesting leads, though: ispell: http://fmg-www.cs.ucla.edu/geoff/ispell.html aspell: http://aspell.sourceforge.net pspell: http://sourceforge.net/project/showfiles.php?group_id=2791 http://www.fifi.org/doc/libpspell-dev/man-html/manual.html The last is a library, which would suggest the strategy of using SWIG or Pyrex or some other python extension method to make the C++ library available to Python. Certainly these can do the things you want, and I have seen programs that use the libraries. > I'm interested primarily in the _engine_, I know where to get various > dictionaries of words, but I don't know of any free fuzzy-match engines > that give you suggestions given a body of words. ?I'd really like the > ability to have multiple loaded word-sets (with the ability to create > unions of the sets as seen above), but I can, I suppose, handle that at > the application level. Alternatively, if you want a pure-python approach, I'm pretty sure that the standard library module "difflib" could be persuaded to fuzzy-match words. It will fuzzy-match sequences, and a word can be regarded as a sequence of characters. E.g.: >>> l = list('hello') >>> l ['h', 'e', 'l', 'l', 'o'] But that's a long way from what you need, of course. > This is more curiosity than a real project issue (I just downloaded a > buggy spell-check for Mozilla). ?I was just wondering if it would be > feasible to wrap such a thing in Corba and COM wrappers and make it a > generic cross-platform OS service so that projects such as Open Office, > Mozilla and even proprietary software could share the same engine (and > the same dictionaries). ?Would want to provide some management UI stuff > (control-panel app on Windows, not sure what on Linux) for > adding/removing word-sets, exporting word-sets for backup, sharing and > the like, but that'd be pretty simple compared to the services > themselves. ?Might also need policy control for user versus system > dictionaries I suppose. Sounds ambitious, but I think a pspell wrapper would probably fill the bill. I did a brief google search without finding such a thing already written, but it wasn't exhaustive -- you might want to look a little harder before deciding to implement one. But it's probably not *that* hard to implement, either. I suppose I might attempt it myself someday -- but I have a big stack of higher priorities to get through before I could even consider it. Best of luck. Cheers, Terry -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From shagshag13 at yahoo.fr Tue Oct 22 04:44:34 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Tue, 22 Oct 2002 10:44:34 +0200 Subject: strip not well formed html tags... Message-ID: hello, i've seen many post about how to strip html tags from a string, some use sgmllib, others regular expressions... i 'd the following trouble i would like to strip html (or even xml) tags but i had to work on incomplete string so they could be not well formed - what should i use ? regexp ? sgmllib with many exceptions handling ? Thanks in advance for yours advices ? s13. From dave at alpha1.csd.uwm.edu Tue Oct 22 12:20:37 2002 From: dave at alpha1.csd.uwm.edu (Dave Rasmussen) Date: 22 Oct 2002 16:20:37 GMT Subject: building 2.2.2, g++ Dec Unix 4.0G Message-ID: I was wondering if anyone else has built python on DEC Alpha boxes and had a fix for me below. We have a 1.5* version here. I don't know python but my site wanted to try mailman. I have this icky feeling that our g++ probably also needs updating. >From my make for 2.2.2 cc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONFIG_H -o Python/thread.o Python/thread.c In file included from /usr/local/gnu/lib/gcc-lib/alphaev56-dec-osf4.0d/2.8.1/inc lude/pthread.h:333, from Python/thread_pthread.h:9, from Python/thread.c:113: /usr/include/c_asm.h:190: parse error before `asm' In file included from Python/thread_pthread.h:9, from Python/thread.c:113: /usr/local/gnu/lib/gcc-lib/alphaev56-dec-osf4.0d/2.8.1/include/ pthread.h:1709:parse error before `destructor' /usr/local/gnu/lib/gcc-lib/alphaev56-dec-osf4.0d/2.8.1/include/ pthread.h:1709: parse error before `)' /usr/local/gnu/lib/gcc-lib/alphaev56-dec-osf4.0d/2.8.1/include/ pthread.h:1717: parse error before `destructor' /usr/local/gnu/lib/gcc-lib/alphaev56-dec-osf4.0d/2.8.1/ include/pthread.h:1717: `pthread_key_create_new_np' declared as function returning a function /usr/local/gnu/lib/gcc-lib/alphaev56-dec-osf4.0d/2.8.1/include/ pthread.h:1718: parse error before `int' *** Exit 1 Stop. ~ From jdhunter at ace.bsd.uchicago.edu Tue Oct 8 14:48:48 2002 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Tue, 08 Oct 2002 13:48:48 -0500 Subject: Installing pyMySQL In-Reply-To: (Lindstrom Greg - glinds's message of "Tue, 8 Oct 2002 13:40:43 -0500") References: Message-ID: >>>>> "Lindstrom" == Lindstrom Greg <- glinds > writes: Lindstrom> Hi, all- I am having a world of trouble installing Lindstrom> pyMySQL on my Windows NT 4.0 box (ActiveState Python Lindstrom> 2.2.1). My current problem occurs when I am trying to Lindstrom> execute setup.py install when the linker complains Lindstrom> about not being able to find mysqlclient_r.lib (sure Lindstrom> enough...I can't fine it, either :-). Can any of you Lindstrom> help me out? Or is there a more windows friendly Lindstrom> database interface to use? This is a new library that ships with more recent versions of mysql. The easiest fix is to edit setup.py and replace this line mysqlclient = thread_safe_library and "mysqlclient_r" or "mysqlclient" with mysqlclient = thread_safe_library and "mysqlclient" John Hunter From Oschler at earthlink.net Fri Oct 18 15:42:32 2002 From: Oschler at earthlink.net (Robert Oschler) Date: Fri, 18 Oct 2002 19:42:32 GMT Subject: SOAP questions Message-ID: This is a bit of a complex question so let me lay out my application for you. I'm working on a GUI IDE tool that allows a user to build web pages that have integrated access to a foreign (external) web server that is also a provider of SOAP services. The GUI IDE tool, when the user is done working with it, generates HTML/XML pages that can be viewed in an Internet browser and are basically the user's "web site". My original intent was that the user could then upload the pages to whatever web server that hosts their web site, whether it is Apache, Zope, IIS, or something else. Now from within the GUI IDE, which is a Delphi application, I can do runtime access of the SOAP service _provider_ with some calls to a Python script that performs the SOAP XML code generation and submission, and then parses the resulting XML document returned from the service provider. The sticking point occurs here: as far as I know the only way I can parse the XML document returned from the SOAP call is via some process or CGI script that is run by the web server, right? A more concrete example. The user decides to put a search of the SOAP provider's product inventory on their web page, and the results are shown in a list box on the web page. I let them build and test this functionality from within the GUI IDE, by using the python interface script. Now when I generate the the web page to actual HTML/XML code, I know I can include the needed SOAP call packaged up as an embedded XML fragment in the web page. The problem is, and I'd love to be wrong here as far as my current understanding of SOAP goes, the web server running the users web page will have no idea what to do with the XML document returned by the SOAP call, correct? My desire is to make the generated pages to be as portable as possible across multiple web servers. But I'm guessing that at least at first, I'll have target the biggest web server package, currently Apache, and develop some sort of module for it that handles the returned SOAP calls and then probably does some HTML template code processing where I fill in variables with the SOAP results. I'm already worried about what kind of collisions might occur between my module and any other SOAP modules the host site manager might have installed. Also, I guess I'll have to then create other modules for each platform I wish to support (IIS, etc.), correct? If anyone has any great ideas on how to do this simpler please let me know. Also, anywhere my knowledge is incorrect, again, please let me know. Lastly, if XML-RPC would be any easier or better, please tell me what the differences might be. I'm assuming it would have the same incoming XML SOAP doc processing problems that SOAP does. thx From tjreedy at udel.edu Tue Oct 8 09:21:10 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 8 Oct 2002 09:21:10 -0400 Subject: appending to beginning of line References: <1001ff04.0210080422.1e373e13@posting.google.com> Message-ID: "Bob" wrote in message news:1001ff04.0210080422.1e373e13 at posting.google.com... > # loop through the list and print the lines to a file > for line in inFile.xreadlines(): > for badword in kw: > if line.find(badword) > -1: > found = '%s %s' % (badword, line) > print found # Print the result > outFile.write(found) # replace with > This will print the badword and then the line it is on. For those > lines that do not contain a badword I want to place a hyphen "-". Is this what you are looking for? for line in inFile.xreadlines(): ok = True for badword in kw: if line.find(badword) > -1: found = '%s %s\n' % (badword, line) print found, # Print the result outFile.write(found) # replace with outfile.write(found+'n') # Write the result ok = False if ok: line = '- ' + line print line, outFile.write(line) Terry J. Reedy From LONGS-SA at GroupPublishing.com Mon Oct 14 14:22:40 2002 From: LONGS-SA at GroupPublishing.com (System Attendant) Date: Mon, 14 Oct 2002 12:22:40 -0600 Subject: ScanMail Message: To Sender virus found or matched file blocking setting. Message-ID: <718171821FEED311BD3200508B8BE2210886762D@longs.grouppublishing.com> ScanMail for Microsoft Exchange has taken action on the message, please refer to the contents of this message for further details. Sender = python-list at python.org Recipient(s) = scoley at grouppublishing.com; Subject = A IE 6.0 patch Scanning Time = 10/14/2002 12:22:39 Engine/Pattern = 6.150-1001/365 Action on message: The attachment Bzj.bat matched file blocking settings. ScanMail has taken the Moved action. The attachment was moved to C:\Program Files\Trend\Smex\Alert\Bzj3dab0b6f467.bat_. 10/14/2002 12:22 PM python-list at python.org Warning to sender. ScanMail detected a virus in an email attachment you sent to scoley at grouppublishing.com; with a subject of A IE 6.0 patch. -------------- next part -------------- An HTML attachment was scrubbed... URL: From peter at engcorp.com Mon Oct 7 20:33:31 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 07 Oct 2002 20:33:31 -0400 Subject: Strange compiler warning References: Message-ID: <3da227db$1@news.sentex.net> Robin Becker wrote: > with 2.2.1 I get the message > > SyntaxWarning: name '_dbg' is assigned to before global declaration with > the following code, but things seem to be working, so is the compiler > wrong or too lazy to see the globals on all paths? How should one do > this sort of on the fly local debugging? > > ...... > if not globals().has_key('_dbg'): > global _dbg > _dbg=open('/tmp/_dbg.txt','w') > else: > global _dbg > print >>_dbg,'=======================\n' + text It's a little unclear what you want, but this looks better: global _dbg try: _dbg except NameError: _dbg = open('/tmp/_dbg.txt', 'w') print >>_dbg, '=====\n' + text Basically: 1. the "global" statement applies for the following scope of the function, so you need only one, 2. you can check if it exists simply by trying to reference it, 3. using exceptions is generally better than not. But what are you really trying to accomplish? -Peter From fredrik at pythonware.com Sat Oct 12 06:21:58 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 12 Oct 2002 10:21:58 GMT Subject: Is there a "reset" in Idle? References: <0rc7qu4l03ga7cdpifce8je632mlcju1fi@4ax.com> Message-ID: Alex Martelli wrote: > ... > > If I had any influence in the development of Python as a whole, I'd > > urge the developers to divert their attention away from sexy new > > language features and concentrate for a couple of releases on > > addressing shotcomings that shag the IDEs. > > I don't think there are any. As long as the IDE runs the Python > application being debugged in a separate process (a pretty obvious > need -- pity that neither IDLE nor PythonWin do that), what would > those shortcomings be? lack of support for in-process editing of Python code (reload doesn't help much). and a ton of other things that I cannot think of right now. (it's all in the PythonWorks bug/request/idea/bluesky data- base...) From kstc at box43.pl Tue Oct 8 17:09:15 2002 From: kstc at box43.pl (Krzysztof Stachlewski) Date: Tue, 8 Oct 2002 23:09:15 +0200 Subject: win32cliboard behavior References: <7n9vna.5f51.ln@boundary.tundraware.com> Message-ID: "Tim Daneliuk" wrote in message news:i9avna.lg51.ln at boundary.tundraware.com... > Well, I discovered the problem (and solution) but I don't understand it. > Apparently, one must *empty* the clipboard before a write to it > is globally visible - apparently emptying it is required to "own" > the clipboard. Can one of you windows gurus 'splain why this is so? > I would expect the clipboard to just be readable and writable by everyone... It is apparently a kind of lock, so noone else can write into clipboard while you are doing it. Stach From gerhard.haering at opus-gmbh.net Thu Oct 10 05:28:39 2002 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 10 Oct 2002 09:28:39 GMT Subject: pygresql and primary key References: Message-ID: Marcin Kadziolka [2002-10-10 08:48 GMT]: > Hi! > > I'm using a pg module wrapper from pygresql. Ouch. I'd recommend you use a DB-API module like pyPgSQL or psycopg. PyGreSQL has a DB-API module called pgdb, too. > I cannot use a get() method for tables containing primary keys definied for > more than one field. It seems get() assumes primary key always consists of > exactly one field. Yes. > How can I force it to use multiple column primary key? You can't without changing the source in pg.py. Why not just use SQL and a DB-API module? -- Gerhard From spam at melkor.dnp.fmph.uniba.sk Fri Oct 18 02:53:41 2002 From: spam at melkor.dnp.fmph.uniba.sk (Radovan Garabik) Date: Fri, 18 Oct 2002 08:53:41 +0200 Subject: no struct.pack for unicode strings? Message-ID: Why there is no format to pack/unpack unicode strings? Or am I missing something? My application needs to struct.pack unicode strings, to save them into a file which can be then read by a C extension module where I need to access characters of the string (as Py_UNICODE). -- ----------------------------------------------------------- | Radovan Garab?k http://melkor.dnp.fmph.uniba.sk/~garabik | | __..--^^^--..__ garabik @ fmph . uniba . sk | ----------------------------------------------------------- Antivirus alert: file .signature infected by signature virus. Hi! I'm a signature virus! Copy me into your signature file to help me spread! From cbbrowne at acm.org Fri Oct 18 13:42:16 2002 From: cbbrowne at acm.org (Christopher Browne) Date: 18 Oct 2002 17:42:16 GMT Subject: SOAP frustrations References: <3DAC6F04.2030704@mindspring.com> <23891c90.0210170137.481cda6@posting.google.com> Message-ID: After takin a swig o' grog, "Robert Oschler" belched out...: > "Christopher Browne" wrote in message > news:aomqcm$o4u41$3 at ID-125932.news.dfncis.de... >> Note that I've books in print that demonstrate the use of both CORBA >> and SOAP using Python; while "future royalties" commend the idea of my >> commending interest in SOAP, I certainly prefer CORBA... > > What is the best book you have out for an advanced level programmer > (for SOAP)? /I/ have only one; see the URL below. I have looked at many of them, and there is /considerable/ variation in the nature of the material they cover. My book has the most detailed presentation (plug! plug! I am not unbiased :-)) that I am aware of about the use of SOAP::Lite, so if you're into Perl, which is almost certainly the best "SOAP for scripting languages" implementation, I would /strongly/ commend it. (Irrespective of my bias as author.) It has decent coverage of Axis (the Apache project's Java-based imp), and says more about Python SOAPs than any other book I am aware of. Unfortunately, in that regard, it's arguably a little obsolete already, as it has considerable discussion of ZSI, which is no longer being worked on. A lot of the books on the market on the subject have been rushed into place, and spend a whole lot more time discussing XML standardsthan they do getting into the "meat" of how to do sophisticated things with SOAP. As such, /they suck/, and you'll probably find little point in buying them. In the "MSFT/Java-frameworked" approaches, WSDL (analagous to CORBA IDL) is a /totally vital/ piece, whereas in implementations of SOAP for Python, Perl, Ruby, and such, WSDL is virtually irrelevant/useless. That's almost certainly the most vital thing that determines which "direction" you'd want to take: - /My/ operating (and authoring) assumption is normally that WSDL is useless, because SOAP::Lite and SOAP.py and SOAP4r make minimal if any use of it. - Someone talking about .NET-based SOAP will make the exact opposite assumption, that WSDL is pervasive, ubiquitous, and mandatory in order to make the slightest use of SOAP. Those are totally divergent (though, in their respective contexts, legitimate) perspectives, and may be helpful in determining what "literary" direction to take. Most books take the "WSDL-is-pervasive" perspective, though not usually consciously. If what you want is to do "sophisticated SOAP stuff" in Python, I'm not sure what your best choice is. The implementations suck fairly badly, and supporting companies have gone out of business, so that there's little code worth documenting. My book probably has the most relevant Python coverage, but there's some risk that you'll feel teased, as it may not get as 'advanced' as you want. On the other hand, since the implementations aren't likely to be as 'advanced as you want,' there is no hope of there being a /better/ option. -- (concatenate 'string "chris" "@cbbrowne.com") http://cbbrowne.com/info/soap.html Rules of the Evil Overlord #169. "If I have massive computer systems, I will take at least as many precautions as a small business and include things such as virus-scans and firewalls." From emile at fenx.com Tue Oct 29 09:54:44 2002 From: emile at fenx.com (Emile van Sebille) Date: Tue, 29 Oct 2002 06:54:44 -0800 Subject: On The Naming of Things References: <20021029105751.GA7836@phd.pp.ru> Message-ID: Oleg Broytmann: > http://www.oreillynet.com/pub/wlg/2225 Almost funny in light of TMTOWTDI: Python resists making major library decisions preferring to leave it to the individual, while Perl's 'first-through-the-gate-naming' wins the standard. -- Emile van Sebille emile at fenx.com --------- From spirit_of_amiga at h-o-t-m-a-i-l.com Thu Oct 10 11:27:17 2002 From: spirit_of_amiga at h-o-t-m-a-i-l.com (Spirit of Amiga) Date: Thu, 10 Oct 2002 11:27:17 -0400 Subject: encoding python scripts References: <291p9.17755$ZO1.822767@news20.bellglobal.com> Message-ID: Thanks guys. You've more or less nipped this thread at the bud. Looking forward to becoming better acquainted with Python. Rick From dale at riverhall.NOTHANKS.co.uk Fri Oct 11 11:37:09 2002 From: dale at riverhall.NOTHANKS.co.uk (Dale Strickland-Clark) Date: Fri, 11 Oct 2002 16:37:09 +0100 Subject: Is there a "reset" in Idle? References: <0rc7qu4l03ga7cdpifce8je632mlcju1fi@4ax.com> Message-ID: Michael Hudson wrote: >Dale Strickland-Clark writes: > >> If I had any influence in the development of Python as a whole, I'd >> urge the developers to divert their attention away from sexy new >> language features and concentrate for a couple of releases on >> addressing shotcomings that shag the IDEs. > >A couple of points: > > 1) what shortcomings are these? Only a few but critical to the re-usability of the debugging environment. I don't remember the technical details but I'm sure Google will find the issues if you're really interested. > 2) this isn't how OS development works, and you surely know this. > Who mentioned OSes? I don't understand the relevence of this. >The only people paid to work on Python are at PythonLabs, who are paid >by ZC, who in turn probably don't have an overriding interest in >interactive debugging. Everyone else works on Python because it's fun >and to scratch an itch, basically. If you try to make us do what you >want rather than what we want, we stop. I'm aware of this. However, surely some of the enjoyment comes from knowing others are using your efforts? Can you imagine the boost Python would get in the programming comminity if a killer IDE appeared on the scene? > >OTOH, if you can come up with concrete suggestions, I'm all ears. Suggestion: Address the problem in Python that prevents IDEs from reloading modules and re-using a debuggin environment. -- Dale Strickland-Clark Riverhall Systems Ltd From gbrunet at sempersoft.com Wed Oct 9 09:08:12 2002 From: gbrunet at sempersoft.com (Greg Brunet) Date: 9 Oct 2002 06:08:12 -0700 Subject: Why is del(ete) a statement instead of a method? References: Message-ID: Chad (and others): Thanks for the response, though (and you are probably expecting this response): > Because del works on a lot more than just lists; you can 'del' any object > (although it doesn't mean the object actually is deleted from use; typically > it just means the local reference to it is removed) So why don't all objects support a .del method? That would seem to be the most consistent behavior. Then you could still use .remove(value) to remove by value, and .del(index) to remove by index, and .del() to delete the whole list. I agree for the need for a .del action (statement / function / method). I just don't understand why it's not a method. For me, in addition to being more consistent, another (admittedly minor) advantage of having it as a method is that the IDE's do a better job in Auto-Completing and prompting me for arguments with methods than with it as a statement. -- Greg From pobrien at orbtech.com Tue Oct 1 14:54:54 2002 From: pobrien at orbtech.com (Patrick K. O'Brien) Date: Tue, 1 Oct 2002 13:54:54 -0500 Subject: ANN: Python User Group for St. Louis, MO Message-ID: There is a new St. Louis Python User Group now forming, and we already have a website, mailing lists, SourceForge project, and more. If you live in the St. Louis, Missouri area and have any interest in using or learning Python, Jython or Zope, feel free to join us at http://www.pystl.org/. Pat -- Patrick K. O'Brien Orbtech ----------------------------------------------- "Your source for Python programming expertise." ----------------------------------------------- Web: http://www.orbtech.com/web/pobrien/ Blog: http://www.orbtech.com/blog/pobrien/ Wiki: http://www.orbtech.com/wiki/PatrickOBrien ----------------------------------------------- From rpcee at operamail.com Sat Oct 5 19:15:27 2002 From: rpcee at operamail.com (rpcee ) Date: Sat, 05 Oct 2002 23:15:27 +0000 Subject: XML Library from Message-ID: <20021005231527.24872.qmail@operamail.com> from what i remember it's a bit of an odd book: it should be titled "using pyxie (I think that was the name)", which is the authors XML library that converts XML to/from a simplified text format so you can leverage normal text processing tools. There's a review on ibm.com/xml somewhere, which said the library was buggy, I think too you will find some python/xml articles there. Oreilly python/xml was more conventional: DOM/SAX etc. ----- Original Message ----- From: "Will Ganz" Date: Sun, 3 Oct 2004 20:38:14 -0500 To: , , Subject: XML Library from "XML Processing with Python" > The book "XML Processing with Python" comes with a companion CD that has > several programs on it for Python 1.5.2. I have ActivePython 2.2.1 > installed on a W2K machine. Is installing "xmln.exe", "xmlv.exe", "Mark > Hammond's Win32 extensions", and "Python XML library from XML-SIG" a GOOD > THING? Or will I thoroughly hose my Python 2.2.1 install? > > I am just converting over from that other "P" scripting language and am > having to do a crash course on how to handle XML. Is this book still a good > reference or is it too dated already? (I got it at the $4.99each discount > store so I didn't lose that much if it is already an antique). > > > Thanks, > > _______________________________________________ > ActivePython mailing list > ActivePython at listserv.ActiveState.com > To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs > Other options: http://listserv.ActiveState.com/mailman/listinfo/ActivePython > > -- __________________________________________________________ Download the FREE Opera browser at www.opera.com/download/ Free OperaMail at http://www.operamail.com/ Powered by Outblaze From lozinski at openstepnews.com Tue Oct 22 07:34:50 2002 From: lozinski at openstepnews.com (lozinski at openstepnews.com) Date: Tue, 22 Oct 2002 04:34:50 -0700 (PDT) Subject: Job Market Software Written in Python In-Reply-To: <20021022104602.21299.97190.Mailman@mail.python.org> Message-ID: <1021022043450.16993AAC/C.lozinski@maya> I have completed a job market product in Python and zope. It only takes me two hours to bring up a new job market. I am curious if anyone is interested in starting a job market using my software. I am so grateful to all the people who contributed open source products which are being used in my application. Regards Chris 1-510-740-6486 lozinski at openstepnews.com lozinski at jobmart.com From jepler at unpythonic.net Thu Oct 10 15:31:42 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 10 Oct 2002 14:31:42 -0500 Subject: Guidelines for a fresh starter In-Reply-To: <05ibqusfqk123aloa42fm4tr0beifq3kep@4ax.com> References: <05ibqusfqk123aloa42fm4tr0beifq3kep@4ax.com> Message-ID: <20021010193141.GA16228@unpythonic.net> On Thu, 10 Oct 2002 20:13:04 +0200, "rodion" wrote: > >have to understand what i read so i would like someone to recommend books, > >url's, etc...where i can make a start. > On Thu, Oct 10, 2002 at 09:01:23PM +0200, Rhymes wrote: > one above all: http://www.freenetpages.co.uk/hp/alan.gauld/ Is this text really very good? For instance, in the section "What's in a name" (the second one I read), the author confuses the "print" statement/keyword with a "'builtin-scope' name": def spam(X): #... if Z > W: # print is a 'builtin-scope' name print "2 x X is greater than X + 5" For the real story on "print", see http://python.org/doc/ref/keywords.html http://python.org/doc/ref/print.html For the real story on locals, module globals, and builtin variables, see http://python.org/doc/ref/execframes.html Jeff From andy at reportlab.com Sat Oct 5 04:21:23 2002 From: andy at reportlab.com (Andy Robinson) Date: Sat, 05 Oct 2002 09:21:23 +0100 Subject: Python + Win32: Cut/Paste w/o GUI References: <5dukna.oh1.ln@boundary.tundraware.com> Message-ID: >Disclaimer: I'm *much* more comfortable with Unix innards than Win32, so if >the question I am about to ask is stoopid, please bear with me... > > >I want to be able to do the following but am unclear if/how it can be done: > >1) Write a non-GUI Python script. > >2) Create a shortcut in Win32 to that script. > >3) Copy text from an arbitrary Win32 application. > >4) Paste the copied text to the aforementioned shortcut/python script and > have that pasted text be somehow available (argv[] ???) for use by that > script. You need a "helper app" which can respond to events - most probably a GUI. I have done similar things in Delphi in the past, inspired by NextStep which had a wonderful "services" features like this. (In NextStep you could write scripts to do something to a chunk of text, 'register' them on a special menu, and have them available in any app to manipulate the current text selection). Tha app could accept a command line argument which is the default Python script to run, so you can make many desktop links to it. I suggest that when invoked it grabs text off the clipboard, manipulates and pastes it back. To genuinely drag and drop text, you probably need a running app, either in a little window or in the system tray - not just a desktop icon. This sounds like a neat little excuse for a generic utility of interest to all Python users - wish I had more time these days :-) - Andy Robinson From gerhard.haering at gmx.de Sat Oct 19 11:07:09 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 19 Oct 2002 15:07:09 GMT Subject: hostid? References: Message-ID: Lance wrote in comp.lang.python: > I'd like to retrieve a computer's hostid. Does anyone know how to do > this? I'm not familiar with the term "host id". In which context does this host id occur? You don't mean the fully qualified domain name or the MAC address, do you? -- Gerhard From see_reply_address at something.invalid Wed Oct 2 21:51:02 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Thu, 03 Oct 2002 13:51:02 +1200 Subject: Larry Wall's comment on python... References: <3D8E6353.7030303@something.invalid> <3D911A1B.1000109@something.invalid> Message-ID: <3D9BA286.8070801@something.invalid> Courageous wrote: > In practice, of course, the developer in question will > very likely strike the tab key to get as far as they can to the first > element of the second line. I'm always very aware of the issue when working on my own code, but I take your point that others may not be so careful. I usually convert to all-spaces before giving my code to anyone else. By the way, I never write function calls that way. I would write it as def long_function_name(argument1,argument2, argument3,argument4): mainly because I think it looks less ugly and doesn't waste so much horizontal space, but it also has the benefit of being less prone to tab/space screwups. On the other hand, I do often line things up in comments, e.g. class Spam: # Instance variables: # amount integer # flavour string and I'm careful to always use tabs-only before the # and spaces-only after it. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From jpm at papercut.org Tue Oct 1 09:23:22 2002 From: jpm at papercut.org (Joao Prado Maia) Date: Tue, 1 Oct 2002 09:23:22 -0400 (EDT) Subject: Question about __getattribute__/__getattr__ In-Reply-To: <20021001014234.Z30315@prim.han.de> Message-ID: On Tue, 1 Oct 2002, holger krekel wrote: > For caching a function's results why do you need __getattr__? > Because with __getattr__ it will work transparently, even if I add new methods to the cached class, or change the name of an existing one. Instead of having to create one method for each method in the cached class, I just use __getattr__ to receive all calls and apropriately cache the results. > It seems you really need another caching policy than the prescribed > memoize pattern. For example, you may implement a dictish object that evicts > old cached values by means of counting accesses, oldest access times > or whatever. I still see no use for expecting __getattr_ to know about > the arguments. Not? > A dictionary approach is not good enough for my needs, as it will eventually hold too much data in memory. As I explained before, saving the method return values in md5()'ed named files is the best solution I can think of. But going back to the subject, I need the arguments on __getattr__ so I can create unique filenames for the method call signatures. That is, calling a method like this: t.real_method('spam') would create a filename as: filename = md5.md5().digest('%%' % ('real_method', 'spam')) While the following method call: t.real_method('eggs') would create a filename as: filename = md5.md5().digest('%%' % ('real_method', 'eggs')) This way you can see that both method calls would be cached in different files. To see if the method call was already cached, I just need to see if the file exists. I hope this explained a little better the rationale behind the question. :) Cheers, Joao From ejeandel at ens-lyon.fr Thu Oct 31 23:53:42 2002 From: ejeandel at ens-lyon.fr (Emmanuel Jeandel) Date: Fri, 1 Nov 2002 05:53:42 +0100 Subject: Classes question References: <20021031205456.GA8006@ens-lyon.fr> Message-ID: <20021101045342.GA1737@ens-lyon.fr> Il est arriv?, un jour, ? Aahz d'?crire : > In article <20021031205456.GA8006 at ens-lyon.fr>, > Emmanuel Jeandel wrote: > > > >I have the following code : > > > >class A: > > def __init__(self): > > pass > > > > def f(self): > > self.x = B() > > > >class B(A): > > def __init__(self): > > A.__init__(self) > > > > > >I would like to have the class A and the class B in two differents files. > >Is it possible ? > >I think that it is not directly possible, but if there is a mean with a > >small change in the code... > > Assuming you put the code for A in classA.py, you can make class B work > by adding the line > > from classA import A > > before the "class B" statement. Obviously no. Please note that A needs to know about B in this example (line: self.x = B() in the class A). If i keep the same examples, and copy them in files classA and classB then i. Add "from classA import A" in classB.py ii. Create C.py with : import classA import classB a = classA.A() b = classB.B() a.f() I get an undefined in a.f() ( even if i replace B() par classB.B() ) Of course, if i do "from classB import B" in classA.py, i have a cyclic dependence, and this not works (cannon import name A). I don't know is there is a solution, i'm just asking.. Emmanuel From marklists at mceahern.com Wed Oct 2 12:31:58 2002 From: marklists at mceahern.com (Mark McEahern) Date: Wed, 2 Oct 2002 11:31:58 -0500 Subject: Merging lists has made my brain hurt. In-Reply-To: <3D9B1953.3030109@moving-picture.com> Message-ID: > I want to merge the three lists into a single list that only contains > the strings present in all three lists. In the above case I want to end > up with > ['ccc'] Python 2.3 will include a set type: http://www.python.org/dev/doc/devel/whatsnew/intro.html In the meantime, try this recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/138982 // m From cbbrowne at acm.org Wed Oct 16 00:23:33 2002 From: cbbrowne at acm.org (Christopher Browne) Date: 16 Oct 2002 04:23:33 GMT Subject: All Your Python Are Belong To Us References: Message-ID: Quoth Andres Rosado : > At 05:41 AM 10/10/2002 -0400, you wrote: > > Or, more concisely: "All your stuff belong to us"? :-) > > I think it's spelled "are belong to us" (I've seen "are belongs" too, > but I believe that's wrong grammar...). > > A very famous grammar error... Actually, the "correct" phrasing is: "All your base are belong to us!" http://www.allyourbase.net http://www.planettribes.com/allyourbase/index.shtml http://www.classicgameroom.com/allyourbase/ The truly best parody of it is the Sesame Street one: http://www.thegamegroove.com/images/sesamebase.jpg -- (concatenate 'string "cbbrowne" "@acm.org") http://www3.sympatico.ca/cbbrowne/languages.html "... and the REALLY GOOD THING, is that after you have gone to the trouble of compiling that once, you can run it MANY MANY times!!!" -- Arthur Norman From creyes at ea.com Tue Oct 15 18:15:20 2002 From: creyes at ea.com (Christian) Date: 15 Oct 2002 15:15:20 -0700 Subject: Oracle DB module for Python Windows98 Message-ID: Does anyone know of an Oracle DB module for Python Win98? I've seen the DCOracle module at zope and that appears to only run through NT or 2K. TIA, Christian From i.linkweiler at web.de Wed Oct 16 05:10:48 2002 From: i.linkweiler at web.de (Ingo Linkweiler) Date: Wed, 16 Oct 2002 11:10:48 +0200 Subject: International APPs / pygettext References: <3DAC5E22.1060102@web.de> <3DAD2741.8040903@web.de> Message-ID: <3DAD2D18.7000108@web.de> ... and what to do now? I have replaced some strings by _("string"), and started pygettext. The result was a "messages.pot" file like this: #: PyNassi.py:121 msgid "&New Editor" msgstr "" Where can I add the translations? And what?s the next step? "msgfmt" needs a ".po"-file, not a ".pot" file. What can I do, when some smaller changes are made on the source file? Is it possible to "update" the translation files without creating a new one? Ingo From aahz at pythoncraft.com Thu Oct 31 16:08:33 2002 From: aahz at pythoncraft.com (Aahz) Date: 31 Oct 2002 16:08:33 -0500 Subject: Classes question References: <20021031205456.GA8006@ens-lyon.fr> Message-ID: In article <20021031205456.GA8006 at ens-lyon.fr>, Emmanuel Jeandel wrote: > >I have the following code : > >class A: > def __init__(self): > pass > > def f(self): > self.x = B() > >class B(A): > def __init__(self): > A.__init__(self) > > >I would like to have the class A and the class B in two differents files. >Is it possible ? >I think that it is not directly possible, but if there is a mean with a >small change in the code... Assuming you put the code for A in classA.py, you can make class B work by adding the line from classA import A before the "class B" statement. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From mfranklin1 at gatwick.westerngeco.slb.com Mon Oct 7 14:41:10 2002 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Mon, 07 Oct 2002 18:41:10 +0000 Subject: How to get the mouse cursor position in TK? In-Reply-To: References: Message-ID: <200210071841.10386.mfranklin1@gatwick.westerngeco.slb.com> On Monday 07 Oct 2002 5:19 pm, Heiner Litz wrote: > hi Thank u! > > event.x_root works but I have another Problem: I want to pop-up an whole > new WINDOW, but the Tk() Objects dont know the gm place. So how can I place > tk Objects, and NOT widgets inside a parent? Not sure i'm following here but perhaps all you need is a Toplevel widget? > > 2. question: > I have got the mentioned listbox and select one entry. Now If there is a > right-mouse-button event I want to know what line was selected. Howtodo? > the listbox.curselection() method returns a tuple of indexes of the selected items (just one if single selection) the listbox.get(first=XXX) method will return the XXX't item in the list box so:- index = int(listbox.curselection()[0]) item = listbox.get(first=index) and from the command line:- Python 2.2.1 (#3, May 29 2002, 20:32:44) [GCC 2.96 20000731 (Red Hat Linux 7.1 2.96-98)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import Tkinter >>> lb=Tkinter.Listbox() >>> lb.insert("end", "one") >>> lb.insert("end", "two") >>> lb.insert("end", "three") >>> lb.pack() >>> lb.curselection() ('1',) >>> lb.get(first=int(lb.curselection()[0])) 'two' >>> should do the trick I guess you need to get hold of some Tkinter documentation....:- http://www.python.org/topics/tkinter/ > thx again > > > Assuming you pass the event to the popup function > > event.x_root and event.y_root should be what you want: -- ### Python Powered Signature I started writting this email on Mon Oct 7 18:34:41 2002 From cnetzer at mail.arc.nasa.gov Wed Oct 2 15:24:26 2002 From: cnetzer at mail.arc.nasa.gov (Chad Netzer) Date: Wed, 2 Oct 2002 12:24:26 -0700 Subject: Tkinter Listbox.curselection() error? In-Reply-To: <8efc7149.0210012308.6a1ada17@posting.google.com> References: <8efc7149.0210012308.6a1ada17@posting.google.com> Message-ID: <200210021924.MAA09489@mail.arc.nasa.gov> On Wednesday 02 October 2002 00:08, Bob wrote: > Hello, > I'm trying to write a fairly simple font selection dialog for a > bigger application I'm working on. Every time I try to use the > curselection() method on a listbox I created I get a weird tcl error. > Can anyone tell me what I'm doing wrong? Any help would be much > appreciated. > > [snipped long class definition] > > if( __name__ == "__main__" ): > root = Tk(); > fb = ERGFontChooser( root ); > > f = fb.getFont(); > > print( `f` ); > print( f.actual() ); You initialize Tk, and create ERGFontChooser, but you never enter into the TK mainloop(). So, first, put root.mainloop() at the end of the program. Then delete the use of fb.getFont() outside of the mainloop, since it won't work like you want it to. (see below) When I run what you have, I get the error only when I hit "OK" or "Cancel", causing self.top.destroy() to be run. But since the mainloop() was never entered, the Tk state is not fully defined, and so this isn't unexpected. You can't use getFont() outside of the mainloop (at least, not effectively) without expecting these kinds of trouble. Outside of the mainloop() Tk isn't really processing events; you could call an after_idle(), before entering mainloop, to start some prcoessing that isn't event based (such as forcing the window to raise, etc.), but I won't guarantee the results. Also, using wait_window() in getFont, doesn't seem right. After all, getFont() MUST stall until the Toplevel window is destroyed (which will destroy all the widgets in it.) At which point, getFont() tries to continue operating on Tkinter widgets that are now destroyed. If I put the getFont() call in the ok() method (changing it to self.getFont()), and get rid of the wait_window() call in getFont(), then it does what I think you want: It returns the font info when you press 'Ok', and destroys the window. Here is the end of the program as I wrote it: def getFont( self ): # we have returned items = self.familyBox.curselection(); fam = self.familyBox.get( items[0] ); if( self.boldVar.get() == 0 ): weight = NORMAL; else: weight = BOLD; font = Font( self.root, family = fam ); font.config( size = self.sizeVar.get(), weight = weight ); return font; def ok( self, event=None ): f = self.getFont(); print( `f` ); print( f.actual() ); print "OK"; self.top.destroy(); if( __name__ == "__main__" ): root = Tk(); fb = ERGFontChooser( root ); root.mainloop() Oh, and lay off the coke, Bob. :) -- Chad Netzer cnetzer at mail.arc.nasa.gov From mr.random at gmx.net Mon Oct 21 16:06:03 2002 From: mr.random at gmx.net (Dave Richards) Date: Mon, 21 Oct 2002 22:06:03 +0200 Subject: Changing completion key Message-ID: <3db45e23_1@news.arcor-ip.de> I recently discovered that idle and the python shell support name completion with the combination Alt+/. As I use a German keyboard, that means I have to press Alt+Shift+7 (/ is Shift+7), which is a little unwieldy for my tastes. Is it possible to change this combo? I had a look at the keydefs file in idle, but it's not in their. As far as I can see, it's in readline.so. Is there any way to rebind this combination to something more convenient for my keyboard - I kind of need the German keyboard, otherwise I have to type Alt+252 or some other 3-digit number every second word to get ??? and ?. Dave From fperez528 at yahoo.com Fri Oct 18 13:11:33 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Fri, 18 Oct 2002 11:11:33 -0600 Subject: Books on scientific/numeric programming in Python? References: <3DB005F8.CD96D868@bio.gla.ac.uk> Message-ID: Francis Burton wrote: > Hi, > > I wondered if any books have been published which focus on using > Python for scientific data processing, numerical methods, mathematics > and/or statistics? There are a few relevant nuggets in the excellent > "Python Cookbook", but it would be nice to have a book dedicated to > the subject. If not, there's a gaping niche in the market waiting to > be filled. > > Francis Look at http://pathfinder.scar.utoronto.ca/~csca57/ They have 'An Elementary Introduction to Scientific Computing', the text is incomplete. I wasn't terribly impressed by it, but it does have a pyhton focus. cheers, f. From chris.gonnerman at newcenturycomputers.net Wed Oct 2 23:16:01 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Wed, 2 Oct 2002 22:16:01 -0500 Subject: Decimal arithmetic, was Re: Python GUI app to impress the boss? References: <7xd6qwqtgz.fsf@ruckus.brouhaha.com> <7xelbcgo56.fsf@ruckus.brouhaha.com> <3D9A5DC4.9030704@tismer.com> <00c601c269c1$7afe83a0$ba01010a@local> <3D9B5B97.4020106@tismer.com> Message-ID: <003301c26a8b$39388900$ba01010a@local> ----- Original Message ----- From: "Christian Tismer" > (On bases: Actually, the primes (2, 3, 5) would give a quite > nice numeric base. They have lots of nice properties > concerning harmony, and the multiples of the prime factors > produce numbers people consider as "nice", most of the time. > So my number base would be at least 30 :-) ) Didn't the ancient Babylonians use 60? I've read we have them to blame for 360 degrees in a circle. Just has another factor of 2... they must have been pretty sharp mathematicians. Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From ykingma at accessforall.nl Sat Oct 5 09:20:17 2002 From: ykingma at accessforall.nl (Ype Kingma) Date: Sat, 05 Oct 2002 15:20:17 +0200 Subject: Simple lru cache? References: Message-ID: <3d9ee62b$0$126$e4fe514c@dreader6.news.xs4all.nl> Bjorn Pettersen schreef: >> From: Ype Kingma [mailto:ykingma at accessforall.nl] >> >> Does anyone know of a good lru cache implementation in >> python? > > Perhaps http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/117228 > will give you some ideas? This is a priorityDictionary. Quoting from the page: Description: This data structure acts almost like a dictionary, with two modifications: First, D.smallest() returns the value x minimizing D[x]. For this to work correctly, all values D[x] stored in the dictionary must be comparable. Second, iterating "for x in D" finds and removes the items from D in sorted order. Each item is not removed until the next item is requested, so D[x] will still return a useful value until the next iteration of the for-loop. End of quote. I don't see immediately how the aging needed for least recently used could be implemented using a priorityDictionary. It's use of binary heaps might help to overcome the problem with of age gaps in the suggestion Alex Martelli made. > And also perhaps: > http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/python/dist/src/Li > b/heapq.py?rev=HEAD&content-type=text/vnd.viewcvs-markup A heapq library. From the url it looks like this is meant to be included in the next python distribution. More batteries, good news. Thanks, Ype From brian at sweetapp.com Sun Oct 13 17:13:38 2002 From: brian at sweetapp.com (Brian Quinlan) Date: Sun, 13 Oct 2002 14:13:38 -0700 Subject: Swedish characters in Python strings In-Reply-To: <7d546104.0210131130.15f91da5@posting.google.com> Message-ID: <005b01c272fd$668cefc0$df7e4e18@dell1700> Urban wrote: > I think Python should take care of that kind of conversions > behind the scene... How would Python do this? > By the way, is there a method to test strings for how they are > coded before messing with them in a program. No. Given a sequence of bytes, it is pretty tough to accurately determine the encoding. There are libraries that try, but they don't always succeed. Cheers, Brian From orlov at diasoft.ru Tue Oct 22 08:49:55 2002 From: orlov at diasoft.ru (Oleg Orlov11980884) Date: Tue, 22 Oct 2002 16:49:55 +0400 Subject: Yet another Python .bat wrapper References: Message-ID: "Oren Tirosh" wrote in message news:mailman.1035286349.21970.python-list at python.org... > It has a header of just one line. All the ugly stuff is at the end. > > ------------------------------------------------------------------- > goto ="python" > > # Python code goes here > > ''' hybrid python/batch footer: > @:="python" > @python.exe %0 %1 %2 %3 %4 %5 %6 %7 %8 %9 > @if errorlevel 9009 echo Python may be downloaded from www.python.org/download > @rem ''' > ------------------------------------------------------------------- > > Oren > WindowsXP: ------------------------------------------------------------------- @D:\Python22\python.exe -x %0 %* && exit # Python code goes here import sys print " ".join(sys.argv) ------------------------------------------------------------------- Oleg From sismex01 at hebmex.com Thu Oct 10 11:25:51 2002 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Thu, 10 Oct 2002 10:25:51 -0500 Subject: time and thread modules. Message-ID: Well, not actually but related. Does invoking time.sleep() automagically allow a thread switch in Python? -gustavo From martin at v.loewis.de Wed Oct 16 15:59:51 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 16 Oct 2002 21:59:51 +0200 Subject: string to float problem References: Message-ID: jubafre at brturbo.com writes: > and in my aplicattion make diference i, how can i transform this > string in a float number, i want 10.60 in float? That is not possible. Your computer cannot represent 10.60 in binary float, see http://www.python.org/cgi-bin/faqw.py?req=all#4.98 Regards, Martin From a.klostermann at kliniken-ruhrhalbinsel.de Thu Oct 10 05:15:31 2002 From: a.klostermann at kliniken-ruhrhalbinsel.de (a.klostermann) Date: 10 Oct 2002 02:15:31 -0700 Subject: How can I use the function "function" in the "new" module to create a function with arguments? Message-ID: <1143bd35.0210100115.7580e1e6@posting.google.com> I want to implement something like the Remote Method Interface, and so I need to append a new, dynamically generated, method to the Interface Object on the client side. at the moment I only know how to generate python code in the form c = compile ("print 'hello'", "","exec") now I create a function object, binding it to a class instance as new Method "hello" a.hello = (c, {}) the "{}" satisfies the globals argument with an empty dictionary, eg. no globals. But I want to provide arguments to the dynamically created function... how can I do that? Thanks in Advance, Andreas Klostermann From loewis at informatik.hu-berlin.de Thu Oct 17 04:43:35 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 17 Oct 2002 10:43:35 +0200 Subject: Pythin-2.2.1 install on Solaris question. References: Message-ID: Hennie Rautenbach writes: > I am having difficulty installing Python-2.2.1 on a Solaris 8 system > uisng the Gnu-C compiler. Which version of the C compiler? If gcc 3, do you have libgcc_s.so.1 in your LD_LIBRARY_PATH? > /usr/local/bin/gcc -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -fPIC > -I. -I/usr/local/src/Python-2.2.1/./Include -I/usr/local/include > -IInclude/ -c /usr/local/src > /Python-2.2.1/Modules/pwdmodule.c -o > build/temp.solaris-2.8-sun4u-2.2/pwdmodule.o > /usr/local/bin/gcc -shared > build/temp.solaris-2.8-sun4u-2.2/pwdmodule.o -L/usr/local/lib -o > build/lib.solaris-2.8-sun4u-2.2/pwd.so > WARNING: removing "pwd" since importing it failed > > Why is this happening ? What am I doing wrong ? Unfortunately, this is unclear. Please invoke the compilation commands manually, ie. /usr/local/bin/gcc -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -fPIC \ -I. -I/usr/local/src/Python-2.2.1/./Include -I/usr/local/include \ -IInclude/ -c /usr/local/src \ /Python-2.2.1/Modules/pwdmodule.c -o \ build/temp.solaris-2.8-sun4u-2.2/pwdmodule.o /usr/local/bin/gcc -shared \ build/temp.solaris-2.8-sun4u-2.2/pwdmodule.o -L/usr/local/lib -o\ build/lib.solaris-2.8-sun4u-2.2/pwd.so Then invoke ./python, and "import pwd". That should give a more detailed error message. If you cannot interpret this error message, please post it here. Regards, Martin From bokr at oz.net Fri Oct 18 15:03:28 2002 From: bokr at oz.net (Bengt Richter) Date: 18 Oct 2002 19:03:28 GMT Subject: Python code examples that _generate_ HTML/XML? References: Message-ID: On Thu, 17 Oct 2002 20:29:20 GMT, "Robert Oschler" wrote: >I'm creating an app for use in-house, that will assist a user (complete >novice) in creating web pages. So after they complete a session I will need >to take their "instructions" and generate the items necessary to display the >desired pages in a browser. Therefore I'll be creating the HTML/XML tags >and code dynamically for things like list boxes, buttons, hrefs, graphics, >etc. Has anybody seen any code samples or URL's for such that show how to >do this in Python? Are there parts of the Zope source code that might be >helpful to look at, if so what 'py' files? > Have you looked at http://www.python.org/doc/current/lib/module-xml.dom.html ? Regards, Bengt Richter From martin at v.loewis.de Tue Oct 15 17:05:20 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 15 Oct 2002 23:05:20 +0200 Subject: International APPs / pygettext References: <3DAC5E22.1060102@web.de> <3DAC7CA5.1080208@web.de> Message-ID: Ingo Linkweiler writes: > do you know other utilities for extracting the strings from my source? I recommend pygettext.py, or GNU xgettext. > Where can I get xpot, or any similar software? > > I have never used the gettext-utilitues before. Is this the correct way? > > Source -> Utility1 -> .po-file -> Editor1 + msgfmt -> .mo-file > > Utility1 = xpot or ??? xgettext. > Editor1 = vi or any text-editor > msgfmt = included in gettext-distribution... But: > > Where can I get a (compiled) windows version of msgfmt? I can not find > it at gnu.org and not in the cygwin utilities. You can use msgfmt.py, included in the Python sources. Regards, Martin From cbbrowne at acm.org Fri Oct 18 09:53:27 2002 From: cbbrowne at acm.org (Christopher Browne) Date: 18 Oct 2002 13:53:27 GMT Subject: Python daemon References: <20021017230255.GA15144@sentinelchicken.net> Message-ID: Quoth pinard at iro.umontreal.ca (Fran?ois Pinard): > [Jason Morgan] > >> You may want to take a look at daemontools by Ban Burnstein. [...] > > You meant Daniel Burnstein? I'd rather not. You may choose the crowd you > want to be with, and decide to stay away from others. It's your life! :-) No, I think that's Ban Q. Burnstein, where the middle name is in fact three silent "q's." Entirely separate from the controversial Dan J. Bernstein. -- (concatenate 'string "aa454" "@freenet.carleton.ca") http://cbbrowne.com/info/rdbms.html Rules of the Evil Overlord #1. "My Legions of Terror will have helmets with clear plexiglass visors, not face-concealing ones." From gabor at realtime.sk Wed Oct 9 19:58:44 2002 From: gabor at realtime.sk (gabor) Date: 10 Oct 2002 01:58:44 +0200 Subject: lists....order... Message-ID: <1034207924.4247.75.camel@wintermute.atriaky.sk> hi, 1. a = [1,2,3,4,5,6] for item in a: print a will print 1 2 3 4 5 6? in other words, is it guarantied that for a list the elements will be enumerated in their order? 2. many times i use this construct: a = ["a","b","c","d"] for letter in a: dosomething.. but now i really need the position of the letter in that list so i need an x, for which a[x] = letter... the only solution i could find: for index in range(len(a)): letter = a[index] is there a way to do that with the normal 'for letter in a' approach? thanks, gabor -- listening to Yuki Kajiura - The World From ken at hotmail.com Sat Oct 5 23:11:33 2002 From: ken at hotmail.com (Ken) Date: Sun, 6 Oct 2002 13:11:33 +1000 Subject: are these operations on list valid? References: Message-ID: By the way....same type of question for dictionary..... Thanks "Ken" wrote in message news:ano9fi$fo0ko$1 at ID-49758.news.dfncis.de... > Hi, just like to know if these are valid: > > 1: > Use: > var1 = "hello" > var2 = "world" > list = [var1, var2] > > Instead of: > list = [] > list.append(var1) > list.append(var2) > -------------------- > 2. > Use: > list=["hello", "world"] > if list==["hello", "world]: #comparing list with list without examining > through every element inside > do something..... > > Instead of: > list1=["hello", "world"] > if list[0]==list1[0] and list[1]==list1[1]: > do something.... > --------------------- > Thanks > > > > From cnetzer at mail.arc.nasa.gov Wed Oct 2 18:49:32 2002 From: cnetzer at mail.arc.nasa.gov (Chad Netzer) Date: Wed, 2 Oct 2002 15:49:32 -0700 Subject: Deleting the first element of a list In-Reply-To: <3d9b72c0_5@news.newsgroups.com> References: <3d9b72c0_5@news.newsgroups.com> Message-ID: <200210022249.PAA00306@mail.arc.nasa.gov> On Wednesday 02 October 2002 15:36, JB wrote: > Is using del to delete the first element (that is, the 0th > element) of a list faster than x = x[1:]? Looks like it (timed both short and long lists. w/ loops unrolled): ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ import time short_list = [0,1,2,3,4,5] * 2 long_list = short_list * 10000 n = 10 avg = 0 lists = [ short_list, long_list ] for l in lists: for i in xrange(n): tmp_list = l[:] start = time.time() del tmp_list[ 0 ] del tmp_list[ 0 ] del tmp_list[ 0 ] del tmp_list[ 0 ] del tmp_list[ 0 ] del tmp_list[ 0 ] del tmp_list[ 0 ] del tmp_list[ 0 ] del tmp_list[ 0 ] del tmp_list[ 0 ] end = time.time() avg = avg + (end - start) avg = avg / 10 / n print "avg (del):\t %.13f secs" % (avg,) for i in xrange(n): tmp_list = l[:] start = time.time() tmp_list = tmp_list[ 1: ] tmp_list = tmp_list[ 1: ] tmp_list = tmp_list[ 1: ] tmp_list = tmp_list[ 1: ] tmp_list = tmp_list[ 1: ] tmp_list = tmp_list[ 1: ] tmp_list = tmp_list[ 1: ] tmp_list = tmp_list[ 1: ] tmp_list = tmp_list[ 1: ] tmp_list = tmp_list[ 1: ] end = time.time() avg = avg + (end - start) avg = avg / 10 / n print "avg (slicing):\t %.13f secs" % (avg,) print ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ avg (del): 0.0000028991699 secs avg (slicing): 0.0000033883095 secs avg (del): 0.0032141237535 secs avg (slicing): 0.0115537309935 secs -- Chad Netzer cnetzer at mail.arc.nasa.gov From mhammond at skippinet.com.au Tue Oct 8 19:04:21 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Tue, 08 Oct 2002 23:04:21 GMT Subject: unable to import win32api into an embedded python interpreter. References: Message-ID: pjd wrote: > Hi > > Here is my problem. > > I have embedded python 22 in a c++ program. Everything works as expected, I > am able to execute external scripts. > But when I do an 'import win32api' in the script I am trying to execute, it > barfs. > The same script works fine when executed from prompt as 'python > myscript.exe'. > > I am able to import other modules in my embedded interpreter. e.g. 'from > xml.dom import minidom' > > > I suspect the following reasons > > 1 ) path of the executable is different from that of Python executable. > Ofcourse my executable with embedded python interpreter lives in another > directory, under a different name. > 2) Modules in C:\Python22\Lib import well. But may be from site-packages > dont work well ? I am not sure about this. > What exception do you get? win32apimodule.pyd depends on pywintypes22.dll - is that on your PATH? (Not PYTHONPATH but, system PATH) Mark. From tjreedy at udel.edu Thu Oct 31 20:02:51 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 31 Oct 2002 20:02:51 -0500 Subject: Global variable visibility References: Message-ID: <9jadnSkHAZ8_TFygXTWcqw@comcast.com> "David LeBlanc" wrote in message news:mailman.1036107510.2298.python-list at python.org... > If I create Db in database.py, I can refer to it as database.Db in main correct > can I do the same thing in commands.py - refer to it as database.db, No, unless you... > or would I have to import database.py into commands.py too? yes TJR From martin at v.loewis.de Mon Oct 21 13:31:21 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 21 Oct 2002 19:31:21 +0200 Subject: Unicode strings -> xml.dom.minidom Text elements? References: Message-ID: Patrick Surry writes: > and am stuffing it into an xml.dom.minidom Text() element. But when I > serialize the document with doc.writexml(), it turns into: > > ABC?DEF I find that hard to believe. Are you sure it really puts a question mark in there? Or is it just that your email program is not capable of sending GREEK CAPITAL LETTER SIGMA? Have you, by any chance, modified sys.setdefaultencoding? > This seems to be because writexml() effectively does > > writer.write('%s' % a) > > making the unicode character turn into a '?' Extremely unlikely. Can you show a complete program that demonstrates this problem? > Am I doing something dumb and/or is there a workaround I could use > other than writing my own XML unicode character escaper... As a starting point, I recommend that you refrain from setting the default encoding to "mbcs". As the next step, I recommend that you try to save the XML document in UTF-8. As it is, writexml is not capable of escaping characters itself. So you will find that writexml gives you a Unicode string, which you need to encode as UTF-8 yourself. Depending on where exactly you got writexml from, you may find that it has an encoding= parameter. It still won't produce character references, though. Regards, Martin From mcfletch at rogers.com Mon Oct 21 03:14:58 2002 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Mon, 21 Oct 2002 03:14:58 -0400 Subject: Spell-check engine? References: <20021018200007.12387.54659.Mailman@mail.python.org> <3DB33B40.5080003@rogers.com> Message-ID: <3DB3A972.4090404@rogers.com> Okay, I think I'm done playing for today, so here's how it stands: The (python) phonetic compression algo appears to work approximately correctly with the aspell phonet.dat files. There is still no rule-priority, "follow-on rule", or accent-stripping support. It does, however, seem to produce at least vaguely intelligible results. I've got word-set classes which store individual word-sets using simple bsddb btree tables. The wordsets provide for exact, exact-soundslike and similar-soundslike searches (as understood by aspell). The edit-distance code works as expected. It still doesn't have typo-pair support. There is an object (SpellDict) which provides a simple API for a collection of some number of word-sets. Still no support for reading in the compiled aspell files (and quite frankly, I don't see a nice way to do it). The SpellDict provides this API: class SpellDict( object ): """Binds together a set of wordsets """ def __init__( self, sets = (), name = "", ): """Create a new SpellDict with the given sets and a user-friendly name sets is a sequence object (iterable) of instantiated WordSet objects name is a user-friendly name for this collection of word sets (dictionary) """ def check( self, word): """Check whether a word is in dictionary If the word is in the dictionary, returns the first set in which the word appears. """ def suggest( self, word, distance=1 ): """Suggest words to replace word distance is a metric determining how far the soundslike value can diverge to still allow for a "similar" ranking. Higher values will dramatically increase the running time and catch far more possible matches. """ with everything basically working as advertised (AFAICT). If there's any interest, I'll setup a SourceForge project tomorrow, post all the code, and move updates off the Python list :) . Enjoy all, Mike Mike C. Fletcher wrote: > Well, I've been playing with this a little more. It seems to me that > about 70% of the complexity of the aspell code is just getting around > the limitations of C++. The engine itself seems to be composed of a > few fairly minimal parts: [previous status deleted] ... From mwh at python.net Mon Oct 14 07:38:03 2002 From: mwh at python.net (Michael Hudson) Date: Mon, 14 Oct 2002 11:38:03 GMT Subject: Is there a "reset" in Idle? References: <0rc7qu4l03ga7cdpifce8je632mlcju1fi@4ax.com> Message-ID: Dale Strickland-Clark writes: > Michael Hudson wrote: > > >A couple of points: > > > > 1) what shortcomings are these? > > Only a few but critical to the re-usability of the debugging > environment. I don't remember the technical details but I'm sure > Google will find the issues if you're really interested. This is a bit vague for formulating a google query. > >The only people paid to work on Python are at PythonLabs, who are paid > >by ZC, who in turn probably don't have an overriding interest in > >interactive debugging. Everyone else works on Python because it's fun > >and to scratch an itch, basically. If you try to make us do what you > >want rather than what we want, we stop. > > I'm aware of this. However, surely some of the enjoyment comes from > knowing others are using your efforts? Yes. > Can you imagine the boost Python would get in the programming > comminity if a killer IDE appeared on the scene? Not really; I like emacs :) > >OTOH, if you can come up with concrete suggestions, I'm all ears. > > Suggestion: Address the problem in Python that prevents IDEs from > reloading modules and re-using a debuggin environment. Um, this isn't what I meant by "conrete" :) Pretend you're explaining things to an idiot, please! Cheers, M. -- Q: Isn't it okay to just read Slashdot for the links? A: No. Reading Slashdot for the links is like having "just one hit" off the crack pipe. -- http://www.cs.washington.edu/homes/klee/misc/slashdot.html#faq From bobx at linuxmail.org Tue Oct 8 08:22:23 2002 From: bobx at linuxmail.org (Bob) Date: 8 Oct 2002 05:22:23 -0700 Subject: appending to beginning of line Message-ID: <1001ff04.0210080422.1e373e13@posting.google.com> I have this script: # loop through the list and print the lines to a file for line in inFile.xreadlines(): for badword in kw: if line.find(badword) > -1: found = '%s %s' % (badword, line) print found # Print the result outFile.write(found) # Write the result This will print the badword and then the line it is on. For those lines that do not contain a badword I want to place a hyphen "-". Bob From mary-python at puzzling.org Wed Oct 9 20:24:27 2002 From: mary-python at puzzling.org (Mary) Date: Thu, 10 Oct 2002 10:24:27 +1000 Subject: ANN: Sydney Australia Python Interest Group: Monday 21st October 2002 Message-ID: <20021010002427.GI744@titus.spanky> The Sydney Australia Python Interest Group meeting: Monday the 21st October, 7pm - 9pm University of Technology Sydney, Australia, Broadway campus. This month's meeting is being held in the Fairfax Building of UTS Broadway, room 2.440 (level 2, solaris lab 10). This month, Pete Hardy is talking about his Python curses interface to the Julie Jukebox[0]. The Sydney PIG's webpage can be found at http://pig.slug.org.au/ [0] http://www.cse.unsw.edu.au/~cgray/julie/ ---- Sydney Python Interest Group meetings are announced on: * comp.lang.python.announce and python-announce-list at python.org[0] * the Australian Python users list[1] * The Sydney Linux User's Group announce list[2] [0] http://mail.python.org/mailman/listinfo/python-announce-list [1] http://starship.python.net/mailman/listinfo/python-au [2] http://lists.slug.org.au/listinfo/announce/ ---- The Sydney Python Interest Group is, while not restricted to Python on Linux, a Special Interest Group of the Sydney Linux Users Group (SLUG), and would like to thank SLUG for its support. From tjabo.kloppenburg at unix-ag.org Sat Oct 26 04:51:48 2002 From: tjabo.kloppenburg at unix-ag.org (Tjabo Kloppenburg) Date: Sat, 26 Oct 2002 10:51:48 +0200 Subject: How to Sort this array In-Reply-To: References: Message-ID: <20021026105148.6d12ee70.tjabo.kloppenburg@unix-ag.org> > How to sort an array with numbers like 021025_11441 in it? It needs to be > sorted first by the number before '_', then sorted by the number after '_'? > How to do it using a customized sort function? start you interpreter. next type: >>> print [].sort.__doc__ L.sort([cmpfunc]) -- sort *IN PLACE*; if given, cmpfunc(x, y) -> -1, 0, 1 so you need a function returning -1, 0 or 1.. def myCmp( x, y ): x_s = map( int, x.split("_") ) y_s = map( int, y.split("_") ) # now we have to lists with two integers in each list. # now just compare the ints an return -1, 0, or 1... ... have fun... :-) tk. -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From kokohh at hotmail.com Wed Oct 2 21:04:32 2002 From: kokohh at hotmail.com (koko) Date: Thu, 03 Oct 2002 01:04:32 GMT Subject: how to get rid of html tags Message-ID: I am trying to retrieve a web page. But I only want to keep the content of the webpage without the html tags. How can I parse the webpage to get rid of the tags? From marklists at mceahern.com Mon Oct 14 17:12:04 2002 From: marklists at mceahern.com (Mark McEahern) Date: Mon, 14 Oct 2002 16:12:04 -0500 Subject: tricky sorting In-Reply-To: <653cf871.0210141246.607fcef9@posting.google.com> Message-ID: [les] > I would like to sort by two fields: first sort by the second > column (which is in > roman numerals) and then I would like to sort by the last column > (only the "from" > part only) > so the above result would be > abdng I 10-11 > rshts I 1201-1210 > abdns IV 43-45 > qurst XIII 87-98 > andng IX 18293-19283 Um, but doesn't XIII come before IX? Mark Pilgrim implemented a nice roman numeral library in his book Dive Into Python (http://www.diveintopython.org/). Look at the chapter on unit testing. The code is available there. Jeff Epler's reply has all the rest of the suggestions I would have made--but his post is more explicit than mine would have been. Cheers, // mark - From bokr at oz.net Mon Oct 7 04:05:51 2002 From: bokr at oz.net (Bengt Richter) Date: 7 Oct 2002 08:05:51 GMT Subject: Parsing variables out of python lines References: Message-ID: On Mon, 07 Oct 2002 05:43:54 GMT, Mark wrote: >I hate finding answer quickly after posting. Anyway, here is code that will >solve my problem: > > >import tokenize >import StringIO > >foo = [1,2,3] >x = "for i in foo:" > ># >#The StringIO trick turns a string into a read'able object (or so it seems) ># >t = tokenize.generate_tokens(StringIO.StringIO(x).readline) > >for junk, item, rest1, rest2, rest3 in t: > if item in vars(): > print eval(item), > else: > print item, >print > >With output: >==> for i in [1, 2, 3] : > >Anyone know how to clean up the tuple assignment (I only want item, the rest >could go to /dev/null if they want). > Not sure what you're doing in your larger context, but extracting the second item from each tuple is easy with a list comprehension (see below). If the sequence is really huge, you could wrap tokenize in a generator to return the selected tuple element. (See further below). (BTW, if you know that item in vars() is true, why not just look it up with vars()[item]?) >>> import tokenize >>> import StringIO >>> foo = [1,2,3] >>> x = "for i in foo:" >>> items = [tup[1] for tup in tokenize.generate_tokens(StringIO.StringIO(x).readline)] >>> print ' '.join([(z in vars() and [`vars()[z]`] or [z])[0] for z in items]) for i in [1, 2, 3] : Though you might want to do `` to all the output so you can distinguish better (and see the ''): >>> print ' '.join([`(z in vars() and [vars()[z]] or [z])[0]` for z in items]) 'for' 'i' 'in' [1, 2, 3] ':' '' or if you don't mind the brackets and commas, just let the list be repr'd >>> print [(z in vars() and [vars()[z]] or [z])[0] for z in items] ['for', 'i', 'in', [1, 2, 3], ':', ''] The generator lets you put "in tokitems(x,1)" in place of "in items" above: >>> from __future__ import generators >>> def tokitems(s, i): ... for tup in tokenize.generate_tokens(StringIO.StringIO(s).readline): ... yield tup[i] ... >>> print ' '.join([`(z in vars() and [vars()[z]] or [z])[0]` for z in tokitems(x,1)]) 'for' 'i' 'in' [1, 2, 3] ':' '' Or, less obscure and avoiding the ugly substitute for (x?y:z), >>> for item in tokitems(x,1): ... try: ... print `vars()[item]`, ... except KeyError: ... print `item`, ... 'for' 'i' 'in' [1, 2, 3] ':' '' (I can't add the final dedented bare "print" interactively on the next line for some reason. If it's waiting for a blank line, why can't it wait for that blank line and decide *then* whether I've done badly with the dedent? It would make for cleaner example-typing. I can get around it by putting everything indented under an "if 1:" but IMO that's a warty restriction.) Regards, Bengt Richter From coo_t2 at yahoo.com Mon Oct 21 23:20:20 2002 From: coo_t2 at yahoo.com (ed) Date: Mon, 21 Oct 2002 20:20:20 -0700 (PDT) Subject: best way to learn Message-ID: <20021022032020.55936.qmail@web14406.mail.yahoo.com> Hey all. I'm a python newbie, but I have experience in other very high level languages, mainly php. I was wondering what is the best way to become proficient in python quickly? I'm actually a pretty decent php programmer, so I don't think I need something that spends too much time on the basics(ie loops and if statements). I just need to know how things work in python. I did do the tutorial that comes with the distro, but I need more than that. Should I get a book, if so which one? "Learning python", "programming python", "python cookbook"? Or can I get pretty much everything I need on the web, like a lot of good tutorials and some good language references? If I get a book I'd like to get one that works as a newbie tutorial but by the end of the book deals with some advanced topics and will also work somewhat well as a reference. Is that asking too much? Should I trust the reviews at amazon.com? :) Any guidance appreciated. tia, --ed __________________________________________________ Do you Yahoo!? Y! Web Hosting - Let the expert host your web site http://webhosting.yahoo.com/ From marklists at mceahern.com Wed Oct 2 16:57:32 2002 From: marklists at mceahern.com (Mark McEahern) Date: Wed, 2 Oct 2002 15:57:32 -0500 Subject: Install rpm : irpm In-Reply-To: Message-ID: [Fernando Perez] > Well, Mandrake has urpmi which is GPLd, so I assume you are doing > this for your own education. In that case, I'd look at the urpmi code > to learn how they addressed various issues. This can be a bit of a > messy problem, so looking at their code might help; it's pretty robust > in general. You may also want to look at gentoo's Portage: http://www.gentoo.org/doc/portage-manual.html which is written in (or at least uses) Python. Cheers, // mark From loewis at informatik.hu-berlin.de Thu Oct 17 07:50:36 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 17 Oct 2002 13:50:36 +0200 Subject: SOAP frustrations References: <3DAC6F04.2030704@mindspring.com> <3DAE9265.6020800@mindspring.com> Message-ID: Andrew Dalke writes: > Me: > >What I don't get is, I figure there's enough people doing web services/ > >SOAP with Python that there shouldn't be these problems. > > Martin v. Loewis wrote: > > Why do you think this is the case? > > Because I did a project with SOAP and Python over 2 years ago, > using /F's soaplib. (Python to Python SOAP.) Looking at your complaints, this is no reason to expect what you expected: - ZSI does not work: Why would the state of soaplib have any effect on the state of ZSI? - SOAP.py is written in unreadable code: Same question. > Because there are at least 4 different SOAP projects, meaning > there's enough interest for several different groups to not > only develop a SOAP library but to make it public. Maybe the reason for those people to develop a new library is that they could not understand the old ones? Maybe the reason to publish them was in the hope that users would contribute corrections and improvements? Maybe neither corrections nor improvements materialized, because nobody uses SOAP? > Because 1) SOAP has been a buzzword for years, 2) Python projects > are easy to develop, and 3) more obscure projects get developed > with Python, so I figured the likelihood was high. 1) Being a buzzword means that many people experiment with it. If it is just a buzzword (instead of being truly useful), they leave off at the point where they realize that it does not do any good. In turn, the code base they leave behing will be hardly working and completely unmaintained. So something being a buzzword sounds like a guarantee to observe what you have observed. 2) So it is easier to start your own project than to use somebody else's code base. People get tricked into believing that things lose their inherent complexity by using Python. For something as complex as the Simple Object Access Protocol, Python can only help to manage the inherent complexity, not to avoid it. Or, if you avoid the inherent complexity, your code will be suitable just for your specific application. You seem to have observed that as well. 3) People working on more obscure stuff often do so because of a real need, instead just because of buzzword compliance. Their libraries are then often more reliable, since they have been used in real applications. Regards, Martin From SBrunning at trisystems.co.uk Mon Oct 7 06:04:11 2002 From: SBrunning at trisystems.co.uk (Simon Brunning) Date: Mon, 7 Oct 2002 11:04:11 +0100 Subject: Boa Constructor and CVS question Message-ID: <31575A892FF6D1118F5800600846864DCBD908@intrepid> > From: Conrad Schneiker [SMTP:schneiker at athenalab.com] > > I've done some groups.google searching around and have seen > recommendations > that the CVS version of Boa Constructor be used (since the .zip and > win32.exe downloads are way out of date). After some further searching, I > haven't found any concise documentation about how to go about doing this, > although there is a considerable abundance of marginally related > information > to sift through. Have a look at . Cheers, Simon Brunning TriSystems Ltd. sbrunning at trisystems.co.uk ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From mike at bindkey.com Tue Oct 29 19:17:58 2002 From: mike at bindkey.com (Mike Rovner) Date: Tue, 29 Oct 2002 16:17:58 -0800 Subject: difficult regular expression References: <1035931448.28476.30.camel@tutelage> Message-ID: > I need to create a regular expression that will grab "the things that > Cats eat". import re pattern = re.compile( r'(\w+) eat (.*), and other foods\.' ) source = " ".join(( 'Here is a list of foods and consumers: Dogs eat , ,', ', and other foods. Cats eat , , , ,', 'and other foods. Chickens eat , , , and other', 'foods. Wow, that's a lot of eating!')) found = pattern.findall( source ) food={} for consumer, foodlist in found: food[consumer]=[s[2:-1] for s in foodlist.split(',')] print food >>> {'Cats': ['ice', 'rats', 'rabbits', 'marmots'], 'Chickens': ['rain', 'corn', 'wheat'], 'Dogs': ['hicken', 'rice', 'steak']} Mike From martin at v.loewis.de Fri Oct 18 04:30:54 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 18 Oct 2002 10:30:54 +0200 Subject: no struct.pack for unicode strings? References: Message-ID: Radovan Garabik writes: > it should pack them as raw Py_UNICODE data. At least that is what > I'd need It happens that this is probably not what most people would expect: Instead, they would expect to get an array of wchar_t (which may or may not be the same thing as Py_UNICODE): why would any C API know what Py_UNICODE is? > This is exactly what I am trying to avoid, since I need to quickly loop > over the strings (it is a dictionary index) written in the file - hence > the C extension module. > I am afraid that using PyUnicode_DecodeUTF8 (or anything that creates a > PyObject) would impose a big speed penalty. Did you actually measure this? I very much doubt you can demonstrate any speed penalty. In any case, to pack this as Py_UNICODE, you need to .encode("unicode-internal") your string, then just add it to whatever else you are packing. Regards, Martin From grahamd at dscpl.com.au Thu Oct 17 05:20:39 2002 From: grahamd at dscpl.com.au (Graham Dumpleton) Date: 17 Oct 2002 02:20:39 -0700 Subject: SOAP frustrations References: <3DAC6F04.2030704@mindspring.com> Message-ID: martin at v.loewis.de (Martin v. Loewis) wrote in message news:... > grahamd at dscpl.com.au (Graham Dumpleton) writes: > > > Okay, you could use Java as you client, but at that point you may as > > well use something like RMI. > > Or you use Python. Oh, forgot to mention one thing. If one were to use JPython in a Java applet, we in part get back to the same issue as this post was originally about. That is, the inadequacy of SOAP implementations. This is because if you were to use Python, you still have to talk to the back end service somehow. Your choices would be to roll your own system with your own protocol or using Python pickling to transfer data around, or use an XML-RPC or SOAP implementation. Thus we haven't really got anywhere. At least RMI and associated protocols in Java present a more complete and robust base to start with. The argument thus still stands that Python doesn't provide a really mature way of implementing web services, which was where the original poster was getting frustrated. From maxm at mxm.dk Fri Oct 4 16:46:11 2002 From: maxm at mxm.dk (Max M) Date: Fri, 04 Oct 2002 22:46:11 +0200 Subject: making a class return None from __init__ References: Message-ID: <3D9DFE13.5040500@mxm.dk> Rajarshi Guha wrote: > (where v will fail) I always get <__main__.Graph instance at 0xXXXXXX> > Is there any way to make the constructor return a None object? def noner(): return print noner() >>> None regards Max M The reason I don't reach any higher is that I stand on the shoulders of little people. From warkid at storm.ru Wed Oct 2 10:51:23 2002 From: warkid at storm.ru (Kerim Borchaev) Date: Wed, 2 Oct 2002 18:51:23 +0400 Subject: newbie: find position of item in a list In-Reply-To: <3D9B01B4.4000700@stacom-software.de> References: <3D9B01B4.4000700@stacom-software.de> Message-ID: <5025123415.20021002185123@storm.ru> Hello Alexander, Wednesday, October 2, 2002, 6:24:52 PM, you wrote: AE> Hallo Again, AE> i wonder weather there is no expression of finding the position of a element is a list like: AE> l = ['a', 'b', 'c', 'd', 'e'] AE> l.find('b') AE> >> 1 AE> Have I overseen something in the documentation to python ? yes: >>> l = ['a', 'b', 'c', 'd', 'e'] >>> l.index('d') 3 Best regards, Kerim mailto:warkid at storm.ru AE> Tanks a lot AE> Alexander From psimmo60 at hotmail.com Wed Oct 16 10:55:53 2002 From: psimmo60 at hotmail.com (Paul Simmonds) Date: Wed, 16 Oct 2002 14:55:53 +0000 Subject: How to print an integer with commas; E.g., 3,056,789 Message-ID: >John Arundel wrote in >news:mailman.1034773342.23488.python-list at python.org: > > > How about: > > > > def commaise(seq): > > if len(seq) <= 3: > > return seq > > else: > > return "".join(commaise(seq[:-3]) + ',' + seq[-3:]) > > > >>>> commaise("3056789") > > '3,056,789' > >I see that this works well, but I don't understand it. I _think_ I >understand join(), but how is the looping accomplished? I suspect the "" in >the same line is what does this, but could you or someone explain a bit? It works by calling itself: || \/ > > return "".join(commaise(seq[:-3]) + ',' + seq[-3:]) So it runs the same function on the [:-3] slice, until it hits a slice smaller than or equal to 3 digits long. Hell of a lot neater doing this by recursion. Thanks John. HTH, Paul _________________________________________________________________ Surf the Web without missing calls! Get MSN Broadband. http://resourcecenter.msn.com/access/plans/freeactivation.asp From max at alcyone.com Sat Oct 12 05:23:25 2002 From: max at alcyone.com (Erik Max Francis) Date: Sat, 12 Oct 2002 02:23:25 -0700 Subject: Ignoring comments - Parsing input file References: Message-ID: <3DA7EA0D.9CEBEB4D@alcyone.com> Simon Faulkner wrote: > I am writing a script which reads it's input from a text file > > What is the easiest way to make it ignore lines that start with # or > blank lines? Something like: while 1: line = input.readline() if not line: break if line[-1] == '\n': line = line[:-1] # strip newline if line.find('#') >= 0): line = line.split('#', 1)[0] # remove everything if not line: continue # skip blank lines If your lines are insensitive to whitespace, a line = line.strip() would be in order there too. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ When angry, count four; when very angry, swear. \__/ Mark Twain Polly Wanna Cracka? / http://www.pollywannacracka.com/ The Internet resource for interracial relationships. From gerhard.haering at opus-gmbh.net Tue Oct 15 10:05:13 2002 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 15 Oct 2002 14:05:13 GMT Subject: Where to get Makefile.pre.in? References: Message-ID: Mykhaylo Sorochan [2002-10-15 14:02 GMT]: >> Makefile.pre.in is not supported anymore in Python 2.2. > So, how should I compile Zope? With Python 2.1.3. Zope doesn't support Python 2.2, yet (at least not officially). -- Gerhard From tjreedy at udel.edu Sat Oct 19 14:33:41 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 19 Oct 2002 14:33:41 -0400 Subject: running programs from within python through CGI References: Message-ID: "revyakin" wrote in message news:fa06e058.0210190931.17eb8bf5 at posting.google.com... > import os,sys > sys.path.append('path to blast') I believe sys.path is Python's private path for finding modules, and has nothing to do with the path used by command interpreters. > os.system('blast -args') So maybe you should try os.system('path/to/blast -args') > However, when I try to run that script from CGI it does not work, I > get the following error: > > sh: blast: command not found Presumably because blast is not on sh path when sh is invoked from cgi context. Terry J. Reedy From mhammond at skippinet.com.au Mon Oct 21 18:54:07 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Mon, 21 Oct 2002 22:54:07 GMT Subject: out parameters in Python and COM References: <3db3c98c.1049328250@news.skynet.be> Message-ID: Henk wrote: > When debugging my exe using Python I always get empty values for a,b > and c (see below) allthough they are filled in correctly inside the > exe (checked with a debugger). > > Any idea what could be wrong? In Python, these values are still *returned*. > import win32com.client > > atm = win32com.client.Dispatch("ATM.Shell") > b4 = atm.LogOn("Administrator", "EHSW", "Python") > > > a="" > b="" > c="" > HEMgr = atm.ATMHeadEndManager > HEMgr.SetCodeTable("BS","ES","EE") > HEMgr.GetCodeTable(a,b,c) You code should say: a,b,c,d = HEMgr.GetCodeTable() Mark. From tjreedy at udel.edu Fri Oct 11 12:44:42 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 11 Oct 2002 12:44:42 -0400 Subject: wxbutton References: <5b8834c2.0210102359.78954086@posting.google.com> Message-ID: "hellprout" wrote in message news:5b8834c2.0210102359.78954086 at posting.google.com... > hi i just want to know what can i do to have a wxbutton disabled > and after you can have a wxbutton enabled You will probably get a better answer sooner by asking questions like this on the specialized wxPython (wxWindows) mailing list. TJR From dvass at felis.uni-freiburg.de Thu Oct 31 08:06:01 2002 From: dvass at felis.uni-freiburg.de (Joerg Woelke) Date: Thu, 31 Oct 2002 14:06:01 +0100 Subject: problems with shell environment in os.system calls References: Message-ID: <3DC12AB9.63319F05@felis.uni-freiburg.de> Hi! Donn Cave wrote: [ snip ] > Finally I am bound to say that most of us are better off in the end > not using the C shell for programming. If you like it for interactive > use, that's mostly a matter of taste, but it is poorly designed for > programming despite some superficial conveniences. ACK, read: "www-dbs.inf.ethz.ch/~fessler/csh-whynot.html" > Donn Cave, donn at u.washington.edu HTH, J"o! -- From mwh at python.net Mon Oct 14 07:39:52 2002 From: mwh at python.net (Michael Hudson) Date: Mon, 14 Oct 2002 11:39:52 GMT Subject: Is there a "reset" in Idle? References: <0rc7qu4l03ga7cdpifce8je632mlcju1fi@4ax.com> Message-ID: "Fredrik Lundh" writes: > Alex Martelli wrote: > > I don't think there are any. As long as the IDE runs the Python > > application being debugged in a separate process (a pretty obvious > > need -- pity that neither IDLE nor PythonWin do that), what would > > those shortcomings be? > > lack of support for in-process editing of Python code > (reload doesn't help much). > > and a ton of other things that I cannot think of right now. > (it's all in the PythonWorks bug/request/idea/bluesky data- > base...) I don't suppose that's viewable to the public, is it? Cheers, M. -- GET *BONK* BACK *BONK* IN *BONK* THERE *BONK* -- Naich using the troll hammer in cam.misc From ark at research.att.com Wed Oct 2 18:27:22 2002 From: ark at research.att.com (Andrew Koenig) Date: 02 Oct 2002 18:27:22 -0400 Subject: [Python-Dev] PEP239 (Rational Numbers) Reference Implementation and new issues In-Reply-To: <20021002221421.GA29958@thyrsus.com> References: <20021002221421.GA29958@thyrsus.com> Message-ID: Eric> APL faced this problem twenty-five years ago. I like its Eric> solution; a `fuzz' variable defining the Eric> close-enough-for-equality range. I used to like APL's approach, but I've changed my mind. Part of the reason is that there are some places where unfuzzed comparison is essential, such as sorting. Another part is that fuzzy comparison destroys substitutability: If a==b, it is not always true that f(a)==f(b). Much as I like APL, I'd rather use Scheme's numeric model. -- Andrew Koenig, ark at research.att.com, http://www.research.att.com/info/ark From peter at engcorp.com Wed Oct 16 18:54:58 2002 From: peter at engcorp.com (Peter Hansen) Date: Wed, 16 Oct 2002 18:54:58 -0400 Subject: Dynamic copy/paste using DDE with Python on Windows References: <3dacaf6d$1@news.sentex.net> Message-ID: <3dadee4b$1@news.sentex.net> Anders M Eriksson wrote: > On Tue, 15 Oct 2002 20:14:29 -0400, Peter Hansen > wrote: > > >>I thought DDE was *way* deprecated by now, and long since replaced >>by OLE, then OLE2 or something, then COM, then ActiveX, and probably >>by now something else... >> > Since DDE is based on Windows Messages and Windows is really using > Messages I don't think it will be deprecated any time in the > foreseeable future! That may be, but just because the underlying mechanism is still in use may not be reason to say the beast called DDE that is built on top of it is still a recommended approach. >>Also, as far as I recall DDE was always broken in a number of, >>uh, "interesting" ways and probably not worth your time trying >>to get it working. Maybe someone else will point out that >>I'm wrong about that... >> > > I can't recall anything that has been broken!? Maybe the broken part > has been the Python implementation? My attempts to use it were with LabVIEW, and involved attempting to copy "large" blobs of binary data around between LabVIEW and a separate C program. Mostly I recall discovering it could not handle binary data fully (maybe no 0 bytes?) or could not handle more than 65280 bytes at a time, or something ugly like that. > For anyone that is interested in DDE, what it is, why you should use > it, DDE vs COM, ... This FAQ has all the answers! > http://www.angelfire.com/biz/rhaminisys/ddeinfo.html Thanks, I should check that out. -Peter From jdriller at orchid.org Sun Oct 20 23:13:31 2002 From: jdriller at orchid.org (Jonathan Driller) Date: 20 Oct 2002 20:13:31 -0700 Subject: newbie Q: how do you re prompt user? Message-ID: I am just getting started so a very basic Q: If I write something that prompts a user for a response and then use the same function later it does not work...how come? I have tried encapsulating this in a def and then calling itself at the end but that did not work either... #import sleep function so we can remind hiring manager... ;-) from time import sleep x = raw_input("Wanna hire someone who likes Python and likes to learn?") #use function to get input negative = '' #assignment of empty char to initialize positive = '' #loop thru all no possibilities (crude) and assign n if no if x == 'n': negative == 'n' elif x == 'No': negative == 'n' elif x == 'NO': negative == 'n' else: negative = '' while negative == 'n': print "Please reconsider your choice" #loop thru all yes possibilities (crude) and assign y if yes if x == 'y': positive = 'y' elif x == 'yes': positive = 'y' elif x == 'Yes': positive = 'y' elif x == 'YES': positive = 'y' else: print "Please reconsider that answer" while positive == 'y': print "Great, email Jonathan now!" print "he is waiting at xxxxxx.org" sleep(300) print "Did you email Jonathan yet?" #rerun function x = raw_input("Wanna hire someone who likes Python and likes to learn?") From anandpillai6 at yahoo.com Thu Oct 17 02:38:05 2002 From: anandpillai6 at yahoo.com (Anand) Date: 16 Oct 2002 23:38:05 -0700 Subject: Py2exe executable not loading images References: <41c203e.0210110459.41b7527@posting.google.com> Message-ID: <41c203e.0210162238.5fb3abea@posting.google.com> Hi Thomas Thanks a lot. It worked. I have similar problems in the module os, when using the os.listdir() function. Any ideas about it ? Here is the error report: "LookupError: no codec search functions registered: can't find encoding" I am passing a unicode string to the function os.listdir(dir) which works well in normal python interpreter. Thanks & Regards, Anand Thomas Heller wrote in message news:... > anandpillai6 at yahoo.com (Anand) writes: > > > I have a simple viewer class in python using wxPython and PIL. > > The code uses PIL Image class to open an image and wxPython classes > > namely wxFrame, wxBitmap, wxImage to paint it on to a wxPanel. > [...] > > > > The code works fine for all images when run as a python script. > > When I create a win32 executable using py2exe and setup.py, the > > Image class fails with a message > > > > > > > File "", line 453, in OpenImage > > File "PIL\Image.pyc", line 960, in open > > IOError: cannot identify image file > > > > > A simple Web search finds several pages offering solutions to this > problem. The best one I could find is from douglas zongker: > http://www.cs.washington.edu/homes/dougz/slithy/py2exe/ > > He writes: > > Statically load PIL image formats. Slithy uses the Python Imaging > Library to read image files. Normally PIL dynamically loads plugins > for the different file formats as it needs them; this scheme won't > work with py2exe. At the top of your main script, add a blob of > code that looks like this: > > > import Image > > import JpegImagePlugin # import drivers for every image format you use > import TgaImagePlugin > import PngImagePlugin > import GifImagePlugin > > Image._initialized = 1 > > HTH, > > Thomas From dkuhlman at rexx.com Fri Oct 18 17:07:12 2002 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Fri, 18 Oct 2002 14:07:12 -0700 Subject: SOAP frustrations References: <3DAC6F04.2030704@mindspring.com> <35b736b9.0210180325.3b6e5904@posting.google.com> <3db01b05$0$18872$afc38c87@news.optusnet.com.au> Message-ID: Nicolas Chauvat wrote: >> Yes. It *is* a security issue. By misusing port 80 for remote procedure >> ... ^^^^^^^^ >> change the policy. Screwing around with port 80 is going to cause a lot >> of ill-will. The first time a SOAP request comes through that runs some >> random bit of code that causes some damage, you can fully expect to be >> hung out to dry for it. >> >> Organizations have security policies for a reason. Hacking around them >> will *never* end well. > > [applause] I been waiting for someone else to ask this question so that I would not have to show my ignorance. No such luck. What about CGI? Uses port 80. Can run "random" bits of code. Powerful enough to destroy servers with a single script. How is CGI any less of a security threat? It doesn't take much of a wizard to write a Perl or Python CGI script that trashes a system, or ruins a database, or ... Isn't SOAP just another way of invoking a script. And, ditto for XML-RPC. With SOAP (and XML-RPC) I put some request information in the body of the request that I would have tacked onto the URL in CGI. How does that make CGI any less dangerous. Basically, hire any computer science student as an intern to come in and write either CGI scripts or SOAP Web service scripts and you are asking for "excitement". And, isn't the point that any of these (CGI, SOAP, XML-RPC) are no more dangerous than the scripts on the back-end that implement them, which puts control on the back-end where we want it. - Dave [snip] -- Dave Kuhlman dkuhlman at rexx.com http://www.rexx.com/~dkuhlman From martin at v.loewis.de Tue Oct 15 17:03:47 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 15 Oct 2002 23:03:47 +0200 Subject: International APPs / pygettext References: <3DAC5E22.1060102@web.de> Message-ID: Ingo Linkweiler writes: > "gettext" is included in the Python 2.2 distribution, but where can I > find "pygettext.py"? pygettext.py is also included in the Python 2.2 distribution, in the Tools/i18n directory. Regards, Martin From grante at visi.com Tue Oct 1 11:22:09 2002 From: grante at visi.com (Grant Edwards) Date: Tue, 01 Oct 2002 15:22:09 GMT Subject: Decimal arithmatic, was Re: Python GUI app to impress the boss? References: Message-ID: In article , Mark Charsley wrote: >> Usually, in the "canned" systems I've seen, those 3 for a >> buck deals are supported by allowing three to five decimal >> places rather than just two for amounts. Results come out >> much as you are expecting there. > > The system a previous company wrote said that "if they've bought 3 > 40p items these give them a discount of 20p". But, standard practice around here is that the "3 for a dollar" price is good on quantities of less than three. (IOW the unit price is 1/3 dollar). I have seen instances where you have to buy 3 to get the discount but IME that's rare. -- Grant Edwards grante Yow! MMM-MM!! So THIS is at BIO-NEBULATION! visi.com From timr at probo.com Thu Oct 3 02:56:35 2002 From: timr at probo.com (Tim Roberts) Date: Wed, 02 Oct 2002 23:56:35 -0700 Subject: wxpython problem References: <5b8834c2.0210020151.3276e847@posting.google.com> Message-ID: hellprout at yahoo.com (hellprout) wrote: >hi , i'm french , i try to use wxgrid or wxlistctrl to print a file , >the result of sql select... >after more test , i don't know what can i use this wx object ... >i just want to find a samlpe or a tutorial for this object ... >thanks a lot for your help I recommend that you join the wxPython-users mailing list: http://www.wxpython.org/maillist.php Then post your question, along with the sample application that is giving you trouble. The wxListCtrl is a little tricky to get started, but once you understand how it works, it does the job. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From bokr at oz.net Sat Oct 12 16:34:54 2002 From: bokr at oz.net (Bengt Richter) Date: 12 Oct 2002 20:34:54 GMT Subject: raw strings References: <2259b0e2.0210081328.2c749ab7@posting.google.com> <2259b0e2.0210100939.6fb23d46@posting.google.com> <2259b0e2.0210110528.449ce434@posting.google.com> <2259b0e2.0210120323.4eb16a1c@posting.google.com> Message-ID: On 12 Oct 2002 04:23:31 -0700, mis6 at pitt.edu (Michele Simionato) wrote: >Wow ! I am overwhelmed by your hack! > >It will take me a long time to understand it, but I will think about. > >I have found myself a partial solution which seems to be enough for my aims, >and I will post it in the future (now I have to test it ;-). > >I am impressed by the time you spent to answer my "silly" question, really >impressed. Thanks! You're welcome. It gave me an excuse to explore a few more trails in the Python woods. Note that it wasn't enough time to get all the bugs out ;-) >P.S. the correct spelling of my name is Simionato (a quite rare family name >except in a radius of five kilometers nearby my little village in North Italy, >where there are dozens of it ;-) My sincere apologies. My fingers seem to be untied in their conspiracy to humble me with their dyslexic mischief ;-/ Regards, Bengt Richter From gbrunet at sempersoft.com Tue Oct 8 21:44:41 2002 From: gbrunet at sempersoft.com (Greg Brunet) Date: 8 Oct 2002 18:44:41 -0700 Subject: Why is del(ete) a statement instead of a method? Message-ID: I'm just trying to learn Python, and one thing that struck me as odd was that to delete a specific list element, I need to use a statement instead of a method like I use for almost everything else I do on the list. This seems a bit inconsistent. Why wouldn't it be a method? -- Greg From amk at amk.ca Sat Oct 12 21:46:59 2002 From: amk at amk.ca (A.M. Kuchling) Date: Sat, 12 Oct 2002 20:46:59 -0500 Subject: Monty Python TV Collection References: Message-ID: In article , Emile van Sebille wrote: > The COMPLETE Monty Python TV Collection on DVD for $199.98 In other words, $70 more than I paid Amazon for it. Whatta deal! --amk From marklists at mceahern.com Wed Oct 16 08:08:38 2002 From: marklists at mceahern.com (Mark McEahern) Date: Wed, 16 Oct 2002 07:08:38 -0500 Subject: What is the class of myobj? In-Reply-To: <3DACF3B9.29D9C5A8@alcyone.com> Message-ID: [Erik Max Francis] > It usually isn't. When you're expecting a sequence type is a good > example, because there are some basic builtin sequence types (tuples and > lists), but there's also builtin functions which generate objects that > _act_ like builtin sequence types (for instance, the return value of > xrange or F.xreadlines), and of course there are user-defined sequence > types. And then there are strings, which are also sequence like--but you don't always want to iterate through them. E.g., def make_list(x): """ Return x as a list. If x is already a list or sequence type, return x. """ # Obviously, I'm missing user-defined sequence types. sequence_types = (list, tuple) if not isinstance(x, sequence_types): l = [x] else: l = x return l // m - From claird at lairds.org Thu Oct 3 10:10:05 2002 From: claird at lairds.org (Cameron Laird) Date: Thu, 3 Oct 2002 14:10:05 +0000 (UTC) Subject: how to get rid of html tags References: Message-ID: In article , Ian Bicking wrote: >The easy answer: > >page = re.sub(r'<.*?>', '', page) > >There may be more Correct answers, though. (Some HTML has unquoted <> >characters, which browsers accept even though it's super annoying to >parse -- but I don't know that htmllib parses improper HTML either) > >On Wed, 2002-10-02 at 20:04, koko wrote: >> I am trying to retrieve a web page. >> But I only want to keep the content of the webpage without the html tags. >> How can I parse the webpage to get rid of the tags? . . . People answer this question in *dozens* of different ways. Perhaps the most satisfying to koko will be dialectically. Does, for example, command-line lynx -dump $URL > $RESULT meet all your requirements? -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From anton at vredegoor.doge.nl Tue Oct 8 11:00:06 2002 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Tue, 08 Oct 2002 17:00:06 +0200 Subject: [OT} How to un-GPL parts of a GPL'd module. References: Message-ID: On Tue, 8 Oct 2002 09:03:44 -0400, "Steve Holden" wrote: >"Anton Vredegoor" wrote in message >news:anujeq$qdk$1 at news.hccnet.nl... > >> I guess I could e-mail the author for permission but if I would have >> to wait for them to answer, it would slow my coding process down to a >> snail's pace, and there's always the possibility of the author being >> unwilling. >> >Indeed. Perhaps you should consider releasing your own code under the GPL >rather than some other license. That way there's no problem incorporating >GPL'd code. That would solve the problem at the cost of passing on the problem to the next coder. It's this kind of "chain letter like" property that I want to adress. >> I know a lot of people rely on writing sourcecode for a living but I >> have been unemployed as a programmer for so long know that the concept >> of owning sourcecode or getting payed for producing it is completely >> alien to me. I think I'll be writing free sourcecode till I die just >> hoping some pieces of my code will survive into eternity. If someone >> has a problem with that, hire me. >> >Sort of like "send money or I'll shoot the dog"? Not a very promising >aproach to potential employers. I would encourage you to contact the >original author and see if you can't get permission to include the code >under license terms acceptable to you. Otherwise you'll need a clean room >implementation (which, if the algorithm is obvious, might be similar to the >GPL'd code, but should be your own work rather than someone else's). > In case it's not clear, the chance of me finding an employer is remote. Contacting the original author consumes time and the outcome would probably not be good since I don't agree with the "pass the problem to the next guy" property of the GPL. Since the dog metaphore was brought up, I would like to add the comparison of having a GPL dog using a specific tree for some known purpose and forbidding any other dog to use it for that same purpose ... Regards, Anton. From python at rcn.com Tue Oct 22 01:25:39 2002 From: python at rcn.com (Raymond Hettinger) Date: Tue, 22 Oct 2002 01:25:39 -0400 Subject: PyDev Summary for week ending 20-Oct-2002 Message-ID: <00d301c2798b$76213ce0$e8d8accf@oemcomputer> I'm filling in while Brett is on vacation. To make everyone appreciate his formatting and lucidity, I'll skip the reStructuredText and write in my own terse style. http://mail.python.org/pipermail/python-dev/2002-October/029577.html Python 2.2.2. was released in final form this week. Oh, yeah! http://mail.python.org/pipermail/python-dev/2002-October/029527.html Why does the Window's installer use shortened 8.3 pathnames? Answer: It doesn't have to, but it is less confusing than dealing with pathnames that can have embedded spaces. http://mail.python.org/pipermail/python-dev/2002-October/029544.html PEP 218 was updated to match the sets.py module in CVS for Python 2.3. The question arose as to whether immutable sets should be implemented in C as a separate type or whether mutability should be a property. Answer: Keep them as different types since they support different methods. Next question: Should there be a separate language syntax for the two different types. Answer: Probably not, leave as an open question in the PEP. http://mail.python.org/pipermail/python-dev/2002-October/029542.html The -U flag was put in to test the Python standard lib for being able to handle Unicode seamlessly. It remained undocumented so that bug reports wouldn't pile up while the issues were being worked out. Progress is being made but it is possible the -U flag will never be fully implemented and released as a documented feature. http://mail.python.org/pipermail/python-dev/2002-October/029535.html Python has more than one place that is vulnerable to 32 bit word overflows unless a bunch of tests are put in place to catch unusual highly contrived cases that never come up in real world examples. Since the fixes would be ugly, wordy, and slow, it was decided to leave them alone. http://mail.python.org/pipermail/python-dev/2002-October/029024.html Tcl 8.0 and 8.1 are ancient history except in the world of Cygwin which is currently stuck with 8.0. Accordingly, Python 2.3's support for the prior versions has been cleaned out and support for UCS-4 in _tkinter has been added. http://mail.python.org/pipermail/python-dev/2002-October/029591.html Getting mtime, atime, and ctime to return floats instead of ints seemed like a simple enough change. Much discussion was held on how to accommodate the change without breaking anything that relied on the type. Though breakage would've been rare (since the only normal use for the data is to compare it or print it), Guido proposed a solution (putting the ints in the tuple) that seemed to accommodate all practical cases. http://mail.python.org/pipermail/python-dev/2002-October/029679.html Brian Quinlan teasesd out the design issues behind proxies and weakref objects. From stuart at bmsi.com Thu Oct 3 13:41:21 2002 From: stuart at bmsi.com (Stuart D. Gathman) Date: Thu, 03 Oct 2002 17:41:21 GMT Subject: mailbox module broken! References: Message-ID: <5j%m9.73068$IL6.3695274@news2.east.cox.net> On Thu, 03 Oct 2002 13:36:47 -0400, Stuart D. Gathman wrote: > The following trivial code to read through a unix mailbox skips a little > over 100 messages in the mailbox at > > http://www.bmsi.com/python/test/inbox > > I have tested python-2.1.3 and python2-2.2.1 I have tested on both RedHat 7.2 and AIX 4.1.5. The mailbox module *does* work *most* of the time. That is why I need to provide a specific mailbox that it fails on. I have been unable to manually create a small mailbox with the same problem. BTW, the mailbox is normally managed with the UW IMAP daemon. -- Stuart D. Gathman Business Management Systems Inc. Phone: 703 591-0911 Fax: 703 591-6154 "Confutatis maledictis, flamis acribus addictis" - background song for a Microsoft sponsored "Where do you want to go from here?" commercial. From ark at research.att.com Thu Oct 31 14:05:55 2002 From: ark at research.att.com (Andrew Koenig) Date: Thu, 31 Oct 2002 19:05:55 GMT Subject: How to use new email package to read a mailbox? Message-ID: The documentation for the mailbox package says that the default behavior of class UnixMailbox is to use rfc822.Message to create messages. However, rfc822 is noted as deprecated. Suppose I have a file that represents a Unix mailbox. What's the right idiom to use to process each message in that file using the new email package? -- Andrew Koenig, ark at research.att.com, http://www.research.att.com/info/ark From derek at wedgetail.com Fri Oct 18 10:30:12 2002 From: derek at wedgetail.com (Derek Thomson) Date: Sat, 19 Oct 2002 00:30:12 +1000 Subject: SOAP frustrations References: <3DAC6F04.2030704@mindspring.com> <35b736b9.0210180325.3b6e5904@posting.google.com> Message-ID: <3db01b05$0$18872$afc38c87@news.optusnet.com.au> Hi John, John Keeling wrote: > > Over the internet, you really want to use Web Services rather than > CORBA, because CORBA/IIOP uses multiple ports that have to be > explicitly allowed on the firewall ( on both the client and server > side). This is an admin and security issue. Yes. It *is* a security issue. By misusing port 80 for remote procedure calls, you are violating the contract between you and your sysadmin, and quite likely violating your organization's (our your client's) security policy. That port was opened to allow web pages to be served up, not to run bits of arbitrary code on request. If I were a sysadmin, I'd be blocking anything that looks like SOAP at the firewall. Sysadmins I've spoken to about SOAP have reacted with horror when I explain the nature of SOAP, and have started writing little filters already ;) Expect a few "anti-SOAP" scripts on sourceforge any time now. The problem with this whole firewall issue is that it's a political and organizational one. It *cannot* be solved technically. If you want RPC you have to allow it through the firewall. Many developers/deployers don't even think to find out what the admins think at the deployment site, or even what the security policy is, and certainly don't do what they *should* do - which is to involve the admins who are looking after the target system. Instead, they get all upset when the admin, who has a professional responsibility for the security of his users' data, refuses to just open up random ports without notice. Then the deployer views the admin as the problem that must be "worked around". Enter SOAP and misusing port 80 to get RPC requests throught without needing a anyone's authority. All that will happen is the sysadmins will be forced to filter it, and you are back to square one. The lesson is - you can't hack around a problem like this. You have to negotiate, and get all the people who will be impacted by your development involved from day one. Sure, they might say, "this is against our policy, it will never be allowed", but isn't it better to find that out *before* starting? Then, if you want, you can work to change the policy. Screwing around with port 80 is going to cause a lot of ill-will. The first time a SOAP request comes through that runs some random bit of code that causes some damage, you can fully expect to be hung out to dry for it. Organizations have security policies for a reason. Hacking around them will *never* end well. -- D. From brian at sweetapp.com Tue Oct 1 18:42:59 2002 From: brian at sweetapp.com (Brian Quinlan) Date: Tue, 01 Oct 2002 15:42:59 -0700 Subject: Override a method in another module In-Reply-To: Message-ID: <000d01c2699b$e4c183d0$df7e4e18@brianspiv1700> > What's the basic syntax to override (redefine) a function in another > module at runtime? > > Say, I have module M, class C, method F, and I want to redifine method F. > > setattr( M.C.F, eval("def F(self): pass")) doesn't exactly work..... You are working too hard: def F(self): pass M.C.F = F Cheers, Brian From jb at cascade-sys.com Thu Oct 3 09:35:55 2002 From: jb at cascade-sys.com (James J. Besemer) Date: Thu, 03 Oct 2002 06:35:55 -0700 Subject: PEP239 (Rational Numbers) Reference Implementation and new issues References: <20021002221421.GA29958@thyrsus.com> Message-ID: <3D9C47BB.9050504@cascade-sys.com> Fran?ois Pinard wrote: >On the other hand, [...] >On average, most programs will not use matrices of rational numbers, >nor play with series. Moreover, most programs do not use so many different >numeric variables anyway, nor perform long computations involving them. >Many programs do not go beyond adding or subtracting one, once in a while! > I think this is an excellent point. The prospective active user base for rationals, at least initially, is a small subset of the user base. Most people who propose to do much numerical computation often encounter performance issues and in any case are quickly referred to Numerics rather than Python intrinsics. Most courses in "Numerical Analysis" assume floating point arithmetic and include chapters on minimizing loss of precision. However more "accurate" Rationals may be in a mathematical sense they really are a novelty to the majority of computer users and programming environments. While I support their addition to the language I don't see that they'd be something I or the majority of users would use on a routine basis. Like Complex numbers, rationals just don't apply to a large portion of programming applications. I certainly think it would be much more confusing for Newbies to find rational objects showing up and possibly slowing their computation when they least expect it. Guido is right that rationals should be off to the side a bit and not show up in any computations unless expressly introduced by the user. I think complex numbers are a good model -- naive users can pretty much ignore their presence altogether and not get into trouble. >So it might be more >worth accepting as a community to warn programmers who are more prone to >numerical algorithms of the intrinsic dangers of integer division in Python. > I personally think the "dangers" of integer division have been vastly exaggerated. Integer division is older than computers and it's really a trivial concept. The answer cannot be represented accurately so instead you get an approximation. Furthermore, integer division and integer modulo together DO produce a complete and exact answer -- a whole number quotient and a remainder. In my experience, when dealing with integers, the original integer division result (and the modulo) is more useful in practice than the "more accurate" floating point result. That decision is water over the bridge. But substituting a rational for the present floating point result would only be more confusing. Regards --jb -- James J. Besemer 503-280-0838 voice 2727 NE Skidmore St. 503-280-0375 fax Portland, Oregon 97211-6557 mailto:jb at cascade-sys.com http://cascade-sys.com From hughett at mercur.uphs.upenn.edu Sun Oct 13 14:14:19 2002 From: hughett at mercur.uphs.upenn.edu (Paul Hughett) Date: 13 Oct 2002 18:14:19 GMT Subject: [OT} How to un-GPL parts of a GPL'd module. References: Message-ID: offer at sgi.com wrote: : The GPL (like all copyrights) cover an implementation. It does not cover : an idea (that is what patents are for) : To un-GPL something re-do the implementation such that a court would : not see it as a derivative work. : One way obvious way to do this is to convert the algorithm into an : English specification, then to hand that specification off to someone else : (who has not seen the GPL code) for implementation. You can also do it the same way the FSF did to avoid possible copyright suits over reimplementing the basic Unix utilities. Rewrite the algorithm from scratch, making some substantial and non-trivial improvement. If I remember correctly, the FSF rewrote the utilities to remove all arbitrary memory limitations; that is, the improved utilities will malloc as much memory as they need rather than relying on fixed buffer sizes. Paul Hughett From timr at probo.com Sat Oct 12 02:23:47 2002 From: timr at probo.com (Tim Roberts) Date: Fri, 11 Oct 2002 23:23:47 -0700 Subject: I really don't understand Lambda! References: <3DA611F0.588D1037@kootenay.com> Message-ID: Bob van der Poel wrote: >... >However, originally, I had tried: > > wg.bind("", lambda s=wg: seq.setSize(s) ) >... >So, if we don't need to use the variable, why not leave out the >assignment: > > wg.bind("", lambda : seq.setSize(wg) ) > >So, (1) do we always need some kind of assignment between the 'lambda' >and the ':'? Because until Python 2.1, each lambda had its own local namespace. It could not see items in the outer namespace. In your example, the lambda would not have been able to see "wg". You had to pass it as a parameter. With the nested scopes feature in 2.1, the extra parameter is no longer necessary, but there's a lot of code out there that wants to be backwards compatible. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From ianb at colorstudy.com Fri Oct 11 03:23:36 2002 From: ianb at colorstudy.com (Ian Bicking) Date: 11 Oct 2002 02:23:36 -0500 Subject: GUI problem In-Reply-To: References: <369fc45d.0210081239.57a5153a@posting.google.com> <87elazsc8n.fsf@theasylum.dyndns.org> <369fc45d.0210102033.6b27fb75@posting.google.com> Message-ID: <1034321016.21802.206.camel@dsl-65-184-205-5.telocity.com> On Fri, 2002-10-11 at 02:10, Alex Martelli wrote: > I think your best bet might be PyUi, http://pyui.sourceforge.net/ -- I > have not used it "in production", but it seems clean and powerful, > with a simple core. I think it would be a bit odd to start out with PyUI. It's a little odd, in that you get a desktop in a desktop -- the windows you create with PyUI are all contained inside a larger window, and you can only have one of those larger windows. I think it's really meant for adding widgets to SDL -- if you aren't using SDL, you wouldn't want to start with PyUI. Maybe something like PythonCard (http://pythoncard.sourceforge.net/) would be more appropriate. Ian From magnus at thinkware.se Sun Oct 6 20:06:11 2002 From: magnus at thinkware.se (=?ISO-8859-1?Q?Magnus_Lyck=E5?=) Date: Mon, 07 Oct 2002 02:06:11 +0200 Subject: Which Linux distribution References: <814a0eba.0210050348.452ed9ab@posting.google.com> Message-ID: <3DA0CFF3.1050103@thinkware.se> Jaroslav Gresula wrote: > I've installed RH 7.3 recently and I'm pretty frustrated from their > approach to Python packages. It is almost impossible to switch to > Python 2.x version since majority of their scripts is based on 1.5.x. From RH 8.0 Python 2.2.1 is the standard python, so the problem with Red Hat can be fixed with an upgrade. I'm sure most Linux distros will do though. A number of Linux distros do depend on Python for various tools though, which mean that upgrades to non backward compatible versions might cause some problems. Of course, there is nothing stopping you from having several different pythons in any linux box, the questions is just that "which python" might have to point at a certain version... From loewis at informatik.hu-berlin.de Sun Oct 6 07:45:49 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 06 Oct 2002 13:45:49 +0200 Subject: McMillan / Tk / encoding problem References: Message-ID: Gordon McMillan writes: > When you live in the US, use a US keyboard and speak US English, > there is nothing usual about encodings at all. I managed to learn > that most of the world needs the encodings, so unless you use the > --ascii switch, Installer will pretend you imported them (all of > them). If Installer needs to do more to trigger Python's automagical > unicode support, someone will have to tell me what it is. That sounds sufficient to me. If an application has requirements beyond that, I'd like to see what those requirements are, as well. Regards, Martin From bobx at linuxmail.org Tue Oct 8 16:36:09 2002 From: bobx at linuxmail.org (Bob X) Date: Tue, 08 Oct 2002 20:36:09 GMT Subject: appending to beginning of line References: <1001ff04.0210080422.1e373e13@posting.google.com> Message-ID: Terry Reedy wrote: > "Bob" wrote in message > news:1001ff04.0210080422.1e373e13 at posting.google.com... > >># loop through the list and print the lines to a file >>for line in inFile.xreadlines(): >> for badword in kw: >> if line.find(badword) > -1: >> found = '%s %s' % (badword, line) >> print found # Print the result >> outFile.write(found) # replace with > > >>This will print the badword and then the line it is on. For those >>lines that do not contain a badword I want to place a hyphen "-". > > > Is this what you are looking for? > > for line in inFile.xreadlines(): > ok = True > for badword in kw: > if line.find(badword) > -1: > found = '%s %s\n' % (badword, line) > print found, # Print the result > outFile.write(found) # replace with > outfile.write(found+'n') # Write the result > ok = False > if ok: line = '- ' + line > print line, > outFile.write(line) > > Terry J. Reedy Errors out... File "D:\Robert\Projects\Python\inplace.py", line 51 outFile.write(found) # Write the result ^ SyntaxError: invalid syntax From skip at pobox.com Fri Oct 25 12:02:59 2002 From: skip at pobox.com (Skip Montanaro) Date: Fri, 25 Oct 2002 11:02:59 -0500 Subject: Did someone turn down the volume? In-Reply-To: References: <15800.41069.748576.14291@montanaro.dyndns.org> Message-ID: <15801.27443.231436.927906@montanaro.dyndns.org> Pearu> If you compare python-list archives with comp.lang.python Pearu> archives at google then python-list archives are missing large Pearu> number of messages. For example, python-list contains only one Pearu> message dated as Oct 24 but c.l.py has more than 30 messages for Pearu> the same day. Agreed. Pearu> So, maybe news-to-mail gateway is not working properly? I don't think so. Barry Warsaw checked into this yesterday and saw nothing wrong. Seems there is a problem with their ISP's newsfeed. Barry sent them a note about it yesterday afternoon. -- Skip Montanaro - skip at pobox.com http://www.mojam.com/ http://www.musi-cal.com/ From nico at logilab.fr Wed Oct 16 09:53:53 2002 From: nico at logilab.fr (Nicolas Chauvat) Date: Wed, 16 Oct 2002 13:53:53 +0000 (UTC) Subject: Return to Mensa Puzzle Message-ID: In a thread named "A challenge from the Mensa Puzzle Calendar"[1], I mentionned Logilab's constraint package without showing how to use it. For those that are interested, Alexandre Fayolle just posted a solution to the python-logic mailing list[2]. Interested parties are invited to join the Python-Logic SIG[3]. 1: http://groups.google.fr/groups?threadm=d1f767c3.0210031125.6089e63b%40posting.google.com 2: http://lists.logilab.org/pipermail/python-logic/2002-October/000030.html 3: http://www.logilab.org/python-logic/ -- Nicolas Chauvat http://www.logilab.com - "Mais o? est donc Ornicar ?" - LOGILAB, Paris (France) From public at tjora.no Thu Oct 31 09:28:19 2002 From: public at tjora.no (Sigve Tjora) Date: Thu, 31 Oct 2002 15:28:19 +0100 Subject: pymat on windows problem Message-ID: Hi. I am trying to use pymat with Matlab 6.1 on Windows XP with Numeric 22 and pymat 20 and python 2.2.2. I am not able to load the dlls. When I try I get >>> import pymat import pymat Traceback (most recent call last): File "", line 1, in ? ImportError: DLL load failed: The specified module could not be found. I have pymat.pyd in the pythonpath and c:\matlab6p1\bin\win32 is in the dospath. Does anybody have any idea? regards Sigve From marklists at mceahern.com Mon Oct 14 13:54:50 2002 From: marklists at mceahern.com (Mark McEahern) Date: Mon, 14 Oct 2002 12:54:50 -0500 Subject: Linux install question In-Reply-To: <0mDq9.28116$Lg2.7040405@news2.news.adelphia.net> Message-ID: [Robert Oschler] > When you get a new Python tarball, like the new one for 2.2.1b for > instance, what directory do you put it in? Also, what directory do > you extract the contents of the tarball, before running > 'configure/make/etc'? I'm trying to make my directory structure as > uniform as possible. I use: /var/tmp/ Cheers, // m - From jb at cascade-sys.com Tue Oct 1 21:29:43 2002 From: jb at cascade-sys.com (James J. Besemer) Date: Tue, 01 Oct 2002 18:29:43 -0700 Subject: Larry Wall's comment on python... References: Message-ID: <3D9A4C07.7020706@cascade-sys.com> sismex01 at hebmex.com wrote: >AND, I distinctly remember that most printers could customize >their tab stops via escape codes, same as some (not all) terminals; >I worked a lot on some Xoroc terminals, and lots on a Northstar >Advantage (ahh, beautiful hardware... *snif*) and they also had >customizable tabstops. > Escape codes? What's that? ;o) Yes, I think in the trans-PC era -- or really it was the microprocessor era when it finally was possible to dedicate a computer to a desktop printer -- configurable tab stops became the norm. I remember the first printer I bought. It had a zillion escape codes for the half dozen crummy fonts plus Kanji etc., etc. I recall you could set tab stops out of order and make it zig-zag back and forth between them. Krazy uP programmers had ROM to spare and got carried away. To my knowledge I NEVER used ANY of these features (except perhaps sometimes picking an alternative font). >Hmmm... maybe, what I'm getting at is, why did terminal-designers >everywhere toss out years of research in typewriter technology >(at the time) and ignore customizable tab-stops? It's simply not >sane, I think. > I don't know for sure and only purport to report what happened. I guess what I'm saying is that the "heritage" extended back before printers and terminals were smart enough to have tab stops. Most early equipment simply ignored it or printed a goofy symbol. Fact of the matter, a LOT of unit record equipment (and I date myself in even using that term) in the decades before the microprocessor did not have expandable tabs. Or if they did it was not generally user programmable. E.g., the "line printer" we had attached to our PDP-11 had no notion of tabs. Nor could it print square or curly braces or a few other characters critical to C programming. All had to be done by the device driver. It DID have a "programmable" sense of vertical tab and vertical height -- but that was reprogrammed by changing a carefully crafted punched tape. Then there was an issue that communicating tab settings from user space to the device was an additional complication most users didn't care about and most systems programmers didn't want to bother with. This is just speculation but I believe the heritage dates back to where the effort to compute tab stops was not insignificant. I believe 8 chars was chosen because it could be computed with masking functions instead of a divide or mod. Then too, from the beginning Unix acknowledged that SOME terminals were smart enough. So you could tell the driver to send tabs instead of expanding them. We actually had some "smart" terminals with user settable tabs. Everybody wasted some time mucking with tabs and then gave up. It simply was too much of a nuisance for no gain. There wasn't any software that knew about your hardware stops so there was absolutely no point. >Indeed. I *do* recognize that using actual tabs is a much better >solution, but having hard-stops each 8 chars is a show-stopper, >so if my editor can't customize it's tab width, or customize it's >stops (say, when in asm, on columns 12, 18 and 32) then I'm never >going to use it willingly (you *could* whip me into submission, >but I'll curse your name for the rest of my natural life ;-) > I'm not telling anybody what to do. Be free. Be happy. "Go wherever you want to go and do whatever you want to do -- just so long as you don't hurt anybody." >That's what I mean. An editor should be smart enough to handle tab >stops at arbitrary columns, and when using tabbed text, jump between >those columns. Best of both worlds. > I think now days most do. But IMHO it's more effort than it's worth. "Arbitrary" columns seems overkill to me, something for word processing, not computer programming. I can live with evenly spaced tabs at 4 or 8. For me, 8 seems less troublesome because that's how it comes out anyway whenever I am NOT using my special editing environment. And I do like sometimes to use "more", "grep", "pr", "lpr", "notepad", etc., etc. to process my files and most of them still live in an 8 char stop world. >I find them hmmm... philosophically [sp] "wrong", because computers, >being programmable and customizable ("terminals" being specialized >computers) and so, should _at_least_ do what their mechanical >counterparts are able to do, and then some. > The proportional-spaced glyphs I'm looking at on the flat panel monitor are so far removed from the original typewriters that I'm not sure there's even a connection. Yeah, "typing" is a tiny subset of what we use computers for but the analogy sort of breaks down after that. I recall this ancient Remington typewriter that was my fathers -- I used it for papers in high school. Tab stops were changed by removing and reinserting these little clips in the back of the unit. I guess MS Word is SORT of like that only it's easier to insert, remove and move the stops plus you have more flavors. Too, if we're talking about programming, "arbitrary" tab stops seems way overkill. I use all sorts of fancy features when I'm formatting documents. But with code -- I don't even like proportional fonts. >Would an electronic calculator survive, if it couldn't do the same >operations as a mechanical adding machine? > Well, possibly. The myriad extra operations and speed and quiet and portability of modern electronic calculators makes them preferred though many lack hard copy output, a standard feature of most mechanical calculators. Anyway, you're confusing the ability to do something (arbitrary tab stops which I believe is readily achievable) with the need to do it (which is what I was questioning). >Yup, I did the same also, but maybe it was because there was no >alternative? > Spaces were an alternative that some people used. Some fools didn't indent at all. One C project, the lead came up with a standard that indented each level 3 spaces. His reasoning was (a) tabs were bad so they were out, (b) two spaces was too small, (c) 4 was too many to type and thus (d) 3 spaces was Just Right. Needless to say, I used tabs and was prepared to convert if need be when I finished. Alternatively, maybe the standard prevailed for so long because it worked so well for everybody. >Same here, I find that kind of argument a falacy: "my program is >badly modularized and I can't read it clearly, it's the editor's >fault". Nope, sorry. > Then why the emotional contrast between 4 and 8? >If it was corporate standard, it sux. But, as for personal taste, >I never could decide which looks better, either: > >I'm still somewhat ambiguous over which is more readable, >maybe it depends on the context, the surrounding code, >the tab width, the amount of spaces one uses for the >begin/end indent and the actual code indent, I don't >know and I don't really care to do reasearch about it. > Personally I think they all suck. Big problem was the begin/end in the first place. It was such a relief to switch to {}, and further to get rid even of them. >It's been nice tossing ideas around :-) > Ditto. REgards --jb -- James J. Besemer 503-280-0838 voice 2727 NE Skidmore St. 503-280-0375 fax Portland, Oregon 97211-6557 mailto:jb at cascade-sys.com http://cascade-sys.com From SBrunning at trisystems.co.uk Tue Oct 8 06:39:05 2002 From: SBrunning at trisystems.co.uk (Simon Brunning) Date: Tue, 8 Oct 2002 11:39:05 +0100 Subject: Misc questions about type objects and Python 3.0 Message-ID: <31575A892FF6D1118F5800600846864DCBD923@intrepid> > From: David Brown [SMTP:david at no.westcontrol.spam.com] > > 2. If it isn't (I'm guessing it will be), is it the plan to keep > > reference counting? It seems to me that getting rid of reference > > counting might be the first step to getting rid of the GIL. > > First, I would think that removing reference counting would wildly change > the way Python works (correct me if I'm wrong here - I program with > Python, > but I haven't studied its implementation). I don't see how you can get > efficient garbage collection without some sort of reference counting. Jython doesn't use reference counting and it's hardly *wildly* different from CPython. Subtly different, yes, but you don't notice the difference very often, unless you are prone to de-referencing open files, or that sort of thing. Cheers, Simon Brunning TriSystems Ltd. sbrunning at trisystems.co.uk ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From ldwhitley at RemoveMe.charter.net Fri Oct 11 18:49:39 2002 From: ldwhitley at RemoveMe.charter.net (L Whitley) Date: Fri, 11 Oct 2002 17:49:39 -0500 Subject: Win32 and Excel ranges Message-ID: I've been going through Mark Hammond's book doing his Python/Excel examples. It's working nicely but I'm dissapointed with the performance of storing a lot of data in the spread sheet cell by cell. My data is in lists and I would think that I would be reasonable to use ranges deliver the data to Excel. I've found examples of how to read data from Excel using range, but haven't found an example of how to write data to Excel using range. Can anyone help? Larry From tdelaney at avaya.com Sun Oct 20 22:18:43 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Mon, 21 Oct 2002 12:18:43 +1000 Subject: dict1 < dict2 <=> len(dict1) <= len(dict2) ? Message-ID: > From: Tim Peters [mailto:tim.one at comcast.net] > > [Tim] > > 2. Comparing a dict against an empty dict, as in > > > > while dict > {}: > > [Delaney, Timothy] > > Do people actually do that Tim? That's brain dead ... > > > > while not dict: > > No, *that's* brain dead . What a normal person does is > > while dict: > > Perhaps those who get burned by writing "not dict" instead > feel that "dict > > {}" is clearer. I haven't seen it often in any case. You just had me laugh out loud at my own idiocy :) Tim Delaney From martin at v.loewis.de Sat Oct 12 18:50:51 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 13 Oct 2002 00:50:51 +0200 Subject: 4Suite / non-ASCII filenames References: Message-ID: Thomas Korb writes: > The file names come from various sources; e.g Tk - file select > boxes, but also default filenames (defined in the script), > file names passed as arguments on the commandline (Linux only) etc. When they come from Tkinter, I doubt they are byte strings: Tkinter will return Unicode strings in this case. For things coming from the command line, it would be good to convert them to Unicode. > > Can you arrange it to be a Unicode string instead? > > > > Would be no problem (but passing a Unicode-filename to the XSLT- > processor leads to a similar error). Yes. It would be good if you could report the precise place where this causes an error. I'll assume that it is when passing the Unicode string to the open call. In this case, please do locale.setlocale(locale.LC_CTYPE, ""). If you have set lang to, say, de_DE.ISO-8859-1, this will cause the file system default encoding to be set to latin-1. In turn, open will accept Unicode file names as long as they can be converted to latin-1 - independent from the system default encoding. > But I have the feeling that they rely on the default encoding when > dealing with filenames. And since I do not want to use sitecustomize.py, > I do not know how to solve this problem. I assume they mix the URI with some Unicode object, so it would be good if the URI was already a Unicode string. > (Is there a good reason why sys.setdefaultencoding() is not allowed > in scripts? This is not the first time that I would need something > like that.) If sys.setdefaultencoding was available, then people may arrange to break libraries - libraries may not expect that the encoding of their byte strings changes from under them. By not making this a feature, life for library authors ought to get simpler. Also, I'm personally convinced that there is no need to have the system default encoding at any other value but ASCII; problems *can* be solved, in an elegant way, without having to change global variables. Regards, Martin From cliechti at gmx.net Sun Oct 13 15:39:11 2002 From: cliechti at gmx.net (Chris Liechti) Date: 13 Oct 2002 21:39:11 +0200 Subject: building extensions with gcc and python 2.2 References: Message-ID: Ken Seehof wrote in news:mailman.1034532618.15527.python-list at python.org: > I'm developing a tool that involves dynamic compilation of python > extensions. Since I do not want to require my windows users to buy > MSVC, I can no longer use it build my extensions (i.e. the user needs > to be able to recompile). > > Therefore, I am experimenting with using gcc as my compiler. > > Should I use Cygwin or Mingw? use --compiler=mingw with both... i use cygwin with the mingw option and it works perfectly, while i had some troubles with the cygwin mode. the advantage of mingw is that there are no dependencies with the cygwin.dll. > I've found an ancient tome by Robert Kern suggesting Mingw: > http://starship.python.net/crew/kernr/mingw32/Notes.html > It's very nice documentation, but unfortunately, it's for python 1.5.2 > and is dated Aug 09, 1999. Is there any current documentation of that > quality? all you need to know is in the standard docs. just use distutils like python setup.py --compiler=mingw thats all. you have to build the import library the first time. it works fine with pexports and dlltool. chris -- Chris From gmcm at hypernet.com Sun Oct 6 07:37:39 2002 From: gmcm at hypernet.com (Gordon McMillan) Date: 06 Oct 2002 11:37:39 GMT Subject: McMillan / Tk / encoding problem References: Message-ID: Thomas Korb wrote: > Actually, I have the usual > > import sys > sys.setdefaultencoding('iso-8859-1') > > in my sitecustomize.py. I don't know, how the default-encoding can be > set otherwise. In my script, I use an explicit 'import sitecustomize', > which is maybe very naive, but somehow worked. (Before that, I got > errors when a character was not in the ASCII-range 0-127; after that, > those errors did not show up anymore; so it seemed to have 'some' > effect.) > > Is there another way to set the default-encoding for use with your > installer? (I never liked sitecustomize.py any way; and I always felt > that something like sys.setdefaultencoding(...) should work in a normal > script, too.) When you live in the US, use a US keyboard and speak US English, there is nothing usual about encodings at all. I managed to learn that most of the world needs the encodings, so unless you use the --ascii switch, Installer will pretend you imported them (all of them). If Installer needs to do more to trigger Python's automagical unicode support, someone will have to tell me what it is. -- Gordon http://www.mcmillan-inc.com/ From tiberius at ms28.hinet.net Thu Oct 10 10:30:41 2002 From: tiberius at ms28.hinet.net (Tiberius Teng) Date: 10 Oct 2002 07:30:41 -0700 Subject: Python Forms? References: Message-ID: <6c92a8bc.0210100630.49ae7da1@posting.google.com> I would recommend you take a look at Spyce (and Cheetah Template Engine). (I've tried WebWare+PSP and Zope before, and now developing a forum system with Spyce.) http://spyce.sourceforge.net/ http://www.cheetahtemplate.org/ From bvdpoel at kootenay.com Mon Oct 14 14:22:31 2002 From: bvdpoel at kootenay.com (Bob van der Poel) Date: Mon, 14 Oct 2002 11:22:31 -0700 Subject: I really don't understand Lambda! References: <3DA611F0.588D1037@kootenay.com> <1034295802.21804.118.camel@dsl-65-184-205-5.telocity.com> Message-ID: <3DAB0B67.ED0D64BF@kootenay.com> Ian Bicking wrote: > > On Thu, 2002-10-10 at 18:49, Bob van der Poel wrote: > > Just when I thought I was understanding lambda, it totally confuses me. > > I have the following statement in my program, which works: > > > > wg.bind("", lambda s=wg: seq.setSize(wg) ) > > I think you want: > > wg.bind("", lambda e, s=wg: seq.setSize(s)) > > The callback is always called with the event as the one argument (even > if you don't care about the event). > > Ian Thanks. This works perfectly. Understanding a bit more... Am I correct in understanding that the args (if that is what they are called) between the 'lambda' and the ':' are evaluated when the bind is first evaluated.... So, if 'wg' is changed later the 's' is in it's own namespace and not affected. -- Bob van der Poel ** Wynndel, British Columbia, CANADA ** EMAIL: bvdpoel at kootenay.com WWW: http://www.kootenay.com/~bvdpoel From aldo Wed Oct 2 18:46:45 2002 From: aldo (Aldo Cortesi) Date: Thu, 3 Oct 2002 08:46:45 +1000 Subject: Ctrl-C handler, how to override? In-Reply-To: References: Message-ID: <20021002224645.GA4976@nullcube.com> Thus spake Bruce Edge (edgebruce at yahoo.com): > How the @#$!$ do override the SIGINT handler? > > I can create handlers for other signals, but not for SIGINT: > > >>> getsignal(SIGINT) > > >>> def handler(signum, frame): > ... print "got signal", signum > >>> signal(SIGINT, handler) > 1 > >>> getsignal(SIGINT) > > > ...Looks OK so far, but Ctrl-C's still call the default handler: > > >>> > KeyboardInterrupt > >>> > KeyboardInterrupt > http://mail.python.org/mailman/listinfo/python-list Bruce, What you're seeing is a side-effect of running your code in the interactive interpreter. Your code works fine when run from a file. Cheers, Aldo -- Aldo Cortesi aldo at nullcube.com http://www.nullcube.com From lu_gio at hotmail.com Fri Oct 4 20:14:06 2002 From: lu_gio at hotmail.com (Max) Date: Sat, 05 Oct 2002 00:14:06 GMT Subject: Python CSV Message-ID: Hi! I try to get the python source code. I've installed wincvs and followed the instruction but... Python 2.2.1 (#34, Apr 15 2002, 09:51:39) [MSC 32 bit (Intel)] on win32 CVSROOT: d:pserver:anonymous at cvs.python.sourceforge.net:/cvsroot/python (password authentication) cvs login Logging in to :pserver:d at cvs.python.sourceforge.net:2401/cvsroot/python Error connecting to host cvs.python.sourceforge.net: Host sconosciuto. cvs [login aborted]: Connection to server failed *****CVS exited normally with code 1***** ---- With another pc I don't get any connection aborted or connection error, it write "CSV exited normally with code 0". There isn't a simple way to get last distribution source - a good, old,simple link to a .zip file? Thanks From opsys at voodooland.net Tue Oct 8 13:05:14 2002 From: opsys at voodooland.net (Chris Watson) Date: Tue, 8 Oct 2002 12:05:14 -0500 Subject: [OT} How to un-GPL parts of a GPL'd module. In-Reply-To: Message-ID: <1CA862FC-DAE0-11D6-B35A-0003937B4040@voodooland.net> On Tuesday, October 8, 2002, at 11:20 AM, sismex01 at hebmex.com wrote: > > Well, there *is* the problem of corporations trying to take > technology which isn't theirs and gaining zillions off it, > and then burying said technology so other's won't benefit > from it. It's happened with plenty of BSD technology which > ended up in NT, and then became patented by M$ (IIRC). Wrong. I don't know how this myth got started but linux people just love to cite this. There is *very little* BSD code in any windows products. What the real story is... Microshaft bought out a small company (typical MS action) that had network tools based on standard BSD utilities. MS simply inherited them as part of the buyout. And as far as the "omg! corporate monster X stole my code!!!! and made a fortune on it!!!" thats just the most ridiculous thing I have ever heard spewed. Look a company cant make money using a block of code that is under the BSDL just by making that exact block a binary. The only way they can make money is to take that block and *add value to it*. Which means bolting on all the cool/hard crap that open source people never want to do. Because it is not fun. I get tired of hearing how someone stole BSD code. BSD code is *free*. If you don't want people to USE your code then just don't give it out. Period. But don't pull a GPL strong arm tactic by trying to force people into your socialist view of life. The GPL is just as evil and bad as MS except on the other end of the spectrum. > Then you see plenty of other technologies which *were* public > domain, or at least didn't have any heavy licensing (or rather, > *formal* licensing) behind them, and then they were copied > by some opportunist and subsequently patented, resulting in > the net loss of said tech. Take a look at the IRC robot > fiasco going on. That is a totally different issue. And has nothing to do with either licensing scheme. Your beef here is with the completely stupid/retarded/jack ass US patent system. The whole damn patent office should be abolished. It is a blatant train wreck. Pure and simple. Write your congressman/woman. > So there actually *is* a need for the GPL, to help keep things > fair; it's no fun to be inventing stuff and then setting it free, > if there's others with no notion of playing fairly taking all, > making zillions, and shutting others out. There's countless > evidence of it going on every day, you just need take a look > and read around. To destroy IP, kill capitalism, and put programmers out or work isn't quite what id call fair. Write GPL app ??? PROFIT!!! Realize no one is buying what you are giving out for free. File chapter 11. Again the whole GNU/FSF/GPL gang is as evil as MS, it's just the other side of the coin. *waits for the ensuing gang of GPL thugs to attack* Chris -- "I feel..thin. Sort of stretched, like... butter scraped over too much bread. I need a holiday a very long holiday." From hwlgw at hotmail.com Tue Oct 15 11:44:14 2002 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 15 Oct 2002 08:44:14 -0700 Subject: realtime design References: <013goa.m8c.ln@boundary.tundraware.com> Message-ID: > [Tim Daneliuk] > ... > There is an inherent problem with the term "realtime" if it is > not further qualified. > ... > 1) "Hard" realtime - ... > ... > 2) "Soft" realtime - ... > ... I was looking for a primitive that can be used for modeling *hard* realtime, but without the ``service completed'' requirement. ``I cannot do this in time'' is also acceptable at timeout. The point is that the caller should be able to carry on. > ... > http://www.tundraware.com/Technology/Bullet/ > ... And you have more interesting stuff there. > HOWEVER, you said you wanted to "prototype" such a system. > Depending on how functional your prototype needs to be, Python > may well be a good choice. It is relatively easy and quite > appropriate to *model* realtime systems, hard and soft, in other > languages. Well as you can see in this thread I failed using Python! Maybe my requirements are too strict. For modeling ``ordinary'' function calls a combination of Queue.Queue and threading.Thread.join(timeout=...) can be used. But if the function call winds up doing cpu intensive stuff (for example pow()) at the C level then the Python threading timeout fails, so the caller can not carry on in time. And *that* is essential for the realtime modeling primitive. Performance is no issue, the simulation is allowed to be very slow, as long as it does implement the primitive correctly. If I have more time I am going to look into doing this with processes instead of threads. Thank you for your comments! ''' QOTD, about modeling Recession is when your neighbor loses his job. Depression is when you lose your job. These economic downturns are very difficult to predict, but sophisticated econometric modeling houses like Data Resources and Chase Econometrics have successfully predicted 14 of the last 3 recessions. ''' From bokr at oz.net Thu Oct 17 18:25:08 2002 From: bokr at oz.net (Bengt Richter) Date: 17 Oct 2002 22:25:08 GMT Subject: Most efficient method to search text? References: Message-ID: On Thu, 17 Oct 2002 11:14:09 GMT, Michael Hudson wrote: >Tim Peters writes: > >> Especially for purposes of building lexers, it might be useful if the re >> package could recognize when a DFA approach was sufficient and practical, >> and switch to a different scheme entirely then. Or it might not. Build >> code to try it both ways, and let us know how it turns out ... > >Indeed, my code canes re when the wordlist gets long. Here's some If this is easy to add to your test harness, I'd be interested to see what this search does in comparison, with the longer word lists (it's probably faster than has_word.py that I posted elsewhere, depending on relative lengths of word lists and strings, and internal vs external looping and allocation. ==================== # __PyPAN_Py word_is_in.py -- Check if at least one word in list is in string. def word_is_in( wordlist, # ['word', 'word2', 'etc'] aString, # string to find words in trans = ''.join([c.isalnum() and c or ' ' for c in map(chr,range(256))]) ): """ Search for any of a list of words in a string and return 1 if any found, else 0. """ word_dict = dict(zip(wordlist,wordlist)) for w in aString.translate(trans).split(): if w in word_dict: return 1 return 0 # __PyPAN__ ==================== The trans table treats anything non-alphanumeric as word delimiter. You could mess with that. You could write a fast C function to take advantage of not having actually to do the translate and split, but instead just finding the successive tokens and checking for them in the word_dict. For searching large files, this would help with memory use as well as speed. BTW, a split method for strings that would do a pre-translate could be useful. You could specify by way of a character filter function like isalnum, which would be used like for the trans argument above, but a builtin str.splitcs(character_set_filter) would recognize references to its own standard methods (e.g., isalnum) and use cached info instead of building it each time. Alternatively, a string could be assumed to imply '['+the_string+']+' as a findall regex. >numbers (do_comp(n) builds a list of n words composed of ten random >ascii characters and searches the Python standard library for them >using first my code, then a re-based approach): > >>>> import robin >>>> robin.do_comp(10) >2.275832057 >0.317215919495 >>>> robin.do_comp(100) >2.2694439888 >0.980538964272 >>>> robin.do_comp(1000) >2.36677598953 >8.53031408787 >>>> robin.do_comp(2000) >2.34253299236 >16.9222760201 > >So roughly linear behaviour from re, n-independent behaviour from my >code. Isn't it nice when things do what you expect? > >On the other hand, the "compiler" code I posted yesterday consumes >vast gobs of memory -- trying to compile a 10000 long list of random >words got the OOM killer into action. A version using lists seems >slightly better in this respect, though slower in execution. > Regards, Bengt Richter From aahz at pythoncraft.com Thu Oct 10 12:25:14 2002 From: aahz at pythoncraft.com (Aahz) Date: 10 Oct 2002 12:25:14 -0400 Subject: time and thread modules. References: Message-ID: In article , wrote: > >Does invoking time.sleep() automagically allow a thread switch in >Python? Depends. time.sleep() with a non-zero value causes the current thread to block because time.sleep() uses select() to do its dirty work -- but that doesn't mean any other thread will run. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From wlfraed at ix.netcom.com Thu Oct 31 15:44:41 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Thu, 31 Oct 2002 12:44:41 -0800 Subject: MySQL + Python. References: <3DC1783F.5000003@web.de> Message-ID: Ingo Linkweiler fed this fish to the penguins on Thursday 31 October 2002 10:36 am: > Is it possible to use MySQL with Python, if I do not know the > platform? Do you know any "pure" Python-Modules to use MySQL ? > Does the provider have MySQLdb module installed for Python? -- -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < From changeme at changeme Thu Oct 10 10:15:45 2002 From: changeme at changeme (change) Date: Thu, 10 Oct 2002 10:15:45 -0400 Subject: Building Python 2.2.1 for HP Tru64 UNIX V4.0F References: Message-ID: Phoebe_1, Thanks very much. Downloading the newer C compiler did address this issue. I can now compile with no problems. Phoebe 1 wrote in message ... > >Narendra, >Did you hack the makefile to add the options? Then it will *not* work. >I think Martin had suggested CC trick, I usually hack the configure.ac to >set the flags since I have lots >of different OS/Archs to support. >Did you do this: >$ make distclean >$ CC="cc -std1 -msg_disable longlongtype" >$ export CC >$ ./configure --with-pydebug >If you did not run configure again (with distclean) it will *not* work. >Anyways I am using DEC/Compaq/HP C compiler V6.2 > . I have it working with >Tru64 Unix 4.0E, 5.0A, 5.1,5.1A (yes, I have all those versions). I don;t >have a 4.0F system, >maybe it is specific to that OS version. Or it could be your C compiler >version, try to download >the new compiler from the ftp site, there were some issuses with the early >version of 6.0, I have >the 6.2 and 6.3 compilers and I have had no problems. >Cheers > From phoebe_1 at att.net.remove_me Tue Oct 15 12:51:11 2002 From: phoebe_1 at att.net.remove_me (Holden Caulfield) Date: Tue, 15 Oct 2002 16:51:11 GMT Subject: __slots__ questions (v2.2.2) Message-ID: <3IXq9.23106$ue4.1549940@bgtnsc04-news.ops.worldnet.att.net> Greetings, 1) It looks the the __slots__ bug that people have reported earlier, where a 'slotted' variable starting with '__' (double underscore is name mangled is still not fixed in v2.2.2. Are there any plans to fix this? e.g class X(object): __slots__ = [ '__x'] def __init__(self): self.__x = None The above craps out with the Attribute error '_X__x' not found. 2) Also, in python 2.2.2 as in 2.2.1, a variable in the '__slots__' *must* still be initialized 'before use'. I do not whether it is supposed to work that way. If it is, then it seem very counter-intuitive (well, if you are in the new features bandwagon). To demonstrate: class X(object): __slots__ = ['_x'] xobj = X() print xobj._x the above gives attribute error. (in v2.2.1 and v2.2.2). I was expecting that if you use '__slots__', all the 'slotted' variables would get 'instantiated' when an instance is created and default to None. But now, I have to explicitly initialize by providing a __init__ method and setting '_x' to something. To put it another way, I cannot 'get' a slotted variable *unless* it has been "set" first . Currently, I am using the 'metaclass' technique to alleviate the above problem. But I would rather have python support it. Thanks From tismer at tismer.com Wed Oct 9 21:44:31 2002 From: tismer at tismer.com (Christian Tismer) Date: Wed, 09 Oct 2002 18:44:31 -0700 Subject: PEP239 (Rational Numbers) Reference Implementation and new issues References: <20021002221421.GA29958@thyrsus.com> <3D9B7DB5.4000702@tismer.com> <005f01c26a8c$fe2fb3e0$ba01010a@local> <3DA4C654.5060806@tismer.com> <00b101c26ff8$67709840$ba01010a@local> Message-ID: <3DA4DB7F.1010203@tismer.com> Chris Gonnerman wrote: [snipped good stuff again, including stuff snipped] >>Naa, this is slightly different. >>I don't think al too many people asked for an integer >>in the first place when they wrote >> >> 1/3 > > > Ahhh... > > you are thinking, "1/3 as a literal" and I am seeing it as > an EXPRESSION. So to you, this: > > 1/3 > > is not the same as this: > > n = 1 > m = 3 > > n/m > > Or have I misunderstood? Because if you give me a rational > for the second option I'll be royally ticked off. For the > first option, giving me a rational serves me right. No, sorry, I didn't distinguish literal form expression. The 1/3r thingie appeared on python-dev, and I perceived it as a modifier for the whole expression. Probably wrong, and you are right with 3r = rational(3,1) There had been proposals like 1:3, [1:3] and so on, and I was thinking of syntactic sugar for the whole expression. ...bigger snip... >>Now, returning a true fraction instead sounds exciting. >>Having fractions in the language is exciting as well, >>after I had them in Mathematica for long years. > > > ... let's not get too excited here ... > > >>Finally, if I had to choose, I would either stick with >>the old truncation, or use rationals. >>Rationals would be welcome, even if there were just >>an extension module. > > > Now that idea I can get behind. I'd never use them, but > (IMHO) you can never have too many tools in the box. > > What I was proposing wasn't actually > > 1/3R > > as a rational literal; THIS is a rational literal: > > 3R Now it is clear. > and since math operations involving a rational and an int > or float would "promote" the int or float to rational, this: > > 1/3R > > would return a rational one-third value. > > In other words, the R suffix would make a literal integer > "n" into a rational of the form "n/1". That's good anyway, and not related to a decision what 1/3 should be. Let's see what comes... ciao - chris[2] -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 pager +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From max at alcyone.com Sun Oct 20 21:28:30 2002 From: max at alcyone.com (Erik Max Francis) Date: Sun, 20 Oct 2002 18:28:30 -0700 Subject: How do I invoke IE browser from Python on Mac OS X? References: Message-ID: <3DB3583E.EF7B9750@alcyone.com> Paul Jackson wrote: > open - open files > > SYNOPSIS > > open [ -a app ] [ -o ] [ -p ] filename ... I presume this is just a command that can be executed from the shell. > You can specify one or more file names (or pathnames), > which are interpreted relative to the Shell or Terminal > window's current working directory. For example, the fol- > lowing command would open all WriteNow files in the cur- > rent working directory: > > open *.wn ... if so, this is a curious comment in the man page, since filename globbing is done by the shell, not the program. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ No man who needs a monument ever ought to have one. \__/ Nathaniel Hawthorne Rules for Buh / http://www.alcyone.com/max/projects/cards/buh.html The official rules to the betting card game, Buh. From shalehperry at attbi.com Wed Oct 16 15:08:34 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Wed, 16 Oct 2002 12:08:34 -0700 Subject: new-style classes VS classic-classes In-Reply-To: References: Message-ID: <200210161208.34840.shalehperry@attbi.com> On Wednesday 16 October 2002 11:58, Aahz wrote: > > >2. is there any reason not to use the new-style classes ( except > >backwards-compatibility)? > > You can't use new-style classes for exceptions. Other than that, not > much reason. note for clarity Aahz said you can not make an exception class that derives from object. new-style classes can still use exceptions. From ajm_NO_REPLY_ at zanthan.com Wed Oct 9 20:30:16 2002 From: ajm_NO_REPLY_ at zanthan.com (Alex Moffat) Date: Thu, 10 Oct 2002 00:30:16 GMT Subject: How to restrict settable attributes for an object? References: <4f49d232.0210090736.a0fdc11@posting.google.com> Message-ID: Laotseu wrote: > Alex Moffat wrote in message news:... > >>What I want to do is restrict the attributes that can be set on an >>object. I want to do this for "data objects" so that I can catch typing >>errors in my program and more easily manage sql interfacing. My current >>"solution" is pasted below. Is there a better technique that I should >>use. I'm new to python so I'd like to try and follow the established >>idioms and patterns where they exist. >> > > [snip code] > > Depending on the version of python you're using, you could use slots. > They provide the same functionnality as the one you implemented. > > laotseu Thanks, that's exactly what I'm looking for. From marklists at mceahern.com Tue Oct 22 08:14:08 2002 From: marklists at mceahern.com (Mark McEahern) Date: Tue, 22 Oct 2002 07:14:08 -0500 Subject: strip not well formed html tags... In-Reply-To: Message-ID: > i've seen many post about how to strip html tags from a string, > some use sgmllib, others regular expressions... i 'd the following > trouble i would like to strip html (or even xml) tags but i had > to work on incomplete string so they could be not well formed - what > should i use ? regexp ? sgmllib with many exceptions handling ? 1. Try mxTidy. 2. Consider providing an example of the data you're talking about. Cheers, // mark - From pinard at iro.umontreal.ca Mon Oct 21 16:27:20 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: Mon, 21 Oct 2002 16:27:20 -0400 Subject: Parsing SGML document in Python program In-Reply-To: (ishambat@aol.com's message of "21 Oct 2002 12:41:27 -0700") References: Message-ID: [Ilya Shambat] > I have looked at the documentation for nsgmls, and I found it rather > inadequate. This was a while ago, but _if_ I remember well, the documentation was very clear when I needed it. The trick is to read slowly and carefully! :-) -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From vincent_delft at yahoo.com Wed Oct 2 16:14:25 2002 From: vincent_delft at yahoo.com (vincent delft) Date: 2 Oct 2002 13:14:25 -0700 Subject: Install rpm : irpm Message-ID: <5c184570.0210021214.643564c1@posting.google.com> I've just released a project to simplify the RPM installation process. irpm will install automatically all the dependencies. And based on python ... the link is http://sourceforge.net/projects/irpm (cvs, forum and mailing list available) I'm looking for some help (web, doc, tests, ...) Thanks for your collaboration From martin at v.loewis.de Wed Oct 16 22:07:43 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 17 Oct 2002 04:07:43 +0200 Subject: ssh on solaris 8 References: <1936886.1034798480@dbforums.com> Message-ID: Cypher7 writes: > I'm currently trying to make a daemon that will monitor a process on one > of the servers we have. If the process hoses up a ssh connection to a > remote server has to be astablished and a script run. The connection > has to be secure and it has to be done in python. I recommend to use os.system to invoke /usr/local/bin/ssh (or whereever your ssh binary lives). Regards, Martin From tismer at tismer.com Thu Oct 24 09:21:59 2002 From: tismer at tismer.com (Christian Tismer) Date: Thu, 24 Oct 2002 06:21:59 -0700 Subject: Is "the Python Standard library" book worth the money? References: <200210240837.g9O8bAl15053@mail2.infinito.it> Message-ID: <3DB7F3F7.2010602@tismer.com> Alessandro Bottoni wrote: > I have seen that there is a book on the Python standard library (By Fredrick > Lundh, published by O'Reilly). > > Do you think it can be a useful reference book to keep on the desk? > Is it something more than a printed copy of the STDLIB HTML documentation > that came with the Python package? > Does it contains any information that is not already available on the Python > web sites? > Does it conatins any example of use of the described modules? I can only recommend it. It contains examples which are ready to use, and it opens the library to you in a way you would hardly be able to do on your own. If it wouldn't be so, I would not have translated this book into German, togther with Dinu Gherman. ciao - chris -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 pager +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From fperez528 at yahoo.com Sat Oct 12 16:31:08 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Sat, 12 Oct 2002 14:31:08 -0600 Subject: Buffering control in python? Message-ID: I know that using -u will turn buffering off for everything in python. But is there a good reason for the lack of a way to turn buffering off from _inside_ a script? It's a bit nonsensical --at least from a user's perspective-- that something which can be done at the command line so easily isn't available inside the language itself. I don't want to use #!/usr/bin/python -u because of its portability problems. In Perl each stream can be set to unbuffered via a simple STDOUT->autoflush(1); Any reason why something like sys.stdout.autoflush(1) wouldn't be a good thing? I hate having to put sys.stdout.flush() calls all over the place when I need unbuffered output, when a stateful approach would be far cleaner. It would be also better than a blanket '-u' switch, since one could turn buffering off only for those streams that need it, and only in the places where it's needed. Any comments from the cognoscenti? Thanks, f. From fitzgerald at inetmi.com Tue Oct 15 22:44:20 2002 From: fitzgerald at inetmi.com (Will Fitzgerald) Date: Wed, 16 Oct 2002 02:44:20 GMT Subject: Newbie: Inheritance of accessors References: Message-ID: <8o4r9.4730$F53.3716625@newssvr28.news.prodigy.com> Mark McEahern wrote: >[Will Fitzgerald] > > >>I'm curious about accessors being inherited from parent classes. Given >>the code that follows, and I create an instance: >> >> e=S() >> >>How do I access the inherited default 'x' in e (inherited from R)? >> >> > >In the most natural way imaginable, of course: > > e.x = 1 > print e.x > >etc. > >// m >- > > > > Thank you very much for your reply. I guess I should have been clearer. I meant reading the inherited *default* value from the parent class. Given the same code (repeated below), I see: >>> q = R() >>> print q.x 0 >>> e = S() >>> print e.x Traceback (most recent call last): File "", line 1, in ? File "", line 5, in getx AttributeError: 'S' object has no attribute '_R__x' >>> Can e *not* inherit to the default value? Or is there a way to call the __init__ method for R's superclass (so that 'x' in initialized?). WF From mhammond at skippinet.com.au Thu Oct 31 18:43:45 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Thu, 31 Oct 2002 23:43:45 GMT Subject: "Universal Gateway" (Was: Python, win32, COM, IDispatch, I client query) References: Message-ID: Paul Moore wrote: > Unfortunately, the universal gateway stuff is hopelessly > underdocumented (a couple of examples which don't even seem to work, > plus the sources :-() Too true. However, as the generated warning says, I was worried that stuff would change too much as the problem became clearer. Fortunately, I'm now pretty happy with it. In the lastest win32all versions you will find an Outlook Addin sample. This uses the Universal Gateway code to implement a reasonable interface. I have also recently done a little work to make implementing *every* interface in a type library must simpler, which will be very useful when Python can actually generate TLB files from your source, but even now is useful if you don't mind hand-writing the IDL file you want your Python components to implement. So it seems there will be 2 universal strategies: * If you want to implement one or 2 interfaces (eg, the Outlook addin, where you only need to implement a handful of interfaces out of the hundreds available) - in this case you stick with the "RegisterInterfaces()" type calls in the existing examples. * You want to implement *all* interfaces in a TLB. In this case you add a couple of extra annotations to your server class, and magic happens So I am confident that the existing setup is reasonable (well, as reasonable as sticking GUIDs in your source ever can be) If you want to play with Universal, get win32all 149 or 150, as it has a number of univeral related bugs fixed (and indeed the Outlook plugin will not work without it). The plugin is in win32com\demos. Mark. From Gerson.Kurz at t-online.de Thu Oct 31 14:39:36 2002 From: Gerson.Kurz at t-online.de (Gerson Kurz) Date: Thu, 31 Oct 2002 20:39:36 +0100 Subject: AW: The rules of reference In-Reply-To: <20021031192522.GD20810@unpythonic.net> Message-ID: Jeff Epler wrote: > 60 was assigned to __main__.num, but a.num was only set once (to 42) OK, I see that now. But, being of the adventurous sort (even though I probably can't spell that word) as I am, I now try this: -------------------- num = 42 def print_num(): global num print "a.print_num() called, num is %d" % num if __name__ == "__main__": import b # remove everything from __main__, use stuff from a instead. del print_num del num try: print num except: print "ok, num does not exist any more." from a import * print_num() # this proves that num can be referenced print "in __main__ num is now %d" % num num = 60 print "in __main__ num is now %d" % num print_num() b.do_stuff() -------------------- My reasoning: I remove any reference to __main__a, and test it. Then I reimport a. That should work, right? ok, num does not exist any more. a.print_num() called, num is 42 in __main__ num is now 42 in __main__ num is now 60 a.print_num() called, num is 42 b.do_stuff() called a.print_num() called, num is 42 hmmmmmmm. From sholden at holdenweb.com Mon Oct 7 09:06:03 2002 From: sholden at holdenweb.com (Steve Holden) Date: Mon, 7 Oct 2002 09:06:03 -0400 Subject: exec(threads) References: <200210071441.49984.scjuonline@web.de> Message-ID: <04a901c26e02$4b686d00$6300000a@holdenweb.com> [posted and mailed] JS wrote ... > >Threads are created using the underlying mechanism of the host OS, which is > > why you see processes in Linux but not on the other two platforms. > > What exactly is used in the case of Linux? > > > If your program works, I wouldn't worry too much about the representation > > in theprocess list, since that's just an artefact of the OS's thread > > implementation. > > Thats the problem. I have code, thats not proberly running. And its writer > says, that the problem lies within Linux threads. > Now I try to figure out, where to start searching ;-) So when you said "no processes are created" you meant "I don't get threads"? I'm not sure what the problem is yet, so can't yet do much to help you solve it! Although you posted the code you didn't say how it failed to run on which platforms. Your original post said you saw five new processes created on Linux, and you then imply that the problem lies with Linux. Is this actually the case or am I misunderstanding? I think the better fix would be to make sure the Python is correctly structured. I haven't heard any users complaining that the implementations cause problems. Have you tried taking a look at Aahz' web site threads tutorial? Specifically, I notice you don't use thread.join() to wait for all the threads you've started to finish, but instead read a line of input. That might or might not cause problems. As always, the more specific your problem description is the better the help you will get. Let's keep this on the newsgroup (that way you'll get help from many rather than just me). Just Cc: to python-list at python.org for emails. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- From thomas.heller at ion-tof.com Mon Oct 21 13:11:09 2002 From: thomas.heller at ion-tof.com (Thomas Heller) Date: 21 Oct 2002 19:11:09 +0200 Subject: rename running windows exe? References: <2nWs9.47700$La5.140792@rwcrnsc52.ops.asp.att.net> Message-ID: <65vvpviq.fsf@ion-tof.com> Pete Shinners writes: > this falls heavily into a straight win32 question, but i'm trying to > accomplish this under python, so i'm hoping there's an answer. > > i'm trying to write a simple script that will help me manage distribution > of files on multiple platforms. i need a way to rename or move or delete an > executable or dll that is running. perhaps it's a thing that windows will > simply not allow. > No, it it not allowed at all. > if not, is there a way i can find the offending processes and offer to send > them a QUIT message? some simple dialog, "you need to close the following > programs: notepad, shall i try to close them for you?" This may open a can of worms: the program may have no windows open, so the user cannot interact directly with it, the user may not have sufficient access rights to do this, and so on. The common technique AFAIK is describes by Jeff Richter in this article: http://www.microsoft.com/msj/defaulttop.asp?page=/msj/archive/sf9c.htm If this is not a persistent URL, you can probably find it by googling for ReplaceFileOnReboot. This technique is also used in the bdist_wininst uninstaller, because it also allows a currently runing exe to remove itself. HTH, Thomas From gerhard.haering at gmx.de Wed Oct 9 00:11:56 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 9 Oct 2002 04:11:56 GMT Subject: apache+ python ? References: Message-ID: eugene kim wrote in comp.lang.python: > thank you for quick answer.. > > well what i'll be doing is > db access, file uploading, xml generate/parsing I'd definitely go for a persistent AppServer here, as it's quite costly to repeatedly import the XML modules and open database connections. I've made good experiences with the WebWare application server (http://webware.sf.net/). It can be connected to Apache using mod_webkit (a WebWare specific adapter), mod_python and several CGI solutions. > speed doesn't matter .. but if using mod_python is not too much > complicated,(it all depends how fast i can learn & use.. well that's > the purpose of using python, isn't it?) i want to try it. mod_python is great, but doesn't give you a web development framework (with session management, authentication, etc.) yet. You'll have to find add-ons for mod_python for these purposes (or write it yourself). A web application framework will offer these features (and more, like templating) to you. > i think i 've succeeded installing mod_python.. > i have question though, maybe i have to ask this to apache forum, > what's 'PythonHandler' in httpd.conf? The best place to ask this kind of questions is the mod_python mailing list. -- Gerhard From see_reply_address at something.invalid Thu Oct 3 21:42:01 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Fri, 04 Oct 2002 13:42:01 +1200 Subject: A challenge from the Mensa Puzzle Calendar References: Message-ID: <3D9CF1E9.9030600@something.invalid> Marco Mariani wrote: > > Why use an algorithm when you've got a gigahertz CPU and a list > comprehension? That would make a great Python quote! Does anyone keep a database of such things? -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From maxm at mxm.dk Wed Oct 9 05:36:17 2002 From: maxm at mxm.dk (Max M) Date: Wed, 09 Oct 2002 11:36:17 +0200 Subject: Generating a spacer gif on the fly Message-ID: Hi I am writing an app where it would be practical to have a function that generates a spacer gif in a given color:: def spacer(color=''): "Generates a 1x1 pixel gif with color, no color means transparent" I have googled around for a solution, but didn't really find what I was looking for. There are many libraries which does this, but I find this to be overkille due to deployment issues. I have also found the GIF spec, which I will use to do it with. It will just take sooo long. My guess is that it can be done by very simple means if you only know how. And I imagine that many has done something similar and has working code in a dungeon somewhere. Does anybody care to share? regards Max M > > > From robin at reportlab.com Mon Oct 7 04:07:53 2002 From: robin at reportlab.com (Robin Becker) Date: Mon, 7 Oct 2002 09:07:53 +0100 Subject: [Python-Dev] Fw: MRO 2.2 vs 2.3 In-Reply-To: <200210062027.g96KRwh28684@pcp02138704pcs.reston01.va.comcast.net> References: <038401c26d70$52fd6c60$6d94fea9@newmexico> <200210062027.g96KRwh28684@pcp02138704pcs.reston01.va.comcast.net> Message-ID: In message <200210062027.g96KRwh28684 at pcp02138704pcs.reston01.va.comcast .net>, Guido van Rossum writes ...... > >If it's any consolation to you, you'd have to write a program with a >pretty, um, "wild and wonderful" inheritance lattice before this would >ever bite you. It's also the case the the difference between the >current algorithm and C3 is pretty small; the biggest difference is >that in some extreme cases, when you write Its precisely this small set of differences that make this seem more like a bugfix than a new improved feature. I got the impression from lurking on the discussion that this new behaviour was intended and not achieved. Personally I found the reasoning about why one should do the extended precedence thing extremely tenuous as it seems to be based on assertions about programmer expectation. It's hard to believe that many can do high order graph analysis by inspection of the terminal node order. Does this new thing preserve current behaviours when adding more subclasses ie B(A0,A1,...,Ak) C(A0,A1,....Ak,Ak+1) is it possible to say easily what happens? > > class C(A, B): ... > >B may precede A in C.__mro__ with the 2.2 algorithm, but not with the >C3 algorithm. (The paper about C3 referenced by descrintro.html has >some examples; in all the examples that I've verified, the 2.2 >algorithm behaves the same as L*LOOPS in the paper, even though >Samuele has constructed an example where L*LOOPS is different again: >this is due to the fact that L*LOOPS merges all lists simultaneously, >while the "conservative merge" algorithm in 2.2 can only merge two >lists at a time. > >--Guido van Rossum (home page: http://www.python.org/~guido/) > -- Robin Becker From SBrunning at trisystems.co.uk Thu Oct 3 04:35:56 2002 From: SBrunning at trisystems.co.uk (Simon Brunning) Date: Thu, 3 Oct 2002 09:35:56 +0100 Subject: migrate from java to python. How? Message-ID: <31575A892FF6D1118F5800600846864DCBD8E7@intrepid> > From: Alex Martelli [SMTP:aleax at aleax.it] > 2cents wrote: > > Is there any kind of J2EE, JMS or any other Java Technologies in Python? > > You can code in the Python language and access any Java technology you > want by using the Jython implementation of Python -- see www.jython.org. And see for a couple of simple examples. Cheers, Simon Brunning TriSystems Ltd. sbrunning at trisystems.co.uk ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From pj at engr.sgi.com Mon Oct 21 16:04:06 2002 From: pj at engr.sgi.com (Paul Jackson) Date: 21 Oct 2002 20:04:06 GMT Subject: How do I invoke IE browser from Python on Mac OS X? References: <3DB43104.2030206@shaw.ca> Message-ID: Given Piet's experience on another subtread of this this query, and given the "logic" of this open command, I'd wager an ugly penny that: 1) Piet was running an older OS X, and 2) The ability of 'open' to bring up the browser on URLs was added somewhat later on, after the original 'open' was coded. -- -- I won't rest till it's the best ... Programmer, Linux Scalability Paul Jackson 1.650.933.1373 From aremovethiscanton at adamsremovethis-blake.com Thu Oct 17 20:59:36 2002 From: aremovethiscanton at adamsremovethis-blake.com (Adams-Blake Co.) Date: Thu, 17 Oct 2002 17:59:36 -0700 Subject: Report writer for Python? References: <3da7b63b@monitor.lanset.com> <046uqugvehkpadjfm7515vt85jr5v6k9cj@4ax.com> Message-ID: <3daf5dd9@monitor.lanset.com> Andy Robinson wrote: > On Fri, 11 Oct 2002 22:39:15 -0700, "Adams-Blake Co." > wrote: > >>Besides reportlab.com, what other reporting tools are availabe? I'm >>especially interested in a GUI-like report writer like Crystal that can >>generate printed reports. I want to do an application in Python but it has >>some 40 reports. >> >>There are some tools for Java, so I thought there must be some for >>Python.... but I have not found any via Google searching >> >>Thanks, >> >>Al >> > > I do not know of any GUI report creation tools in Python. > If they did, I'd hope they'd be front ends for us, as making PDF is > a better cross-platform solution than driving a printer. I'd LOVE > to write one in wxPython but haven't the time.... > > But let me point one one experience which helped drive me to > start ReportLab inthe first place. I worked on a project using a tool > like Crystal, it too had about 40 reports. 6 developers tried to make > all the documents consistent with each other and "nearly got there". > At one point the marketing people changed the company's phone number, > so someone had to open up all 40 and change them. They all had > subtly different visual spacing, row heights etc which took ages > to track down. Not to mention performance problems trying to > do 10,000 customer statements on a Sunday afternoon. > > Visual tools usually don't allow reuse, and have serious limits on > what you can do. Controlling it all in Python gives total > flexibility. > > If you're a programmer, using our code you can create a family of > 'drawable objects', and reuse them. You can share and maintain > styles. You'll get a long way in 2 days, and will reach a point > where most of those reports only need slightly different queries > and definitions. With our approach, each extra document gets > cheaper and cheaper. With tools like Crystal, the first one is cheap > but each extra one probably costs the same forever. > > If-there's-a-better-reporting-solution-for-Python-than-us-I-want > it-caught-and-shot-ly-yours, > > Andy Robinson > CEO/Chief Architect, ReportLab Inc. > > p.s you can outsource the project to us if it helps ;-) I read the docs to ReportLab and I was really impressed by what it could do. The problem is that it is really LOW level.... down to the painting of the canvas. Also, the docs were written for an experienced Python programmer.... which I'm not. And I was not entirely clear exactly how I would do the traditional "sort, extract, report" function against a table.... with headers, footers, and group breaks with sub totals. This is the kind of thing that Crystal does well... and while I really hate Crystal I have to admit that it works OK. What I'm looing at is moving to Jython. This gives me the advantages of Python along with the Java library.... and I found some report generators (Datavision, for example) that might get me where I want to go. When you're a really small developme team you just don't have the time to layout and program 40 or 50 complex reports at the "bit" level. A code generator or some kind of report writer is the way to go. Oh, and yes, you are absolutely right about sending all reports to PDF and letting Adobe deal with the printer drivers. That's exactly what I plan to do. I'm going to continue to study the ReportLab product and maybe a light will go off and I can understand how to do what I need to do..... plain old text oriented business reports.... the bread and butter of Crystal. Thanks, Al Canton Adams-Blake Company, Inc. www.adams-blake.com From gerhard.haering at gmx.de Thu Oct 3 23:15:51 2002 From: gerhard.haering at gmx.de (Gerhard Haering) Date: Fri, 4 Oct 2002 05:15:51 +0200 Subject: A challenge from the Mensa Puzzle Calendar In-Reply-To: <15773.1547.608303.792441@localhost.localdomain> References: <3D9CF1E9.9030600@something.invalid> <15773.1547.608303.792441@localhost.localdomain> Message-ID: <20021004031551.GA90735@gargamel.ghaering.test> * Skip Montanaro [2002-10-03 22:07 -0500]: > Greg> Marco Mariani wrote: > >> Why use an algorithm when you've got a gigahertz CPU and a list > >> comprehension? > > Greg> That would make a great Python quote! Does anyone keep a database > Greg> of such things? > > Yes, Andrew Kuchling does, though I don't know where it lives off-hand. http://www.amk.ca/quotations/python-quotes/ A very good read :-) -- Gerhard From jepler at unpythonic.net Wed Oct 16 10:52:06 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 16 Oct 2002 09:52:06 -0500 Subject: Most efficient method to search text? In-Reply-To: References: <886c5e4b.0210151635.123359bb@posting.google.com> Message-ID: <20021016145205.GB9288@unpythonic.net> On Wed, Oct 16, 2002 at 01:35:09PM +0000, Michael Hudson wrote: > Here's a way to quickly (I hope! Haven't done any benchmarks) tell if > one of a bunch of words is contained in a chunk of text, assuming the > words are known beforehand [...] Is there any reason to suppose that this is more efficient than using re.compile("|".join(re.escape(words))).match? I haven't looked at the implementation of sre, but it should be able to generate a simple DFA for this RE and execute something very much like your 'match' function, but at C speeds. Having one dict lookup per character scanned seems like a pretty huge chunk of overhead. Jeff From BPettersen at NAREX.com Thu Oct 31 17:36:20 2002 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Thu, 31 Oct 2002 15:36:20 -0700 Subject: What the heck has happened to PythonWin??? Message-ID: <60FB8BB7F0EFC7409B75EEEC13E201920177442F@admin56.narex.com> > From: Mark Hammond [mailto:mhammond at skippinet.com.au] > [snip] > Well, not mine . As Skip posted, the general project is > spambayes.sourceforge.net. I've put together a cute outlook > addin. The > bayesian filter, plus Outlooks integration facilities is providing an > *incredibly* effective Spam filter with very tight integration and > incremental training capabilities. The bayesian nature means that it > doesn't use pre-determined heuristics, so tends to catch even > the most > subtle spam. > > There is no binary distribution yet for good reason - significant, > incompatible changes are still being made. But if you are > brave enough, > all the source code is there (it is all pure-Python once you > have win32all) > > It-works-for-four-people-that-I-know-of I'd be happy to be a guiniea pig :-) -- bjorn From marklists at mceahern.com Thu Oct 3 16:04:49 2002 From: marklists at mceahern.com (Mark McEahern) Date: Thu, 3 Oct 2002 15:04:49 -0500 Subject: A challenge from the Mensa Puzzle Calendar In-Reply-To: Message-ID: > I wrote (IMHO) a very nice piece of python code to solve this for me, > and then generalized it a bit: What if the first digit (7) is not > given? How many unique solutions do we get and what are they? (I > included those numbers that started with 0 for consistency.) > > I'm a puzzle kind of guy, so I thought some of you might be, too. > I'd be very curious to see the kind of solutions people come up with. > My solution ended up being a total of 19 lines of code, including a > print statement to give me a nice formatted output for each solution, > resembling the initial problem from the calendar. > > OK, folks. The gauntlet is down. Have at it! > > (NOTE: I realize this is not really a Python thingy, but more of an > algorithm design thingy, but nonetheless, fun.) Nice puzzle. This is my first stab. It could easily be more general. #!/usr/bin/env python """ In the following multiplication statement, all digits 0-9 are used and are represented with X: 7XX XX ----- XXXXX Solutions: try all possible combinations? Think of it as a string like this: 7XXXXXXXXX You then have a function: def solve_equation(equation, string): ... """ from __future__ import generators def solve_equation(equation, x, replace="X", replacewith="123456890"): # There are hints here of how to generalize this further. # To generalize, don't assume first digit is the one we don't fiddle. supplied_digit = x[0] # seq = x[1:] # assert len(seq) == len(replacewith) for i in permIter(replacewith): p = str(supplied_digit) + str(i) if eval(equation): yield p def permIter(seq): """Given some sequence 'seq', returns an iterator that gives all permutations of that sequence. Source: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/105962 """ ## Base case if len(seq) == 1: yield(seq[0]) raise StopIteration ## Inductive case for i in range(len(seq)): element_slice = seq[i:i+1] rest_iter = permIter(seq[:i] + seq[i+1:]) for rest in rest_iter: yield(element_slice + rest) raise StopIteration a = "7XX" b = "XX" c = "XXXXX" equation = "int(p[0:3]) * int(p[3:5]) == int(p[5:10])" for p in solve_equation(equation, a+b+c): print p From tim.one at comcast.net Sun Oct 20 15:51:31 2002 From: tim.one at comcast.net (Tim Peters) Date: Sun, 20 Oct 2002 15:51:31 -0400 Subject: Speeding up a script -- looking for ideas In-Reply-To: Message-ID: [Richard Bow] > I'm hoping to get some hints for significantly speeding up the below > script. I've found 43 integers between 1 and 1,000,000 that satisfy the > condition, and would like to push on toward 10,000,000 in hopes > of finding an integer for which there are 3 pairs. Of course, another > reason for asking is to learn more Python from you guys. I'm going to cheat by using a better algorithm. This finds all the results up to 10,000,000 in about half a second on my box (under current CVS Python, which is a bit zippier). You'll find going up to 100,000,000 more interesting (which takes longer than an eyeblink, but a lot less time than it's taking me to add this gratuitous parenthetical comment ). The key gimmick: The cube root of N is a *hell* of a lot smaller than N. So rather than look at each N and then look for all ways of expressing N as the sum of two cubes, instead loop over all cubes and figure out all the N that can be gotten via adding two cubes. This is Rule #1 of Python optimization: Any Python program using a dict is 1000x faster than any C program. There are no exceptions to this rule . def drive(start, end): largest_root = int(end ** 0.333) while (largest_root + 1) ** 3 < end: largest_root += 1 cubes = [i**3 for i in xrange(1, largest_root + 1)] ncubes = len(cubes) n2cubes = {} # map n to list of (cube1, cube2) for i in xrange(ncubes): cube1 = cubes[i] for j in xrange(i, ncubes): cube2 = cubes[j] n = cube1 + cube2 if n > end: break n2cubes.setdefault(n, []).append((cube1, cube2)) for n, pairs in n2cubes.iteritems(): if len(pairs) >= 2: print n, pairs From mwilson at the-wire.com Sat Oct 19 11:36:20 2002 From: mwilson at the-wire.com (Mel Wilson) Date: Sat, 19 Oct 2002 11:36:20 -0400 Subject: wxPython newbie problems References: <3db1535b_10@news.newsgroups.com> Message-ID: <0vXs9ks/KPve089yn@the-wire.com> In article <3db1535b_10 at news.newsgroups.com>, JB wrote: >I should like to rewrite a small application that runs on >PyQt/Linux to work on wxPython/WinNT (as Qt is not free on >Windows). >I hav installed wxPython and get some principal difficulties >at the start: >I open a text console and type in >> python wxtest.py >Then I get a window with some error messages but this window >is closed again so I see only a flash and cannot read the >error messages. >Can somebody help me? I don't have anything elegant on this -- I just set up my main program code as import traceback try: # The only way to debug in Python 2.1 / wxPython app = MyApp () app.MainLoop () except: # The only way to debug in Python 2.1 / wxPython traceback.print_exc (file=open('error.txt', 'w')) and then get the error messages from the error.txt file. Good Luck. Mel. From dougfort at dougfort.net Tue Oct 8 18:09:23 2002 From: dougfort at dougfort.net (dougfort) Date: Tue, 08 Oct 2002 15:09:23 -0700 (PDT) Subject: [ANN] FixedPoint with selectable rounding Message-ID: <20021008150925.26246.h003.c001.wm@mail.dougfort.net.criticalpath.net> FixedPoint release 0.1.0 http://fixedpoint.sourceforge.net This is the second SourceForge release for Tim Peters' FixedPoint math object. What's New ========== The main new feature is settable rounding. You can select which rounding algorithm FixedPoint uses by assigning a bound function to FixedPoint.RoundingAlgorithm. Take a look at examples/roundingsample.py to see various forms of rounding. Joe has redone the LaTex documentation to add an excellent description of rounding. There's a link to the HTML rendering at the project website. We also modernized the code a little. - FixedPoint now derives from 'object', making it a 'new' class. - FixedPoint's member variables are now in __slots__. - precision is now a property, allowing you to uses expression like f.precision -= 1 (note that get_precision/set_precision are unchanged, so this shouldn't break anything) What's Next =========== This release concludes our planned changes to FixedPoint. We're going to sit back and watch for bug reports and feature requests, but we won't mess with the code anymore without provocation. You can enter bug reports and feature requests at the project website: http://fixedpoint.sourceforge.net Contents ======== README - this readme file fixedpoint.py - the FixedPoint module itself libfixedpoint.tex - LaTex documentation test_fixedpoint.py - unit tests for regression testing examples - a folder of sample code containing: FPBench.py - a benchmark program, timeing various FixedPoint operations roundingsample.py - a small demo, showing what can be done with rounding Doug Fort http://www.dougfort.net From peter at engcorp.com Thu Oct 3 01:40:24 2002 From: peter at engcorp.com (Peter Hansen) Date: Thu, 03 Oct 2002 01:40:24 -0400 Subject: Deleting the first element of a list References: <3d9b72c0_5@news.newsgroups.com> <3D9B78EC.B5316B9B@alcyone.com> <3d9b8082$1@news.sentex.net> <3D9BC6F0.4080500@cygnus-software.com> Message-ID: <3d9bd845@news.sentex.net> Bruce Dawson wrote: > Then it should be much better to go: > > myList.reverse() > while myList: > # Do Something with the last element > del myList[len(myList)-1] > > This changes it from O(n^2) to O(n), which could make it run thousands > of times faster. You're making assumptions, possibly good ones, about the implementation of the list object in Python. It's possible, though obviously unlikely, that the list is reallocated and copied every time it shrinks by even one element. (I'm just pointing this out for discussion purposes... no doubt it doesn't work that way.) That would leave it at O(n^2). Unless you profiled this already under a particular implementation of Python and are sure it really is a question of O(n) vs. O(n^2)... Likewise, even with the original question, it's possible that for del list[0] vs. list = list[1:] the overhead of allocating a new list and deallocating the old one is negligible compared to the cost of copying n-1 references around in memory. In that case there would be only minor performance differences between them for suitable values of n. -Peter Disclaimer: the above may contain bizarre misspellings. Apparently late-night dyslexia led me to write "dellocating" and "deglegible", and I couldn't figure out the correct spellings for a while... there may still be others lurking. Yikes... From Stefan.Goethals at adept.be Fri Oct 11 05:54:09 2002 From: Stefan.Goethals at adept.be (Stefan - ZipKid - Goethals) Date: Fri, 11 Oct 2002 09:54:09 GMT Subject: AttributeError with getmail. Message-ID: <3DA6A0A3.8010605@adept.be> Hello, I am assembling a cd-based linux system. I installed python and getmail (http://freshmeat.net/projects/getmail/) When i start getmail i get the following error: getmail version 2.3.9 ConfParser version 3.1 Python version 2.2 (#1, Mar 26 2002, 15:46:04) [GCC 2.95.3 20010315 (SuSE)] Unhandled exception follows: File "/usr/lib/getmail/getmail.py", line 1569, in main getmail (account, _locals).go () File "/usr/lib/getmail/getmail.py", line 397, in __init__ except socket.error, txt: AttributeError: 'module' object has no attribute 'error' The problem is NOT with getmail since an identical install on another system works ok. I am probably missing a lib or a file somewhere. As I now very little about python, could someone point me in the correct direction please. Stefan Goethals. -- #Stefan - ZipKid - Goethals http://adept.be stefan.goethals at adept.be # # Linux User Group West Vlaanderen # Vereniging voor Open Standaarden # # http://lugwv.be # http://openstandaarden.be # From alessandro.bottoni at infinito.it Thu Oct 24 04:25:20 2002 From: alessandro.bottoni at infinito.it (Alessandro Bottoni) Date: Thu, 24 Oct 2002 10:25:20 +0200 Subject: Random Database in Python In-Reply-To: References: Message-ID: <200210240836.g9O8atl14996@mail2.infinito.it> Alle 09:42, mercoled? 23 ottobre 2002, David LeBlanc ha scritto: > Is there any example of the type of database used by programs like Lotus > Agenda or InfoSelect in Python? Sometimes described as a "random" > database... > > Failing that, does anyone have a notion of how they work or can point me to > information on them? > > TIA, > > David LeBlanc > Seattle, WA USA I do not use neither Lotus Agenda nor InfoSelect (I use the KDE Office programs) but I think they should work in one of these ways: - a linked (or double linked) list of "event" objects, implemented and stored as a collections of linked Python objects. This is the most likely solution for a small agenda-oriented applications. - a regular RDBMS, like MySQL, used to store the agenda events and the related info into linked tables (using "foreign keys" to link the table each other). This requires an external RDBMS or an internal RDBMS engine. It is meaningful only if you plan to manage a large, multi-user application. - an OODMS, like ZODB (the OO database used by Zope). Same as above. - a B-Tree internal database engine. I just cannot help you with this item because I do not use this technology. You can find the related info by searching for the mentioned terms with google. Try something like: +"linked list" +python +database, for example. Python have a few different built-in facilities for dealing with data on the disk, starting from simple database engines like Gadfly to much more sophisticated OO DMS engines like ZODB. Have a look at "marshall", "pickle" and "dictionaries" into the Python doc, for example. Of course, "linked lists" and other internal data structures are described in many beginner's guide for programmers that are devoted to data structures, as well. Have a look at ASPN.activestate.com web site, as well. The "database" section of the activestate's Python cookbook contains a lot of info and examples on marshalling, pickling, dictinaries, small and large database engines and related technologies. --------------------- Alessandro Bottoni From bokr at oz.net Sun Oct 13 22:11:22 2002 From: bokr at oz.net (Bengt Richter) Date: 14 Oct 2002 02:11:22 GMT Subject: Buffering control in python? References: Message-ID: On Sun, 13 Oct 2002 15:45:21 -0600, Fernando =?ISO-8859-1?Q?P=E9rez?= wrote: >holger krekel wrote: > >> No that i know off. The closest is the aspn-cookbook. >> >> Heck, I can't believe it. >> >> We still don't have a useful repository for all >> the nice snippets, recipes and patterns posted and >> discussed everywhere. Although there is plenty of nice >> web-software, mailing lists and whatnot written in python. >> Sometimes people say that we have a great standard lib >> aka "batteries included". True, but i don't think that's >> enough. E.g. > >Hey Holger, why don't you repost this as a new thread? I think it's worth it >and it will prevent it from being filtered out by those who see the buffering >subject and decide they are not interested. > Seconded. I'll add something when the thread appears. ;-) Regards, Bengt Richter From martin at v.loewis.de Mon Oct 21 17:55:05 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 21 Oct 2002 23:55:05 +0200 Subject: how to use smtp starttls() encryption? References: <8f41cfd.0210101719.ad47c7@posting.google.com> <8f41cfd.0210120805.6ced204a@posting.google.com> <8f41cfd.0210162236.3e5c970a@posting.google.com> <8f41cfd.0210211030.33365530@posting.google.com> Message-ID: xucs007 at yahoo.com (Xu, C.S.) writes: > Any help? Make sure you compile the SSL support of the socket module. Specifically: Check the compilation output for the line that compiles the socket module, and try to find out why it fails to pass the USE_SSL command line option. The most likely reason is that you don't have OpenSSL installed. Regards, Martin From mwh at python.net Mon Oct 14 07:45:52 2002 From: mwh at python.net (Michael Hudson) Date: Mon, 14 Oct 2002 11:45:52 GMT Subject: Unhelpful Error Messages No. 15: Find it yourself. References: <95959723.0210111721.6b170cca@posting.google.com> Message-ID: Dale Strickland-Clark writes: > Anyway, for what it's worth, after several hours of hacking the code > around trying to work out which bit was at fault, I eventually deleted > the .pyc files and the problem went away. If that cured your problems, something pretty odd has happened! It's not surprising that the error messages were wierd. > How fustrating is that? Very, I'm sure. Cheers, M. -- US elections For those of you fearing that the rest of the world might be making fun of the US because of this: Rest assured, we are. -- http://www.advogato.org/person/jameson/diary.html?start=12 From martin at v.loewis.de Wed Oct 16 11:40:05 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 16 Oct 2002 17:40:05 +0200 Subject: Parsing SGML document in Python program References: Message-ID: Eric Brunel writes: > I had once to do that and I couldn't find a parser directly usable in > Python. Maybe it has changed (just check the Vaults of Parnassus for it). > The solution I used at the time was to rely on an external parser that gave > easy to parse results. The one I used was nsgmls, part of James Clark's SP > project. You may find it @ http://www.jclark.com/sp/ ; just test it and > you'll see that its output is really easy to get back into Python. When I need structure analysis, I use nsgmls as well: its output is really easy to process. Regards, Martin From GavinT at ResMed.com.au Wed Oct 30 18:44:16 2002 From: GavinT at ResMed.com.au (Gavin Tomlins) Date: Thu, 31 Oct 2002 10:44:16 +1100 Subject: getting the script name - ActiveScripting Message-ID: <362133AB12B2CE4EA3C01E12CD6CCC6E0254E1A9@osprey.corp.resmed.org> Hi Henk, One problem we have is that we haven't been able to access variables of the host application. I was wondering if you have managed to achieve this within your development. My understanding is that, if the scriptinterpreter comes across a variable it doesn't understand it fires it to the ActiveScript engine and the registered engine eg. Python for further interpretation, if nothing is found then it returns an error. Is this your experience? We have been testing this using ActiveState Python but have had limited success. If you could possible share your experiences or any references, it would be appreciated. Regards Gavin -----Original Message----- From: Henk [mailto:Henk] Sent: Wednesday, 9 October 2002 7:42 PM To: python-list at python.org Subject: Re: getting the script name On Wed, 09 Oct 2002 09:28:17 GMT, Padraig Brady wrote: >Henk wrote: >> Hi, >> >> Is there any way to retrieve the name of the running script from >> within this running script? > >import sys >sys.argv[0] Thanks, However, I need to refine my question: my script is launched from within a C++ app (using IActiveScriptingEngine and that kind of stuff). Using your solution gives me the exe, not the script name. Any idea? Henk > -- http://mail.python.org/mailman/listinfo/python-list Warning: Copyright ResMed. Where the contents of this email and/or attachment includes materials prepared by ResMed, the use of those materials is subject exclusively to the conditions of engagement between ResMed and the intended recipient. This communication is confidential and may contain legally privileged information. By the use of email over the Internet or other communication systems, ResMed is not waiving either confidentiality of, or legal privilege in,the content of the email and of any attachments. If the recipient of this message is not the intended addressee, please call ResMed immediately on +61 2 9886 5000 Sydney, Australia. From JXSternChangeX2R at gte.net Wed Oct 16 11:00:44 2002 From: JXSternChangeX2R at gte.net (JXStern) Date: Wed, 16 Oct 2002 15:00:44 GMT Subject: What is the class of myobj? References: Message-ID: <6lvqqusonelt6v6kato74gfppkomp0il7b@4ax.com> On Wed, 16 Oct 2002 11:29:57 +0100, Xiao-Qin Xia wrote: >Class MyClass: pass >myobj = MyClass() >if myobj.__class__.__name__ == "MyClass": print "OK!" >if myobj.__class__ == MyClass: print "OK!" Also very useful to know, thanks! Especially that last one never occured to me, eg: >print MyClass __main__.MyClass J. From duncan at NOSPAMrcp.co.uk Thu Oct 3 04:26:20 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Thu, 3 Oct 2002 08:26:20 +0000 (UTC) Subject: regex: im getting better References: Message-ID: ":B nerdy" wrote in news:uDLm9.21074$kd3.60008 at news-server.bigpond.net.au: > $pattern = '|]*)="([^"]*)")*>|ism'; > > i'd like to match all the input tags's but also in a subexpression, > i'd like to match each of the parameters in the format > parameter_name="parameter_value" > where parameter_name and parameter_value are strings > > my pattern doesnt work, it only matches the last parameter, whats > wrong with my pattern? and can someone show me how one would match my > description above? > > cheers > Personally I wouldn't even consider using regular expressions for a parsing task like this. Try the code below instead: import sgmllib class MyParser(sgmllib.SGMLParser): def do_input(self, attributes): print "Input tag",attributes if __name__=='__main__': data = ''' ''' parser = MyParser() parser.feed(data) parser.close() -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From stacom at stacom-software.de Mon Oct 14 12:31:04 2002 From: stacom at stacom-software.de (Alexander Eisenhuth) Date: Mon, 14 Oct 2002 18:31:04 +0200 Subject: newbie: constructor question Message-ID: <3DAAF148.3060509@stacom-software.de> Hallo everybody, is it possible to implement multiple constructors with different no. of arguments for one class ? >>> class A: def __init__(self, a): self._a = a def __init__(self,a,b): self._b = b def __init__(self,a,b,c): self._c =c >>>obj = A(12) Traceback (most recent call last): File "", line 1, in ? obj = A(12) TypeError: __init__() takes exactly 4 arguments (2 given) >>> -------------------------------- That doesn't work. Any suggestions ? Thanks in forward Alexander From news at titanic.co.uk Sat Oct 12 04:46:24 2002 From: news at titanic.co.uk (Simon Faulkner) Date: Sat, 12 Oct 2002 09:46:24 +0100 Subject: Ignoring comments - Parsing input file Message-ID: I am writing a script which reads it's input from a text file What is the easiest way to make it ignore lines that start with # or blank lines? Simon From mhammond at skippinet.com.au Sat Oct 19 21:19:20 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Sun, 20 Oct 2002 01:19:20 GMT Subject: Win32, COM, DLLs and DirectX References: <3dafef7a$0$1367$626a54ce@news.free.fr> Message-ID: I'm afraid that pythoncom can not support calling vtable based interfaces. You really have 3 options: 1) Help me fix this. You need more C++/x86 experience that Python experience to help with this, but we have the other half of the problem solved (that Python can implement such interfaces) so is tractable. 2) Use some other tool. SWIG may be a good candidate here, as that is how I previously wrapped exchange, ocx control, shell32 etc support. The tools are all in place in the win32com build setup. 3) Any option not one of the above . Mark. GambiT wrote: > Hi everyone, > > I am quite new to Python, and as a game developper I am looking forward > using it in development tools (like graphical editors and so on). > I know useful graphical libraries like OpenGL and SDL are available (not > mentionning GUIs) from Python code, but I wanted to do a little check by > myself about DirectX. > > Talking about a specific tool, it can be possible to think about all DirectX > features I need and use a DLL to be loaded in Python to call them. But for > the moment I wanted to know how deep into DirectX I can dive from Python. > > First thing I tried is COM objects, or I would better say DirectX Type > Librairy for Visual Basic. I do not quite understand really what is the > difference between this and an usual COM object, but it seems I cannot > access DirectX features this way. At best, I can obtain a IDirectx8 > interface object, but no further (as DirectX methods are stored in vtables I > cannot access and it seems other intrefaces do not support IDispatch - then > I cannot instantiate any other type of object) > > Then I looked at dynwin and calldll stuff, and loaded DX DLLs. Methods are > accessible this way, but as there is no type support for DX objetcs this > way, I cannot do much with returned objects (for example I can create a > device from DX top-level interface loaded from the DLL, but then I cannot > access the device object's methods) > > I read on the pycom-dev ML that someone has coded the Invoke() and > InvokeTypes() methods for PyITypeInfo, and making win32com.client support > vtable interfaces. I am not there yet, as I do not have any experience of > Python in-depth coding. > > Could someone give me some advice, or someone has maybe run into the same > problem. Any kind of help would be appreciated. > > Thanks, > Alexis > > From tundra at tundraware.com Sat Oct 5 15:50:08 2002 From: tundra at tundraware.com (Tim Daneliuk) Date: 05 Oct 2002 19:50:08 GMT Subject: Python + Win32: Cut/Paste w/o GUI References: <5dukna.oh1.ln@boundary.tundraware.com> <3d9ef747_1@corp-goliath.newsgroups.com> Message-ID: Roger Upole wrote: > You can grab the clipboard text using the win32clipboard module. > > import win32clipboard > win32clipboard.OpenClipboard() > print win32clipboard.GetClipboardData() > win32clipboard.CloseClipboard() > > It won't really be copy'n'paste, but all you would have to do is copy the > text you need and double-click the script, which can then do whatever it > wants with the text. If you really wanted it to look like a Paste, you > could > add a Paste action the the .py filetype. > Roger > *Exactly* the magic that I was looking for. Many thanks... (and also to the other folks who took the time to respond...) -- ------------------------------------------------------------------------------ Tim Daneliuk tundra at tundraware.com From skip at pobox.com Thu Oct 3 23:07:55 2002 From: skip at pobox.com (Skip Montanaro) Date: Thu, 3 Oct 2002 22:07:55 -0500 Subject: A challenge from the Mensa Puzzle Calendar In-Reply-To: <3D9CF1E9.9030600@something.invalid> References: <3D9CF1E9.9030600@something.invalid> Message-ID: <15773.1547.608303.792441@localhost.localdomain> Greg> Marco Mariani wrote: >> Why use an algorithm when you've got a gigahertz CPU and a list >> comprehension? Greg> That would make a great Python quote! Does anyone keep a database Greg> of such things? Yes, Andrew Kuchling does, though I don't know where it lives off-hand. Skip From ken at hotmail.com Fri Oct 11 09:55:56 2002 From: ken at hotmail.com (Ken) Date: Fri, 11 Oct 2002 23:55:56 +1000 Subject: cgi integration question References: Message-ID: "Gerhard H?ring" wrote in message news:slrnaqdigu.164.gerhard.haering at haering.opus-gmbh.net... > [Broken Outlook Express quoting manually repaired, setting > textwidth to 65 to help your craps oftware not mess up] > > Ken [2002-10-11 12:34 GMT]: > > "Gerhard H?ring" wrote: > >> Ken [2002-10-11 12:03 GMT]: > >> > [...] I have 2 sets of code. Python is used to display > >> > interface and C++ is used for backend execution. The > >> > executed result is saved to file so the python can read it > >> > and display back on the screen. [...] > >> > >> No need for intermediary files, just use os.popen*. > >> > >> Here's a simple example: > >> > >> >>> import os > >> >>> outf, inf = os.popen2("cat") > >> >>> print >>outf, "hi" > >> >>> outf.close() > >> >>> print inf.read() > >> hi > >> > >> outf is a stream to write to your child process (in this example, > >> the Unix cat utility, which will just duplicate on stdout what it > >> gets on stdin). After writing the "parameters" to cat's stdin, I > >> close it (don't ask me why that's necessary, but this is the way it > >> works :-D). Then, I read the whole output of cat and print it. > > > > Hi, can you explain what is "inf" and "popen2" in: > > outf, inf = os.popen2("cat") ? > > os.popen2 is a function in the os module. It gets one parameter: > the executable you want to run as a child process. It returns a > tuple of two file objects: > > * The first file object is connected to the > input stream of the child process, i. e. you can WRITE to it. > > * The second file object is connected to the output stream of the > child process, i. e. you can READ from it. > > > Is "cat" suppose to be a program name for me to call? > > Yeah. As you seem to use Windows (with a b0rken newsreader), you > won't have a 'cat' program. But you will have a 'sort' program, > so you can try the following: > > >>> import os > >>> outf, inf = os.popen2("sort") > >>> print >>outf, "Mark" > >>> print >>outf, "Joe" > >>> print >>outf, "Marvin" > >>> outf.close() > >>> lines = inf.readlines() > >>> inf.close() > >>> print lines > ['Joe\n', 'Mark\n', 'Marvin\n'] Will argc[1] = "Mark", argc[2]="Joe" and argc[3]="Marvin" in this example? Does "lines = inf.readlines()" read out what is exactly printed out from the return value of the main method or does it catch out what is printed out from the cout<< command? Eg:, if I have a command line: cout<<"hello world"<<"hi"< > So.... if I get the idea right, my program should look like this: > > import os > > outf, inf = os.popen2("cat") > > # Obviously, replace 'cat' with the path to your compiled C++ > # application. > > # This send input to the C++ program: > > > print >>outf, "hi" > > > outf.close() > > > print inf.read() # does this mean read from file? > > Yep. > > > and the backend c++ program look somethingl like this: > > executable filename: cat > > > > #include > > using namespace std; > > > > int main (int argc, char** argv) { > > cout << "value from argv"<< endl; > > return 0; > > } > > > > Still don't get how values are passed to the backend though....can you > > please explain.... : ( > > In the Python script, you send the paramters to the C++ program > by writing to its stdin. Then, the C++ program does its job, and > when it's ready writes its output on stdout. See above for how to > do the Python script, and here's a simplistic C++ 'backend' > program: > > /** > * doubler.cc - Reads one line from stdin, then returns the > * "doubled" string on stdout. > */ > > #include > #include > > using namespace std; > > int main(int argc, char** argv) { > string s; > > cin >> s; > > cout << s + s; > > return 0; > } ['ss'] or ['s', 's'] or ['s\n', 's\n'] ? > > > Alternatively, you could send over commandline arguments and > parse these in the C++ app. > > HTH, > > -- Gerhard Thanks From emile at fenx.com Fri Oct 11 10:37:01 2002 From: emile at fenx.com (Emile van Sebille) Date: Fri, 11 Oct 2002 07:37:01 -0700 Subject: Monty Python TV Collection Message-ID: This spam caught my eye this morning. I though it may be of interest to some. Apologies if not or it's old news. Here's your chance to scoff at all of your friends who have been trying for years to record Monty Python episodes off the television. Because now you can own the "Full Monty," yes, that's every single episode of the ground-breaking British comedy series, in one giant 14 disc DVD collection. All the classics are here, every quirky, bizarre & just plain silly episode is yours to cherish. This DVD collection also includes special features like: Meet the Chaps, Pythonisms Glossary, Troupe Career Highlights and Trivial Quest. The entire crumpet is OVER 24 HOURS LONG in full color. http://ads.pulsetv.com/al/a?aid=3194&ent=58 The COMPLETE Monty Python TV Collection on DVD for $199.98 -- Emile van Sebille emile at fenx.com --------- From mwh at python.net Fri Oct 18 09:02:30 2002 From: mwh at python.net (Michael Hudson) Date: Fri, 18 Oct 2002 13:02:30 GMT Subject: How to print a string one char at a time, with no spaces? References: Message-ID: Richard Bow writes: > I'd like to write a script that appears to be calculating digits of pi and > spitting them out one at a time, with no spaces, such as below (pi to 1002 > digits, gotten from http://www.angio.net/pi/piquery ). It's easy to do this > by > > pi = str(pi) > for k in range(len(pi)): > print pi[k], > > but this prints 3 . 1 4 1 5 9 2 6 5 ... > > How to print without those Python spaces (which are very nice when you want > them)? Two options: 1) don't use print at all, use sys.stdout.write() instead: >>> for c in str(math.pi): ... sys.stdout.write(c) ... else: ... sys.stdout.write('\n') ... 3.14159265359 >>> 2) reset sys.stdout.softspace after each print: >>> for c in str(math.pi): ... print c, ... sys.stdout.softspace = 0 ... else: ... print ... 3.14159265359 >>> Cheers, M. -- I have gathered a posie of other men's flowers, and nothing but the thread that binds them is my own. -- Montaigne From mongo57a at comcast.net Sat Oct 5 17:04:27 2002 From: mongo57a at comcast.net (mongo57a at comcast.net) Date: Sat, 5 Oct 2002 21:04:27 GMT Subject: What a mess! References: <3d9e2b8f$1_8@goliath.newsgroups.com> Message-ID: <3d9f4271_7@goliath.newsgroups.com> Thanks. I'll see if I can untangle myself from this. -----------== Posted via Newsfeed.Com - Uncensored Usenet News ==---------- http://www.newsfeed.com The #1 Newsgroup Service in the World! -----= Over 100,000 Newsgroups - Unlimited Fast Downloads - 19 Servers =----- From gua81 at XXXyahoo.com Mon Oct 7 11:10:42 2002 From: gua81 at XXXyahoo.com (CheapSkate) Date: Tue, 8 Oct 2002 01:10:42 +1000 Subject: String help References: <3DA18C4C.1050705@Linux.ie> Message-ID: OK COOL! It all worked now! Thanks people. When I post the earlier msg, I did not have python installed in my system. I have to upload the files to the web server and try to run it. It's pretty tedious. Telnet will be too slow(im on dial-up) PS: I have python installed now! :) From edgebruce at yahoo.com Tue Oct 1 18:34:07 2002 From: edgebruce at yahoo.com (Bruce Edge) Date: Tue, 01 Oct 2002 15:34:07 -0700 Subject: Override a method in another module Message-ID: What's the basic syntax to override (redefine) a function in another module at runtime? Say, I have module M, class C, method F, and I want to redifine method F. setattr( M.C.F, eval("def F(self): pass")) doesn't exactly work..... Thanks, Bruce. From m2 at plusseven.com Tue Oct 15 16:42:37 2002 From: m2 at plusseven.com (Alex Polite) Date: Tue, 15 Oct 2002 22:42:37 +0200 Subject: scripting ximian evolution Message-ID: <20021015204237.GA868@matijek.plusseven.com> According to ledgend it's possible to interact with ximian evolution's addressbook and calendar (wombat?) via python. Has anyone actually tried this? If so please post some code. -- Alex Polite http://plusseven.com/gpg From mstenner at phy.duke.edu Tue Oct 8 11:40:28 2002 From: mstenner at phy.duke.edu (Michael Stenner) Date: Tue, 8 Oct 2002 11:40:28 -0400 Subject: [OT} How to un-GPL parts of a GPL'd module. In-Reply-To: ; from anton@vredegoor.doge.nl on Tue, Oct 08, 2002 at 05:00:06PM +0200 References: Message-ID: <20021008114028.A14289@phy.duke.edu> On Tue, Oct 08, 2002 at 05:00:06PM +0200, Anton Vredegoor wrote: > On Tue, 8 Oct 2002 09:03:44 -0400, "Steve Holden" > wrote: > > >"Anton Vredegoor" wrote in message > >news:anujeq$qdk$1 at news.hccnet.nl... > > > >> I guess I could e-mail the author for permission but if I would have > >> to wait for them to answer, it would slow my coding process down to a > >> snail's pace, and there's always the possibility of the author being > >> unwilling. > >> > >Indeed. Perhaps you should consider releasing your own code under the GPL > >rather than some other license. That way there's no problem incorporating > >GPL'd code. > > That would solve the problem at the cost of passing on the problem to > the next coder. It's this kind of "chain letter like" property that I > want to adress. But that is the fundamental point of the GPL. You're not pointing out some subtle side-effect burried on clause 53d here. You're asking how you remove the GPL-ness from the GPL. It's a silly question. > In case it's not clear, the chance of me finding an employer is > remote. Contacting the original author consumes time and the outcome > would probably not be good since I don't agree with the "pass the > problem to the next guy" property of the GPL. You're not willing to GPL your code. The GPL states that you can't use this other guy's code UNLESS you GPL your code. You've got two options. 1) Get the other guy to license it differently for you. 2) Don't use his code. You correctly note that you've been tainted since you looked at his code. That leaves you in a bit of a quandry, but you got yourself into it. Why did you look at his code in the first place? You knew it was GPL'd. You knew you weren't willing to use the GPL! What LEGITIMATE benefit could you gain? > Since the dog metaphore was brought up, I would like to add the > comparison of having a GPL dog using a specific tree for some known > purpose and forbidding any other dog to use it for that same purpose > ... I don't understand this at all, but I'm guessing you're drifting into a more philosophical discussion of the benefits/drawbacks of the GPL. That's not relevant here at all. You may not like the GPL, but ultimately, the guy who wrote it gets to choose his license. Sure it puts restrictions on you. I don't like Microsoft's licenses either, because it puts restrictions on me. But they wrote it and they can license it any way they want. Sorry I don't have many warm fuzzies for you, but it really seems to me that you're simply trying to sneak around this guy's license, and that just ain't cool. -Michael -- Michael Stenner Office Phone: 919-660-2513 Duke University, Dept. of Physics mstenner at phy.duke.edu Box 90305, Durham N.C. 27708-0305 From mstenner at phy.duke.edu Mon Oct 21 12:39:12 2002 From: mstenner at phy.duke.edu (Michael Stenner) Date: Mon, 21 Oct 2002 12:39:12 -0400 Subject: python script question In-Reply-To: ; from ken@hotmail.com on Tue, Oct 22, 2002 at 01:31:04AM +1000 References: Message-ID: <20021021123912.A15323@phy.duke.edu> On Tue, Oct 22, 2002 at 01:31:04AM +1000, Ken wrote: > Hi all, just like to ask if python CGI script can be mix with python Shell > script? > > I.e. if: > file1 is CGI (#!/usr/local/bin/python) > and file2 is shell script (#!/bin/sh) > > can I have "import file2" inside file1 and use the functions inside file2? Short (and pretty darned accurate) answer: no. You can run any shell COMMAND (including shell scripts) from within a python program via system or popen, or whatever. You won't easily be able to call a function from within a shell script, though. You could make "script wrappers" for all of those functions. If you have a master shell script that acts like a library, defining several functions, but executing none of them, then you could make several wrappers, each of them a script... like so: #!/bin/sh source master.sh # function foo is defined in master.sh foo $@ Then, you can call this file (foo.sh) via system from within python. > Also, does the shell script have *.py extension? Shell scripts usually have .sh extensions, but on unix, the extension exists only for the user's convenience. It usually has no relevance for the os. -Michael -- Michael Stenner Office Phone: 919-660-2513 Duke University, Dept. of Physics mstenner at phy.duke.edu Box 90305, Durham N.C. 27708-0305 From duncan at NOSPAMrcp.co.uk Thu Oct 3 04:36:30 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Thu, 3 Oct 2002 08:36:30 +0000 (UTC) Subject: Deleting the first element of a list References: <3d9b72c0_5@news.newsgroups.com> <3D9B78EC.B5316B9B@alcyone.com> <3d9b8082$1@news.sentex.net> <3D9BC6F0.4080500@cygnus-software.com> Message-ID: Bruce Dawson wrote in news:3D9BC6F0.4080500 at cygnus-software.com: > Then it should be much better to go: > > myList.reverse() > while myList: > # Do Something with the last element > del myList[len(myList)-1] > > This changes it from O(n^2) to O(n), which could make it run thousands > of times faster. Ignoring any questions of speed, it may make the code somewhat clearer to rewrite this as: myList.reverse() while myList: element = myList.pop() # Do Something with element Alternatively, in many cases you can just avoid the removal of individual items. For example if the list contains items to process, and during the processing it is possible that more items are added: while myList: work, myList = myList, [] for item in work: process(item) -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From cnetzer at mail.arc.nasa.gov Fri Oct 4 04:24:09 2002 From: cnetzer at mail.arc.nasa.gov (Chad Netzer) Date: Fri, 4 Oct 2002 01:24:09 -0700 Subject: Tix.FileEntry directory In-Reply-To: References: <3d9ca678.2970545@nntp.ix.netcom.com> Message-ID: <200210040824.BAA25683@mail.arc.nasa.gov> On Friday 04 October 2002 00:31, dijk wrote: > Why do I get this error?? > I thought that Tix is intalled when Tkinter is installed. Not necessarily. Tk can exist without Tix, and installations can run Tk and Tkinter without having Tix at all. That said, it looks like Tix is available, but perhaps not installed correctly (There are sometimes path scripts for Tcl that need to be set up) What kind of system is it? Windows? Linux? Where did you obtain the Python, Tcl/Tk and Tix packages? Do you have the ability to do some reconfiguration? -- Chad Netzer cnetzer at mail.arc.nasa.gov From wilk-spamout at flibuste.net Mon Oct 21 11:32:51 2002 From: wilk-spamout at flibuste.net (William) Date: 21 Oct 2002 17:32:51 +0200 Subject: Reports, PDF, and grid widget for Python? References: <3db41988@monitor.lanset.com> Message-ID: <87iszverj0.fsf@flibuste.net> "Adams-Blake Co." writes: > I want to write a "business" application in Python and I need to create many > complex text reports (subtotals, totals, grand totals, etc.). I'd also like > to display data in a grid object (like Java's Jtable.) Finally, I want this > to run on the Mac, Linux, and Windows.... with an install as easy as possible > and able to be performed by a non-techie. Thus, I don't want to get > "involved" with a 3rd party widget library (wxW.., Qt, etc.) that might make > the install a nightmare for the user. if you don't want to use 3rd party widget library, you can do a web application, with the http module of python. > > Is there a native Python library to do grids? How do you folks "layout" > complex reports and send them to PDF? pdf can be done with http://reportlab.com -- William Dod? - http://flibuste.net From marklists at mceahern.com Tue Oct 15 20:47:35 2002 From: marklists at mceahern.com (Mark McEahern) Date: Tue, 15 Oct 2002 19:47:35 -0500 Subject: What is the class of myobj? In-Reply-To: Message-ID: [JXStern] > I want to write something like: > > If ClassOf(myobj) == "MyClass": print "OK!" > or > If ClassOf(myobj) == MyClass: print "OK!" # no quotes on class > > The best I've found in Python is based on str(myobj.__class__). > > What's the official way? $ python Python 2.2.1 (#1, Jun 25 2002, 10:55:46) [GCC 2.95.3-5 (cygwin special)] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> class foo:pass ... >>> class bar(foo):pass ... >>> f = bar() >>> isinstance(f, foo) 1 >>> isinstance(f, bar) 1 >>> isinstance(bar, foo) 0 >>> issubclass(bar, foo) 1 >>> print f.__class__.__name__ bar >>> f.__class__.__name__ == "bar" 1 - From marklists at mceahern.com Wed Oct 2 12:25:45 2002 From: marklists at mceahern.com (Mark McEahern) Date: Wed, 2 Oct 2002 11:25:45 -0500 Subject: I really give up In-Reply-To: Message-ID: > Yes, I am aware of that. The only thing I'm trying to do is to implement > that alghoritm in python in order to give the hashed password back to some > server that uses it. As the previous poster hinted: import sha print sha.new("foobar").hexdigest() Are you saying this doesn't suffice? // m From mfranklin1 at gatwick.westerngeco.slb.com Wed Oct 9 06:50:15 2002 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Wed, 09 Oct 2002 10:50:15 +0000 Subject: Generating a spacer gif on the fly In-Reply-To: References: Message-ID: <200210091050.15168.mfranklin1@gatwick.westerngeco.slb.com> On Wednesday 09 Oct 2002 9:36 am, Max M wrote: > Hi > > I am writing an app where it would be practical to have a function that > generates a spacer gif in a given color:: > > def spacer(color=''): > "Generates a 1x1 pixel gif with color, no color means transparent" > Guessing that you are using Tkinter....... try the PhotoImage class:- from Tkinter import * class Spacer: def __init__(self, color="", width=1, height=1): self.image = PhotoImage(width=width, height=height) for row in range(height): for col in range(width): self.image.put(color, (row, col)) def getSpacer(self): return self.image if __name__=="__main__": root=Tk() image=Spacer(color="black", width=10, height=10) l=Label(root, image=image.getSpacer()) l.pack() root.mainloop() -- ### Python Powered Signature I started writting this email on Wed Oct 9 10:43:32 2002 From brian at sweetapp.com Tue Oct 15 16:31:26 2002 From: brian at sweetapp.com (Brian Quinlan) Date: Tue, 15 Oct 2002 13:31:26 -0700 Subject: Swedish characters in Python strings In-Reply-To: Message-ID: <001a01c27489$d5f4ffa0$df7e4e18@dell1700> Magnus wrote: : >>> import MP3Info : >>> title = getattr(MP3Info.MP3Info(open('file.mp3', 'rb')), 'title') : >>> title : 'K\xf6ttbullar i n\xe4san' I took a quick look at the ID3 specification reveals that Unicode was not introduced until ID3v2, so determining the encoding before that was not possible. With ID3v2, the possible encodings are ISO-8859-1, UTF-16 + BOM, UTF-16BE (no BOM) and UTF-8. When reading ID3v2, MP3Info should present the title as a Unicode object (though I have no idea if it actually does this or not). When reading ID3v[0,1], MP3Info would have no choice but to present the title as a byte string. Cheers, Brian From gerhard.haering at gmx.de Sat Oct 19 12:38:25 2002 From: gerhard.haering at gmx.de (Gerhard Haering) Date: Sat, 19 Oct 2002 18:38:25 +0200 Subject: Encryption In-Reply-To: <65113796.0210190752.29b0f326@posting.google.com> References: <65113796.0210190752.29b0f326@posting.google.com> Message-ID: <20021019163825.GA18703@gargamel.ghaering.test> * Dirk Lannatewitz [2002-10-19 08:52 -0700]: > Hi to all, > > I'm searching for one or mor modules, thats enables: > DES (mode: ECB and CBC) > Hashfunktions (MD-5 und SHA-1) and > RSA. > > I found pycrypto at sourceforge.net, but I'm unable to compile it. Argh. Doesn't compile with mingw: src/RIPEMD.c:108: conflicting types for `LONG' e:/mingw/include/winnt.h:51: previous declaration of `LONG' If I'll find some time, I'll try to submit a patch. But maybe it's fixed in CVS already. M$VC (*yuck*) works, here's the result (untested): http://www.cs.fhm.edu/~ifw00065/downloads/pycrypto-1.9a4.win32-py2.2.exe -- Gerhard From meles at free.fr Sun Oct 20 13:45:47 2002 From: meles at free.fr (Meles MELES) Date: Sun, 20 Oct 2002 19:45:47 +0200 Subject: Problem with gzip module and windows Message-ID: Hi, I'm actually having a little problem with the gzip module under Windows. I'm currently getting some text file containing many lines, all having the same format. Before applying any treatment to them, I would like to stock them in a single compressed text file. To do this, I've written a little piece of software like this one: import gzip Z1=gzip.GzipFile("test.txt.gz","ab",9) for i in listoffile: f=open(i,"r") for line in f.readlines(): Z1.write(line) f.close() Z1.close() Under linux, this little bit of software works very well. Under windows, it works very well the first time I launch the program (the test.txt.gz file is created and is filled with the lines of the other text files). But when I launch the script a second time, it doesn't work. There is no error message while running, but no new lines are added to the compressed archive. I just get 2 or 3 lines of weird symbol at the end ofthe previously imported lines. Any ideas of what's wrong? Best regards. Blaise. -- La beaut? sans la gr?ce attire, mais elle ne sait pas retenir ; c'est un app?t sans hame?on. Maxime Planude From hwlgw at hotmail.com Sat Oct 19 14:49:47 2002 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 19 Oct 2002 11:49:47 -0700 Subject: hostid? References: Message-ID: [Lance] > I'd like to retrieve a computer's hostid. Does anyone know how to do this? socket.gethostname() ''Return a string containing the hostname of the machine where the Python interpreter is currently executing. If you want to know the current machine's IP address, you may want to use gethostbyname(gethostname()). This operation assumes that there is a valid address-to-host mapping for the host, and the assumption does not always hold. Note: gethostname() doesn't always return the fully qualified domain name; use gethostbyaddr(gethostname()) '' >From the Reference Manual in your Python distro. Works like a charm on Windows; I have NT and XP. Linux sometimes has problems with that address-to-host mapping since linux is so hard to configure. ''' The program said "Requires Windows 9x or better", so I installed Linux. ''' From hancock at anansispaceworks.com Mon Oct 28 03:59:11 2002 From: hancock at anansispaceworks.com (Terry Hancock) Date: Mon, 28 Oct 2002 00:59:11 -0800 Subject: indirect **keyword calls Message-ID: Hi all, I've just recently come across a need for this idiom (isn't this new in Python 2.x?): def my_func(spam, ham=1, **eggs): #... pass where 'eggs' gets a dictionary of keyword arguments. I haven't previously had any experience with it. It seems that Zope's ZSQL methods accept their arguments in this form, but I need to provide an intermediate layer. Is there any way of writing a general call that passes a received set of keywords on to a called function. The following is apparently illegal, but I hope it expresses the concept: def sql_funct_i_want_to_call(**kw): """ makes an SQL query using keyword args and returns a result object, kw always contains a "username=''" field in this case. """ # ... pass def my_wrapper(username='anonymous', **kw): """ Now I want to try the call and return the result if there is one. Otherwise, I want to return a default record. """ kw['username']=username result = sql_funct_i_want_to_call(kw) if result: return result else: kw['username']='anonymous' result = sql_funct_i_want_to_call(kw) if not result: raise BrokenDBError("Database has no anonymous/default user") else: return result Or something along those lines. The only problem is that python doesn't seem to understand what I want when I try to pass the dictionary to the object "TypeError: sql_funct_i_want_to_call() takes exactly 0 arguments (1 given)" Is there a way to get what I want to do here without having to go through too many hoops? If I knew in advance what the arguments would be, I could do it that way, but I'd like to be able to define a general behavior and use it for a lot of similar SQL calls, in which case, kw would vary depending on the call needed. Maybe this is really obvious to someone else, but I can't see how to do it. Thanks for any ideas, Terry -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From mikeb at mitre.org Mon Oct 28 07:29:45 2002 From: mikeb at mitre.org (Mike Brenner) Date: Mon, 28 Oct 2002 07:29:45 -0500 Subject: Python COM for Microsoft Project (the final solution) Message-ID: <3DBD2DB9.3C2A0B26@mitre.org> Mike Brenner >> ... the code that worked to have a >> Microsoft Project file do a SAVE AS tab-delimited text ... >> My next challenge is to figure out why it is not automatically >> choosing the 'Map="Better Task Information". Instead, >> it is popping up a window and making the user select it >> with the mouse. That is the only remaining barrier to >> do a stream 100% automated SAVE AS COM commands. > If solved kindly help me as well, by telling me also > by sharing the solution. Sorry, I have not solved it in Python. The main engine that rips the Microsoft Project files is still in Python, but when I use it, it pops up boxes we have to click on each Microsoft Project file: - want to save? - want to enable macros? - which fields to save? To make this horrible situation a little better, I stopped using "Better Task Information" and just saved ALL the task information, so there is only an average of about 2 pop up windows on each Microsoft Project file. There was no change when we upgraded to Microsoft Project 2000. If we had some way to decode the object model better, there might be flags to take care of these pop-up boxes, but there are literally thousands of flags, and little or no explanation of what they do. Unless someone with better knowledge of those flags can shed some light on this issue, the next best hope will be a product Microsoft has announced for a July 2002 delivery, but not yet released. That product is called Microsoft Project 2002 Enterprise. I am not referring to the existing Microsoft Project Enterprise, which works the same was as Microsoft Project 97, 98, and 2000. When it finally gets released, it might be called Microsoft Project 2003 or XP or whatever Enterprise. They announced it would cost $1500 for a 5-seat license, but did not say what improvements it would have in access via COM. From ianholmes01 at lycos.com Fri Oct 4 07:03:48 2002 From: ianholmes01 at lycos.com (Ian Holmes) Date: 4 Oct 2002 04:03:48 -0700 Subject: Is it possible to 'compile' a script? References: <3D9CF0BA.6000207@something.invalid> Message-ID: "solosnake" wrote in message news:... > My suggestion to those responsible for > maintaining Python is to differentiate between calling a script which is > then parsed and compiled into bytecode and executed, and calling a function > which will parse and create the bytecode, but return a handle to that (now > faster) bytecode and allow it to be executed through this handle. > > Thanks for all replies. > > - solosnake When you first run a script in python the text file you created gets "compiled" into bytecode and run (as you mentioned) you will have also noticed that a .pyc file is created which is the bytecode version of your script. If you run myscript.py python will run myfile.pyc if it exists hence speeding up subsequent executions by not having to recompile into bytecode. If the .py file changes then obvoiusly it is recompiled. Therefore a handle isn't required as python uses the fastest method possible by default. ---Mike C. Fletcher wrote Or, you can decide to use something like the Python specialising compiler (Psyco). --- This is good and I recommend it. It increases the pystone benchmark by approx 5 times on my machine (ran on linux or win2k - celeron 500 320Mb) There is also pyrex you may wish to consider. From jsaul at gmx.de Thu Oct 10 05:41:10 2002 From: jsaul at gmx.de (jsaul) Date: Thu, 10 Oct 2002 11:41:10 +0200 Subject: partial list sort In-Reply-To: References: <20021009094141.GA852@jsaul.de> Message-ID: <20021010094110.GA11277@st18.gfz-potsdam.de> * Terry Reedy [2002-10-09 14:50]: > > list=[ [1,'C'], [2,'B'], [3,'A'], [4,'C'], [5,'B'], [6,'A'] ] > > print list > > Don't use list as a variable name. It is a builtin type name. I will > call this lis3. > > > def sort_components (list): > > def cmp_comp (data1, data2): > > if data1[1] == data2[1]: return 0 > > elif data1[1] < data2[1]: return -1 > > return 1 > > print list > > list.sort(cmp_comp) > > print list > > return > > Tabs are bad for Usenet posting if you want stupid people like me who > use Outlook Express to read posted code. I totally agree, sorry. > > for k in range(0, len(list), 3): > > # sort over ranges: > > sort_components(list[k:k+3]) > > for k in range(0, len(lis3), 3): #not tested > tem = lis3[k:k+3] > sort_components(tem) > lis3[k:k+3] = tem This works, thanks! Though the use of a temporary makes it look somewhat "ugly" doesn't it? ;) I have now changed it so that it returns the list, thus avoiding the temporary: lis3[k:k+3] = sort_components(lis3[k:k+3]) > Since you presumably want to process triples after sorting, I would > suggest going this route. IE > >>> listin=[ [1,'C'], [2,'B'], [3,'A'], [4,'C'], [5,'B'], [6,'A'] ] > >>> for item in listin: item.reverse() > ... > >>> listin > [['C', 1], ['B', 2], ['A', 3], ['C', 4], ['B', 5], ['A', 6]] > >>> worklist=[[listin[i],listin[i+1],listin[i+2]] for i in range(0,len(listin),3)] > >>> worklist > [[['C', 1], ['B', 2], ['A', 3]], [['C', 4], ['B', 5], ['A', 6]]] > >>> for triple in worklist: triple.sort() > ... > >>> worklist > [[['A', 3], ['B', 2], ['C', 1]], [['A', 6], ['B', 5], ['C', 4]]] That could be an alternative, though it involves restructuring the list, which can probably be handled somehow. But since copying seems unavoidable anyway, I'd prefer the above approach. That 'item.reverse()' won't work in "real life" because of the actually much more compex data type I want to handle, while the above was just meant as a minimal example to illustrate the problem. Thanks a lot to all who replied! Cheers, jsaul -- Que le gusta rrrodarrr la errre. From john.abel at pa.press.net Tue Oct 8 08:04:52 2002 From: john.abel at pa.press.net (John Abel) Date: Tue, 08 Oct 2002 13:04:52 +0100 Subject: SimpleXMLRPCServer Releasing Ports Message-ID: <3DA2C9E4.2070907@pa.press.net> Hi, I have a script running, using SimpleXMLRPCServer, which works OK. Except, when I stop, and restart the script, I receive the error, "Address already in use". Is there something I can do, like a destructor, to tidy up, so that the script can be restarted? Thanks John From juneaftn at REMOVETHIShanmail.net Sun Oct 6 22:58:41 2002 From: juneaftn at REMOVETHIShanmail.net (Changjune Kim) Date: Mon, 7 Oct 2002 11:58:41 +0900 Subject: Python + Win32: Cut/Paste w/o GUI References: <5dukna.oh1.ln@boundary.tundraware.com> <3d9e5d67.456578463@news-server.austin.rr.com> Message-ID: Check this out. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/150115 You don't need unxutils. "Rudy Schockaert" wrote in message news:byCn9.146954$8o4.21689 at afrodite.telenet-ops.be... > > I have a text file on my desktop (at work and I'm at home now, so I > > can't post the code) with extension of 'clipdata'. I registered a new > > file type in windows with this extension and I created two actions. > > The default action, runs my python script and the other action edits > > the file. The python program uses a popen call to the 'gclip.exe' > > from the unxutils package (http://unxutils.sourceforge.net/) which > > writes the clipboard data to stdout. I read from the popoen call and > > I have whatever was in the clipboard. I then write this to the top of > > the 'clipdata' file with a time stamp. I use this a temporary holding > > place for little scraps of code or SQL. All I have to do is load up > > the clipboard and then dbl-click the icon on the desktop (I have a > > command line function also) and the data is saved for posterity. > > The unxutils package also has a 'pclip.exe' which sends stdin to the > > clipboard, which I also have used with sucess. > > > > Hopefully this helps. If need be I can send you the code on Monday. > > Just email me. > > > > ... > > jay > > > > Jay, > > I think there are more people interested in that piece of code. I certainly > am. > I would like to try this out. So, if you send it, can you put me in CC > > Thanks, > > Rudy > > From printers at sendme.cz Thu Oct 17 09:08:21 2002 From: printers at sendme.cz (A) Date: Thu, 17 Oct 2002 15:08:21 +0200 Subject: Modules - problem Message-ID: <3DAED265.28699.F7C6B8@localhost> Hi, I would like to access a variable in one module from another module.For example The main module is like this ############# #Main modul z1.py import z3 print "x variable=", z3.x ########### where z3.py module is like ######## #My module z3.py global x x=11 ######### Now if I run z1.py for the first time it prints properly x variable= 11 but if I do any change in z3 module , it has no effect For example If I change in z3 x=12 I still get x variable= 11 Why? Thank you for help. Is it possible to name module with a different extension from py? For example is it possible to import z3.cod file? Ladislav From peter at engcorp.com Sat Oct 5 18:43:59 2002 From: peter at engcorp.com (Peter Hansen) Date: Sat, 05 Oct 2002 18:43:59 -0400 Subject: Fast persistent dictionary References: <3d9ddc93@news.mt.net.mk> Message-ID: <3d9f6b2e$1@news.sentex.net> Alex Martelli wrote: > ... but recent versions of Copycat's Berkeley DB Heh :-) I think you meant "Sleepycat", as in http://www.sleepycat.com/ -Peter From mwh at python.net Wed Oct 16 07:44:02 2002 From: mwh at python.net (Michael Hudson) Date: Wed, 16 Oct 2002 11:44:02 GMT Subject: Linux install question References: <0mDq9.28116$Lg2.7040405@news2.news.adelphia.net> Message-ID: "Robert Oschler" writes: > Do you do anything special in regards to setting the User and Group > priveledges for executing Python, what settings do you use? The main worry > of course is of someone hacking my linux box and perhaps running some > harmful python scripts. I don't understand this concern; if someone's cracked your account the presence or otherwise of Python isn't going to make a lot of difference. The default isn't to install the interpreter setuid root or anything insane like that. Cheers, M. -- it's not that perl programmers are idiots, it's that the language rewards idiotic behavior in a way that no other language or tool has ever done -- Erik Naggum, comp.lang.lisp From bokr at oz.net Fri Oct 18 15:20:36 2002 From: bokr at oz.net (Bengt Richter) Date: 18 Oct 2002 19:20:36 GMT Subject: XML question, DOM or SAX? References: <3DB01DD6.AA0D5C0F@ipm.fhg.de> Message-ID: On Fri, 18 Oct 2002 16:42:30 +0200, Markus von Ehr wrote: >Hi, > >1. >I want to save one or more spectras in a XML file. >The program shall be able to read this file into my own >data object structure, too. >The data can be displayed or altered. >After all the data has to be saved again to XML. > Why XML? Is there another consumer of the data whose requirements you are catering to? Have you looked at the pickle module? (BTW, I think someone has also written a pickler that uses XML, but I forgot what it's called) >Shall I use SAX or DOM? > The structure looks simple enough just to generate with print statements and a loop or two. Regards, Bengt Richter From jdhunter at ace.bsd.uchicago.edu Tue Oct 22 09:29:22 2002 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Tue, 22 Oct 2002 08:29:22 -0500 Subject: Help with MySQLdb Please In-Reply-To: <7ar1pa.404.ln@ix.netcom.com> (Dennis Lee Bieber's message of "Mon, 21 Oct 2002 14:24:23 -0700") References: <7ar1pa.404.ln@ix.netcom.com> Message-ID: >>>>> "Dennis" == Dennis Lee Bieber writes: Dennis> if the call expects a tupple for the last argument Dennis> you'll need to use (userinput,) -- -- Just tested that one but it didn't solve the problem. Thanks, JDH From tsidwick at remove.yahoo.co.uk Tue Oct 15 15:25:29 2002 From: tsidwick at remove.yahoo.co.uk (Tom) Date: Tue, 15 Oct 2002 21:25:29 +0200 Subject: mod_python and xml.dom.minidom problem References: <3DAB182B.9000201@remove.yahoo.co.uk> <3DAB2C4D.5040602@remove.yahoo.co.uk> <3DAB41F8.1080308@remove.yahoo.co.uk> Message-ID: <3DAC6BA9.3050706@remove.yahoo.co.uk> > > That seems to be the problem: You somehow have an old pyexpat > module. Please make sure you recompile pyexpat from the sources that > are included in PyXML 0.8 (or whatever version you are using). > I reinstalled PyXML 0.8.1 and that upgraded the expat version to 1.95.5. Now that my expat is correct, I now have the original error message that I was trying to fix : ------------------------------------------------------------------------ File "/usr/lib/python2.2/site-packages/_xmlplus/dom/minidom.py", line 1605, in parseString return expatbuilder.parseString(string) File "/usr/lib/python2.2/site-packages/_xmlplus/dom/expatbuilder.py", line 943, in parseString return builder.parseString(string) File "/usr/lib/python2.2/site-packages/_xmlplus/dom/expatbuilder.py", line 190, in parseString self._setup_subset(string) File "/usr/lib/python2.2/site-packages/_xmlplus/dom/expatbuilder.py", line 200, in _setup_subset if self.document.doctype: AttributeError: 'NoneType' object has no attribute 'doctype' ----------------------------------------------------------------------- I have just upgraded to Python 2.2.2 hoping that this might resolve something but with no luck. This error _only_ happens when I call parseString from within apache-->mod_python, a parseString in the interpreter works correctly. Thanks for all your help so far, Tom From hancock at anansispaceworks.com Fri Oct 4 19:04:00 2002 From: hancock at anansispaceworks.com (Terry Hancock) Date: Fri, 04 Oct 2002 16:04:00 -0700 Subject: Single Pound # comments versus Double Pound ## comments References: <20021004205602.2320.47117.Mailman@mail.python.org> Message-ID: <3D9E1E60.F737E113@anansispaceworks.com> From: Tim Peters > [Manuel M. Garcia] > > In Python code, does anyone distinguish between > starting comments with > > a single pound (#) or a double pound (##)? > > I expect they're just following the convention that # > means "this is a > useful comment" and ## means "this section is commented > out -- pretend it > doesn't even exist". I'd like to add that in Zope, when you store Python scripts on the file system, the meta-data (arguments expected, namespace bindings, etc) is stored in a block of double-commented "##" text at the top of the file. These comments are interpreted by Zope and are stripped out of the imported file. I can't comment on whether this is wise design or not, but that's how they do it. It occurs to me, in reference to a previous thread about blocked-comments, rather than line comments, that having blocks like: ### This might be a block comment in some hypothetical future version of Python. Although I'm not holding my breath. ### Might be very sensible, analogous to the """ string definitions. Since someone pointed out that unused strings are stripped out, unless they correspond to docstrings or something, this would have very similar semantics. Except that it could be more unambiguous -- such as being used to block out code even within expressions: this_is_a_dict = { 'spam':1, ### Didn't really want this part, but might later: 'ham':3, 'eggs':4, ### 'morespam':2 } The nice thing being that you don't have to muddle up the indentation or edit every single line in the section you wanted to comment out (or depend on editor gymnastics to accomplish this for you). It also seems like this would be moderately easy to implement, since """ is already caught. The only semantic difference would be that ### is always thrown out (I think this is true anyway). Despite seeing discussion about block comments on list, I can't find anything in the PEPs. Am I looking in the wrong place, or did it just not ever get that far? Would there be a "sure, send us a patch cause we don't want to do it" or a "Aaauurrghh! Get that away from me!" sort of response to this sort of thing, do you think? If it's the former, I might have a look at the sources and see if it's really as simple as I think it must be. Cheers, Terry -- ------------------------------------------------------ Terry Hancock hancock at anansispaceworks.com Anansi Spaceworks http://www.anansispaceworks.com P.O. Box 60583 Pasadena, CA 91116-6583 ------------------------------------------------------ From shalehperry at attbi.com Tue Oct 1 10:46:09 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Tue, 1 Oct 2002 07:46:09 -0700 Subject: Question on Global Modules In-Reply-To: <3D99A61C.21CC4047@rac.ca> References: <3D99A61C.21CC4047@rac.ca> Message-ID: <200210010746.09621.shalehperry@attbi.com> On Tuesday 01 October 2002 06:41, Allan Waddington wrote: > Greetings and HELP from a Newbie: > > Where do I find the os.path, cString and StringIO global module? I > didn't find them in the lib directory. > They are implemented in C, not python. Look in the python source for their source. From soerense at jorge.verwaltung.uni-mainz.de Thu Oct 31 09:42:15 2002 From: soerense at jorge.verwaltung.uni-mainz.de (Ruediger Soerensen) Date: 31 Oct 2002 15:42:15 +0100 Subject: Python and Informix References: Message-ID: Ondrej Krajicek writes: > Hello, > > I wonder if anyone uses Python to connect to Informix servers > (IDS7, IDS9). I plan to use Python in one of my > projects which involves transfers of modest loads of data > (personal information of users) from Informix > into Active Directory. Active Directory bindings > in Python work quite good (excellent job boys!) > but what troubles me is the second part of the process, > the Informix connectivity. > > According to http://starship.python.net/crew/sturner/informixdb.html, > the latest informixdb is from 30 November 1999, which is > nearly 2 years old. Does it still work ? Has anyone > any experience with it ? Is it usable for serious work ? > I'm still looking for some hints, tips or resources. Well.... it works, sort of. We are using informixdb in a production environment with several informix server versions (7.xx, 9.xx) on HP-UX, Solaris and Linux for 2-3 years now. I had to fiddle around with S. Turner's code to get stored procedures to work, and Date/Time fields were an issue. For me, the most difficult work was to compile the whole thing. Still no luck in producing a thread-safe version of _informixdb.so which is needed for zope. Turner's code has a surprisingly small footprint and works very well, I have just finished a script that does about 15000 queries, each of them returning one row of data. Time needed to execute about 2 minutes. My knowledge of esql/c is too limited so I cannot help much in improvement and/or further development. best regards, R?diger From sholden at holdenweb.com Thu Oct 3 16:17:02 2002 From: sholden at holdenweb.com (Steve Holden) Date: Thu, 3 Oct 2002 16:17:02 -0400 Subject: Annoyed - Python 2.2.1 BUG in calendar module References: Message-ID: "Kaleb Pederson" wrote in message news:mailman.1033664407.19258.python-list at python.org... > Ok. I just finished a PyQt date widget wherein I created a wrapper > around the calendar module to use as my backend. The Calendar module, > however, doesn't explicitly say that it doesn't work for dates pre-1970. > The best case is that this is a DOCUMENTATION BUG. I would prefer to > see a more powerful date module that starts at the beginning of the > Gregorian calendar. > > What the documentation does say: > > From http://www.python.org/doc/current/lib/module-calendar.html: > > weekday(year, month, day) - Returns the day of the week (0 is Monday) > for year (1970-...), month (1-12), day (1-31). > I should say this is a pretty explicit statement that dates can't be before 1970. > // I figured that was fine, I can avoid using that function in my > wrapper > > timegm(tuple) - An unrelated but handy function that takes a time tuple > such as returned by the gmtime() function in the time module, and > returns the corresponding Unix timestamp value, assuming an epoch of > 1970, and the POSIX encoding. In fact, time.gmtime() and timegm() are > each others' inverse. > And this promises you that dates are based on a starting point of 1970. RTFM ;-) > // Okay, I can avoid that too, especially since it is "unrelated" > > I probably should have got a clue based on the above, but I didn't.... > We all have our blind spots :-) > Well, anyone have a different calendar module that isn't limited like > the Python one that happens to be available? I would prefer one that > was API compatible. > > If not, I'm off to write my own. > It's hard to say what you need from calednar. It would probably be worth a look at mxDateTime and then snitching the code from calendar to build around it. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- From see_reply_address at something.invalid Wed Oct 9 19:01:53 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Thu, 10 Oct 2002 12:01:53 +1300 Subject: Mixin class data References: Message-ID: <3DA4B561.1040906@something.invalid> Paul Moore wrote: > I'd rather not make it a requirement of > this particular mixin that the derived class call its __init__ routine Why not? It seems perfectly reasonable to me that if you inherit something you should be responsible for making sure it's initialised properly. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From kstc at box43.pl Tue Oct 8 16:41:31 2002 From: kstc at box43.pl (Krzysztof Stachlewski) Date: Tue, 8 Oct 2002 22:41:31 +0200 Subject: Metaclasses? References: Message-ID: "Thomas Heller" wrote in message news:anvbm0$hu6gd$1 at ID-59885.news.dfncis.de... > Google is your friend: > > http://www.google.de/search?q=python+metaclasses OK. I found PEP252 and 253. I didn't know metaclasses are new to Python2.2 and expected to find something in Data Model section of Language Reference. Stach From ark at research.att.com Thu Oct 10 13:57:34 2002 From: ark at research.att.com (Andrew Koenig) Date: Thu, 10 Oct 2002 17:57:34 GMT Subject: Concrete classes -- stylistic question References: Message-ID: Aahz> You can also do the dirt-simple: Aahz> class xy: pass Aahz> class rtheta: pass Aahz> foo = xy(); foo.x,foo.y = 1,2 Aahz> I'm not recommending this, of course. You can also do the even more Aahz> dirt-simple: Aahz> class Record: pass Aahz> foo = Record(); foo.x,foo.y = 1,2 Aahz> It all depends on where you want your complexity to lie. Understood. I was looking for a more compact notation for constructing such objects. -- Andrew Koenig, ark at research.att.com, http://www.research.att.com/info/ark From see_reply_address at something.invalid Wed Oct 16 18:33:04 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Thu, 17 Oct 2002 11:33:04 +1300 Subject: realtime design References: <013goa.m8c.ln@boundary.tundraware.com> <3DAC94DD.9070609@something.invalid> Message-ID: <3DADE920.2030608@something.invalid> Bengt Richter wrote: > It sounds a bit funny to me to be worrying about "too long" (presumably > _real_ time?) in a realtime *simulator* (especially after saying performance > is no issue). I guess you're not simulating time itself in your realtime simulator? I've been wondering about that, too. If you're seriously trying to simulate the behaviour of a real-time system, you want the timeout to occur after a certain amount of *simulated* time, not actual time. To be able to do that, your simulator needs to have a notion of how much simulated time each operation takes, and keep track of it. So, before going any further, the question which must be answered is: how accurately does the behaviour of the simulated system in simulated time have to reflect the behaviour of the real system in real time? -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From bokr at oz.net Tue Oct 8 17:57:38 2002 From: bokr at oz.net (Bengt Richter) Date: 8 Oct 2002 21:57:38 GMT Subject: SOT : & in XML-documents References: Message-ID: On Tue, 08 Oct 2002 18:59:59 GMT, "Thomas Weholt" <2002 at weholt.org> wrote: >I'm trying to parse an old fileformat into xml. The problem is that the >character & appears from time to time in the original file. Tried to put > What is your "old fileformat" ? Regards, Bengt Richter From travis at enthought.com Sat Oct 19 16:58:47 2002 From: travis at enthought.com (Travis N. Vaught) Date: 19 Oct 2002 13:58:47 -0700 Subject: Books on scientific/numeric programming in Python? References: <3DB005F8.CD96D868@bio.gla.ac.uk> <3DB16D77.38BC7C80@bio.gla.ac.uk> Message-ID: <7044f080.0210191258.2ed1d1e0@posting.google.com> Francis Burton wrote in message news:<3DB16D77.38BC7C80 at bio.gla.ac.uk>... However, I had in mind something > much more like a cookbook - not so much a "Numerical Recipes in Python" > (although that would be quite nice!) as a collection of more general > purpose code snippets and modules that show how Python idioms could be > applied in the scientific/numerical field. So it would include lots of > database, graphical and GUI examples and maybe have rather less of a > web slant. I like the "Python Cookbook" style of exposition. > > Francis There is a tutorial (pdf of powerpoint presentation) with some coverage of this here: http://www.scipy.org/site_content/tutorials/scipy_tutorial_overview Travis From k.robert at gmx.de Wed Oct 2 15:28:03 2002 From: k.robert at gmx.de (Robert) Date: Wed, 2 Oct 2002 21:28:03 +0200 Subject: Merging lists has made my brain hurt. References: <3D9B1953.3030109@moving-picture.com> Message-ID: <3d9b4acd$1$155$9b622d9e@news.freenet.de> > lol = [ > ['aaa', 'bbb', 'ccc'], > ['bbb', 'ccc', 'ddd'], > ['ccc', 'ddd', 'eee'] > ] > > I want to merge the three lists into a single list that only contains > the strings present in all three lists. In the above case I want to end > up with > ['ccc'] using 'reduce' would be nice functional style programming. however calls & copying, creating, slicing, modifying lists are very expensive while running is so-la-la. so a simple breaky 2D-loop would almost outperform at minimum cons-ing and still read best for newbies: common=[] for e in lol[0]: for l in lol: if e not in l: break else: common.append(e) #(the else belongs to for!) #in certain cases when NX&NY are both huge, a dict would gain O(2) speed but only if you play economically with one dict! : common=[] d={} for l in lol: for e in l: if e in d: d[e]+=1 else: d[e]=1 n=len(lol) common = [e for e in d if d[e]==n] print common #(slightly improveable); but if you have your input sub-lists occasionally prepared as dicts (sets in the future), the first solution is again prefereable for small & huge stuff without code modification Robert From its1louder at yahoo.com Tue Oct 8 15:13:15 2002 From: its1louder at yahoo.com (Tom) Date: 8 Oct 2002 12:13:15 -0700 Subject: Spectrogram plotting References: <7557b51f.0210080127.7ffc6bb6@posting.google.com> Message-ID: <90f2d9db.0210081113.ab4d2c4@posting.google.com> Fernando P?rez wrote in message news:... > seh wrote: > > > I would like to sample some data from the soundcard into a vector. > > Then process the data ex. take an FFT. Then plot the data intensity > > modulated vertically on the screen. Then sample some new data, process > > and plot them near to the previous data and so on. > > > > Anybody has some code to do this? Peferably in Tkinter but wxPython is > > also of interest. > > > > Svein-Erik > > http://scipy.org has all the pieces you need. You can also just use > Numeric+Gnuplot, but the gnuplot interface is a bit clunky. > > Cheers, > > f. I also use spectra and plot the FFT. here's what I found out. I think scipy is ok, but it is rough and doesn't seem to work with python 2.2. I like it for making quick plots at the commandline. I like dislin a little better for 2-D plots. But ultimately, I have not been really pleased with any plotting packages for python. I think Chaco (from the scipy people) has the potential to be a really good cross platform package, but not for probably a year, it just got started. I'm also waiting to see how pyncl turns out, that would be super cool for anyone interested in powerful cartography in addition to typical plotting. In the end I've given up on python plotting packages for now. I use the wxPython activexwrapper module. I find this works really well. The Visual basic activex controls that I have been using a long time (the national instruments Component works or whatever they call it now) are easily dropped into wxpython guis. I've created a class called CWPlotPanel that is returned by MakeActiveXClass() function. BTW it is interesting that Python seems to have better activex support then Borland C Builder, I never got these controls to work there. the disadvantage is basically that I've abdicated cross platform functionality to use COM. Another disdvantage is that a bug seems to crash the program when I try to create cursor objects for the plot and then resize the plot. So I don't use cursors, which is a shame, but not a tragedy. Since I need to use COM libraries anyway win32 only isn't a problem for me. I need com because I am using instruments that return spectra (e.g., an FTIR) in the *.spc file format. This is a complicated format and the best high level library for reading them that I know of is the thermo galactic GSPCIO com library. Anyway, my instrument spits out a *.spc file. I use the python win32com.client lib to access the data in the spc file. Then I use the Numeric FFT module: def performFFT(self,): """Calculate the FFT of the interferogram.""" fftdat = abs(real_fft(self.spcf.YData, n = SpcIO.NumPoints,)) return fftdat I make a plot control class called AXPlotControl with MakeActiveXClass() and then I instantiate two plot objects - one for the interferogram, and one for the spectrum which is the former's fft. My understanding of MakeActiveXClass() is that it is returning a class that is derived from up to three things, a wxWindow, the activex control's CoClass, and potentially an eventclass. In this case the event class is the object itself and the coclass is registered as guiModule.CWGraph. AXPlotControl = MakeActiveXClass(guiModule.CWGraph, eventObj = self) self.ifgramAXCtrl = AXPlotControl(self.notebook1, -1) self.specAXCtrl = AXPlotControl(self.notebook1, -1) (My gui is structured around a notebook with a log page that spits out *.spc header info, the intereferogram plot page, and the spectrum plot page.) The win32com support is so seamless that passing arrays from the GSPCIO COM library to the the python numeric module to the activex control requires nothing special at all, it just works. I can show you some example code if you are interested. It is still a work in progress, but it basically works now (except cursors, confound it). From magnus.heino at pleon.sigma.se Sun Oct 13 09:39:50 2002 From: magnus.heino at pleon.sigma.se (Magnus Heino) Date: Sun, 13 Oct 2002 15:39:50 +0200 Subject: Swedish characters in Python strings References: <7d546104.0210120944.17486548@posting.google.com> <0Icq9.2091$MV.88372@newsc.telia.net> Message-ID: > check the locale settings; to minimize the pain, make sure you use > an 8-bit encoding (e.g ISO-8859-1) and not a designed-for-internal- > use-only variable-width encoding like UTF-8. Still, all new RH8 installs do use utf-8, and there must be a good reason for that, and I guess its something they will do for a while now... > with UTF-8, your operating system is messing things up before Python > gets a chance to look at the characters (most likely, Python gets 6 > characters from the keyboard, and sends 6 characters to the console). Is that the reason in this case? This is RH8.0, en_US.utf-8 Python 2.2.1 (#1, Aug 30 2002, 12:15:30) [GCC 3.2 20020822 (Red Hat Linux Rawhide 3.2-4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import MP3Info >>> title = getattr(MP3Info.MP3Info(open('file.mp3', 'rb')), 'title') >>> title 'K\xf6ttbullar i n\xe4san' >>> print title K?ttbullar i n?san >>> type(title) >>> print title K?ttbullar i n?san >>> print u'K\xf6ttbullar i n\xe4san'.encode('utf-8') K?ttbullar i n?san >>> > (avoiding RedHat 8.0 might also help. based on the kind of bugs I've > experienced this far, 8.0 might qualify as the worst unix-like operating > system ever released...) Besides this stuff, I think it's really nice.. -- /Magnus From claird at lairds.com Sun Oct 20 13:43:30 2002 From: claird at lairds.com (Cameron Laird) Date: Sun, 20 Oct 2002 17:43:30 -0000 Subject: hostid? References: Message-ID: In article , Skip Montanaro wrote: > Lance> Thanks all for the advice.. but I'm still not getting the hostid > Lance> to which I refer. At work we use the Flexlm license manager. It > Lance> requires users to send us the hostid of their computer. For > Lance> example, the computer on which I write this has hostid > Lance> 00d009b88fca and the hostname is the name of my computer which is > Lance> MYNEWBOX. > >I seem to recall that Sun's had a CPU-specific hostid. I just checked on a >Sun I have access to. It has a "hostid" command. So does Linux, at least >the Mandrake and Red Hat systems to which I have access. My Mac (OS 10.2.1) >doesn't.) > >Why not just encapsulate it in a function? > > def hostid(): > return os.popen("hostid").read().strip() > >If executing the hostid command isn't an option, you could write a little >extension module which calls the gethostid() library function. Both Linux >and Solaris seem you have it. . . . Right. hostid is NOT an artifice of FlexLM; it has a distinguished pedigree that goes back reasonably far in Unix circles. While POSIX.1 does not include hostid (or gethostid()), they're present in ISO/IEC 9945-1:1990. They're part of SVr4. On the other hand, I think HP-UX has dropped hostid. Did someone in this thread make the point that, if the requirement is to meet some expectation of the commercial FlexLM product, then it's natural to look first to Globetrotter (FlexLM's vendor) for the necessary information? That's my instinctive position. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From ark at research.att.com Fri Oct 18 15:41:38 2002 From: ark at research.att.com (Andrew Koenig) Date: Fri, 18 Oct 2002 19:41:38 GMT Subject: repr(x) == repr(y) <=> x == y AND eval(repr(x)) == x References: Message-ID: Thorsten> This relies on two assumptions: Thorsten> 1. repr(x) == repr(y) <=> x == y Thorsten> 2. eval(repr(x)) == x (for further processing) Thorsten> Does anyone know under which circumstances 1. and 2. are Thorsten> wrong? 1. is not true for x==3, y==3.0, because x==y and repr(x)!=repr(y). 2. is not true for x==repr, because eval(repr(repr)) raises SyntaxError. -- Andrew Koenig, ark at research.att.com, http://www.research.att.com/info/ark From rhymes at dot.com Wed Oct 9 15:33:29 2002 From: rhymes at dot.com (Rhymes) Date: Wed, 09 Oct 2002 21:33:29 +0200 Subject: GUI problem References: <369fc45d.0210081239.57a5153a@posting.google.com> Message-ID: On Tue, 08 Oct 2002 22:23:02 GMT, Alex Martelli wrote: >Rempt's "GUI Programming with Python: QT Edition" is reasonably >tutorial and freely available at http://www.opendocspublishing.com/pyqt/ -- is there a downloadable version of such book? -- Rhymes (rhymes_NOSPAM_ at myself.com) http://www26.brinkster.com/rhymes http://bw-crema.blogspot.com From jaqui at shaw.ca Mon Oct 21 12:50:57 2002 From: jaqui at shaw.ca (Jaqui) Date: Mon, 21 Oct 2002 16:50:57 GMT Subject: How do I invoke IE browser from Python on Mac OS X? References: Message-ID: <3DB43104.2030206@shaw.ca> Skip Montanaro wrote: ~snip~ I suspect perhaps there's something > special about URLs so that they are only opened with the default browser. > that isn't really a bad thing. I could not run the script you are working on if it requires ie, not available on linux.(besides my not liking ie and not wanting it on my comp ) default browser is a more portable solution than requiring a specific browser From johnroth at ameritech.net Fri Oct 4 10:42:57 2002 From: johnroth at ameritech.net (John Roth) Date: Fri, 4 Oct 2002 10:42:57 -0400 Subject: [Python-Dev] PEP239 (Rational Numbers) Reference Implementation and new issues References: <3D9CF2ED.3020507@something.invalid> <3D9CFA77.19D2944A@alcyone.com> Message-ID: "Chad Netzer" wrote in message news:mailman.1033702569.6466.python-list at python.org... > > My comments about 0/0 were somewhat tongue-in-cheek, so don't take them > too seriously. :) > > As Tim Peters pointed out, there is often a convention in the numerical > field to declare (for the purposes of floating point calculation) that: > > 1.0/0.0 = Inf > 0.0/0.0 = NaN > > A useful question is what to do with the equivalent rational > expressions? Should the floating point conventions be followed? > Should there even be the equivalent of a NaN or Inf? Do they apply > only when memory limits, or lossy conversions, come into play? Well, my first impression was that when you get into the limit thing, you're talking about mathematics that is usually applied to physics or other essentially continuous quantities, not discrete quantities. > My gut instinct is that both 1/0 and 0/0 should simply throw divide by > zero, and that NaN and Inf do not exist. If they do exist, they are > defined directly by subclasses of the rational type (and are NOT > created by any simple, defined expression, only by practical limits). > At least that should be the default; like floating point, there may be > a need to override the exception throwing behavior (for array > operations, etc.) But this complicates things, and since these are not > performance critical, I think it best to keep things simple and > consistent. Those working with large numbers of rationals may just > have to deal with the possibility of exceptions, and perhaps > precondition there data. (A compromise might be a DividedByZero > object, that is distinct from a Nan or Inf) I think keeping it simple is exactly right. I don't have any clear idea of how to make it values like NaN and Inf 'right,' so I'd go with just throwing an exception for anything that attempts to get a value from a rational with a zero denominator. If someone needs a different behavior, they can encapsulate it and catch the (hopefully rare) exception. John Roth From aahz at pythoncraft.com Wed Oct 2 20:17:49 2002 From: aahz at pythoncraft.com (Aahz) Date: 2 Oct 2002 20:17:49 -0400 Subject: OT: Mandrake 9.0? Message-ID: Mandrake just sent me an offer to upgrade to 9.0 (I currently have 8.1) for 15% off if I pre-order. Anyone have an opinion on whether I should upgrade now or wait for 9.1? I'm a tiny bit leery because I had some problems installing 8.1 in the first place. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From cliechti at gmx.net Fri Oct 18 15:55:59 2002 From: cliechti at gmx.net (Chris Liechti) Date: 18 Oct 2002 21:55:59 +0200 Subject: repr(x) == repr(y) <=> x == y AND eval(repr(x)) == x References: Message-ID: Thorsten Kampe wrote in news:aopma6$odeho$1 at ID- 77524.news.dfncis.de: > Hi, > > I'm using dictionaries for some "very generalized programs". This > means that I cannot tell in advance if all the items I'm operating on > are hashable. The "trick" that came to my mind was to use repr(x) as > the key (instead of x). > > This relies on two assumptions: > > 1. repr(x) == repr(y) <=> x == y > > 2. eval(repr(x)) == x (for further processing) > > A wise man once said to me: > ,--- >| You're FAR more likely to meet objects where you can't count on >| eval(repr(x)) == x, than non-hashable objects. > `--- > > Does anyone know under which circumstances 1. and 2. are wrong? 1) >>> class A: ... def __init__(self, v): ... self.v = v ... def __cmp__(self, other): ... return cmp(self.v, other.v) ... >>> a = A(7) >>> b = A(7) >>> a <__main__.A instance at 0x010F6970> >>> b <__main__.A instance at 0x010F4D08> >>> a==b 1 >>> repr(a) == repr(b) 0 2) many user object either use repr in a custom way / not emmiting python syntax or they don't define __repr__ at all (see 1 for such an example) what you should do is to use the pickle module to convert instances to strings and back. chris -- Chris From max at alcyone.com Mon Oct 14 17:30:15 2002 From: max at alcyone.com (Erik Max Francis) Date: Mon, 14 Oct 2002 14:30:15 -0700 Subject: What dir. should Jython be installed in? References: <3daa230b@monitor.lanset.com> Message-ID: <3DAB3767.5BDD626@alcyone.com> Gerhard H?ring wrote: > It doesn't really matter much, but conventional places to put software > like JDKs, Jython, etc. are /opt and /usr/local. My Jython > installation, for example is in /usr/local/jython-2.1. It varies from operating system to operating system and distribution to distribution, but /opt usually is intended for vendor-provided optional software modules. The proper place to put locally installed software is under /usr/local (which is almost always the default for most installation). -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ Peace with a cudgel in hand is war. \__/ (a Portugese proverb) Bosskey.net: Counter-Strike / http://www.bosskey.net/cs/ A personal guide to Counter-Strike. From kp at kyborg.dk Tue Oct 1 11:32:21 2002 From: kp at kyborg.dk (Kim Petersen) Date: Tue, 01 Oct 2002 17:32:21 +0200 Subject: Decimal arithmatic, was Re: Python GUI app to impress the boss? References: Message-ID: <3D99C005.7010508@kyborg.dk> Grant Edwards wrote: > In article , Mark Charsley wrote: > > >>>Usually, in the "canned" systems I've seen, those 3 for a >>>buck deals are supported by allowing three to five decimal >>>places rather than just two for amounts. Results come out >>>much as you are expecting there. >> >>The system a previous company wrote said that "if they've bought 3 >>40p items these give them a discount of 20p". > > > But, standard practice around here is that the "3 for a dollar" > price is good on quantities of less than three. (IOW the unit > price is 1/3 dollar). I have seen instances where you have to > buy 3 to get the discount but IME that's rare. (assuming IME is In My Environment) might be - but around here - All shops (with possible exceptions (i've never seen it)) sell only (multiple) quantities of 3 at the discount *even* if 2 will sell at a higher price.... > From see_reply_address at something.invalid Mon Oct 7 19:05:47 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Tue, 08 Oct 2002 12:05:47 +1300 Subject: How to get the mouse cursor position in TK? References: Message-ID: <3DA2134B.50100@something.invalid> Martin Franklin wrote: >> I want to pop-up an whole >> new WINDOW, but the Tk() Objects dont know the gm place. So how can I place >> tk Objects, and NOT widgets inside a parent? You can position a Toplevel widget on the screen using the wm_geometry method, e.g. Python 2.2 (#1, Jul 11 2002, 14:19:37) [GCC 3.0.4] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import Tkinter >>> tk = Tkinter.Tk() >>> tk.wm_geometry("+10+20") positions the main window 10 pixels from the left of the screen and 20 from the top. The general form of the string passed to wm_geometry is: x++ -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From martin at v.loewis.de Wed Oct 16 09:19:27 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 16 Oct 2002 15:19:27 +0200 Subject: where is idle? (solaris) References: Message-ID: nobody writes: > Where is idle, on a Solaris installation? You need to install it separately. One approach should be "python setup.py install" in the Tools/idle directory; this is rarely tested and may fail. If so, you need to copy all files manually to where you want them. Regards, Martin From tim.one at comcast.net Fri Oct 18 15:59:23 2002 From: tim.one at comcast.net (Tim Peters) Date: Fri, 18 Oct 2002 15:59:23 -0400 Subject: Most efficient method to search text? In-Reply-To: Message-ID: [Michael Hudson, searching for words] > ... > Indeed, my code canes re when the wordlist gets long. Here's some > numbers ... > ... > So roughly linear behaviour from re, n-independent behaviour from my > code. Isn't it nice when things do what you expect? When you're young, it can seem that way. At my age, it mostly makes one nervous, waiting for the other and always larger and much smellier foot to fall . > On the other hand, the "compiler" code I posted yesterday consumes > vast gobs of memory -- trying to compile a 10000 long list of random > words got the OOM killer into action. A version using lists seems > slightly better in this respect, though slower in execution. Which is, of course, the traditional tradeoff between NFA and DFA approaches -- in bad cases you can pay in memory and preprocessing time due to exponential state explosion, or you can pay at runtime. I see Bengt discovered how to use dicts for this, and that's probably what you'll use in the future too . For the more general case of lexing, you're searching for patterns (like r'[A-Za-z_]\w*'), and twisting a dict gets at best obscure. There's a large literature now on compromise approaches, building only the parts of the DFA that the target string actually needs to explore, in a dynamic way. This sounds horribly expensive at first glance (don't think about that mixing eyes with ears doesn't make sense), but in some practical cases there are exceedingly clever ways to "fake it" with a handful of machine-level instructions per character, using integers as bit vectors representing the *set* of NFA nodes currently active. Gonzo speeding of all arguably common cases of pattern-matching is a lifetime job. Although there's nothing unique about pattern-matching in that ... learning-to-live-with-fast-enough-leaves-more-time-for-life-ly y'rs - tim From florian.proff.schulze at gmx.net Thu Oct 3 12:57:32 2002 From: florian.proff.schulze at gmx.net (Florian Schulze) Date: Thu, 3 Oct 2002 18:57:32 +0200 (Westeuropäische Sommerzeit) Subject: Printing with python In-Reply-To: <3D98C642.3090003@trisoft.com.pl> References: <3D98C642.3090003@trisoft.com.pl> Message-ID: On Mon, 30 Sep 2002 23:46:42 +0200 Grzegorz Makarewicz wrote: > Florian Schulze wrote: > > Hi! > > > > I would like to know what solutions exist for printing (on paper) with > > python. Preferable would be a crossplatform approach, but only for > Windows > > would be good enough. I also thought about using the reportlab pdf lib > and > > using the free Acrobat Reader for preview and printing. It has a nice > API > > and I don't think it will be too hard to send it to Acrobat Reader. > > > > Any suggestions or thoughts about this? > > > > Regards, > > Florian Schulze > > > > > > > > try DDE connection to AR: > > import os > import win32ui > import dde > > fname=os.path.join(os.getcwd(),'demo.pdf') > server = dde.CreateServer() > server.Create("PyAcroview") > > conversation = dde.CreateConversation(server) > > conversation.ConnectTo("acroview", "control") > conversation.Exec("[DocOpen(%s)]" %fname) > > -- > You can print, select pages and documents, ... > > mak > > I played with it a bit, but couldn't get it working. If Acrobat Reader isn't already open ConnectTo fails. I tried to work around that by starting Acrobat Reader first, but this produced other problems. I downloaded some DDE documentation about Acrobat and tried various commads including your DocOpen, but most of them just don't work. I found out later that I had to put the filename into "s, when it contained a space. I think I will use os.startfile for now, as this is the easiest way, without messing with registry values to get the AcroRD32.exe path etc. If you have some advice it would still be greatly appreciated though. Thanks and regards, Florian From phr-n2002b at NOSPAMnightsong.com Tue Oct 1 18:29:37 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 01 Oct 2002 15:29:37 -0700 Subject: patch in Python? References: <7xit0l3koi.fsf@ruckus.brouhaha.com> Message-ID: <7xy99h23ou.fsf@ruckus.brouhaha.com> Gerhard H?ring writes: > > > > [1] http://www.tc.umn.edu/~ringx004/mapm-main.html > > > ... > > > - How does this compare to gmpy? > > ... one of the requirements is a BSD-ish license, as in the > end this will be used for the NUMERIC type of pyPgSQL. If it's going to > be useful for other purposes, that's a nice side-effect. MAPM doesn't have a BSD-ish license--you're not allowed to distribute modified versions except as the original plus patches. I'd read that as meaning you're not allowed to ship pre-compiled binaries. GMP is LGPL'd, which means you're free to ship modified versions, binaries (as long as you offer the library source), etc. That sounds way preferable to MAPM. From mwh at python.net Tue Oct 8 07:18:08 2002 From: mwh at python.net (Michael Hudson) Date: Tue, 8 Oct 2002 11:18:08 GMT Subject: Misc questions about type objects and Python 3.0 References: Message-ID: Standard caveat: I don't think there are many fixed plans for "Python 3.0". I might well prove to be totally wrong with this post. Carl Banks writes: > 1. Is it the plan that Python 3.0 be binary compatible with Python > 2.x? Depends what you mean. It's unlikely to be perfectly compatible. None of 2.0, 2.1, 2.2 or 2.3 from current CVS are totally binary compatible. But I don't think wild changes are expected. "Most" extension modules will keep working, probably with a warning. > 2. If it isn't (I'm guessing it will be), is it the plan to keep > reference counting? I'd be amazed if it went. > It seems to me that getting rid of reference counting might be > the first step to getting rid of the GIL. It seems very unlikely the GIL is going away (at least, that's want Guido said at EuroPython). > 3. The docs say types choose their member resolution order (?), but > I'm wondering if that's just a temporary hack to support both > old-style and new-style classes. Don't think so. > After old-style classes are dropped, will MRO be fixed for all > types? If I had to guess, no. > (And is it really that useful for it to be customizable?) Dunno. > 4. What is the point of having both tp_base and tp_bases in the type > structure? I have no idea. Probably historical reasons of one sort or another. > 5. What's the deal with unification of numeric types? What's expected > or planned or hoped for in 3.0? I think there are PEPs you can read about this -- 237, 238 and 239, maybe? In that range, numerically speaking, anyway. Cheers, M. -- You owe The Oracle a TV with an 'intelligence' control - I've tried 'brightness' but that didn't work. -- Internet Oracularity #1192-01 From eric.brunel at pragmadev.com Wed Oct 16 11:15:51 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Wed, 16 Oct 2002 17:15:51 +0200 Subject: Parsing SGML document in Python program References: Message-ID: Ilya Shambat wrote: > Hello all, > > I need to be able to parse an SGML document in a Python program. I > need to know the syntax on how to do that. The project involves using > a DTD, passed as a command line argument, to read all the SGML files > that exist in a directory. Does anybody know how this is done? There is a sgmllib module in the standard library, but it's not a full SGML parser. SGML has a lot of funky possibilities that are quite hard to parse and that were apparently not considered in the sgmllib module. I never used it, but as far as I can see from the docs, it doesn't use a DTD, so it's really not a SGML parser (XML seems to live well without a DTD, but doing so in SGML may be considered as heretic ;-). It may however be usable if your documents are really simple. I had once to do that and I couldn't find a parser directly usable in Python. Maybe it has changed (just check the Vaults of Parnassus for it). The solution I used at the time was to rely on an external parser that gave easy to parse results. The one I used was nsgmls, part of James Clark's SP project. You may find it @ http://www.jclark.com/sp/ ; just test it and you'll see that its output is really easy to get back into Python. HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From bromden at gazeta.pl Tue Oct 22 16:04:20 2002 From: bromden at gazeta.pl (bromden) Date: Tue, 22 Oct 2002 22:04:20 +0200 Subject: maintaining order with cgi References: <40a8aa92.0210220509.6f9279ac@posting.google.com> <3DB5A9C0.430F886B@alcyone.com> Message-ID: <3DB5AF44.3030000@gazeta.pl> > you. As far as I know, the browser gives it no significance. furthermore, the order of fields may depend on a browser, and so relying on it seems to be a wrong approach Daniel, consider if you really need the order of fields, this sounds pretty strange ... -- bromden GCS d- s+: a- C++$ UL(++++) P-- L++ E--- W+(++) N++ o? K? w(++) !O M-- !V PS+ PE++ Y+ PGP+ t--- 5? X- R- tv-- b++>+++ DI- D- G e+++ h-- r- y? From sholden at holdenweb.com Mon Oct 7 16:53:02 2002 From: sholden at holdenweb.com (Steve Holden) Date: Mon, 7 Oct 2002 16:53:02 -0400 Subject: exec(threads) References: <200210071441.49984.scjuonline@web.de> <04a901c26e02$4b686d00$6300000a@holdenweb.com> <200210072140.55174.scjuonline@web.de> Message-ID: <067101c26e43$88428440$6300000a@holdenweb.com> "JS" scjuonline at web.de wrote: > > So when you said "no processes are created" you meant "I don't get > > threads"? > > "No Processes" means, I get threads. (as expected) > So, what else is wrong? > > I'm not sure what the problem is yet, so can't yet do much to > > help you solve it! Although you posted the code you didn't say how it > > failed to run on which platforms. Your original post said you saw five new > > processes created on Linux, and you then imply that the problem lies with > > Linux. Is this actually the case or am I misunderstanding? > > The code I posted was just a dirty testing hack. > This code shows, that 5 processes are created under linux. Linux will list each thread as a separate process. What part of the performance of your code is unsatisfactory (*besides* seeing five processes on Linux which you don't see on other OSs)? > Or at least I think so. But if a 'ps' gives me > > PID TTY TIME CMD > ... > 2543 pts/9 00:00:00 go.py > 2544 pts/9 00:00:00 go.py > 2545 pts/9 00:00:00 go.py > 2546 pts/9 00:00:00 go.py > 2547 pts/9 00:00:00 go.py > > they should be processes, right? > Process, thread, it depends on the particular platform: some OSs show threads as separate entries in the process list, some don't. > What is used if I call start_new_thread()? > Is it a user-level library? If yes, which one? > Well, you could read the code. I'm still waiting to hear how your program is broken (I suspect it isn't). Does the program do the same thing on each OS? What's the *real* problem here? regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- From jepler at unpythonic.net Sun Oct 20 09:29:27 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Sun, 20 Oct 2002 08:29:27 -0500 Subject: Speeding up a script -- looking for ideas In-Reply-To: <87fzv15vxp.fsf@flibuste.net> References: <87fzv15vxp.fsf@flibuste.net> Message-ID: <20021020082917.B2488@unpythonic.net> On Sun, Oct 20, 2002 at 10:57:54AM +0200, William wrote: > without looking at your algorithme, it's typical think where psyco will > help you : > > without psyco : > > [(13832, 2, 24), (13832, 18, 20)] > > Time's up! 16.6103349924 seconds have elapsed > EEEEEEEEEnnnnnnnnnnddddddddd Well, looking at the algorithm, there's no reason to loop on values of c, then loop on values of a, then loop on values of b. Why not loop on c, then on a, then find whether there's a value of b that will satisfy the condition? Your program on my system, no psyco: Time's up! 6.24721693993 seconds have elapsed My program on my system, no psyco: (13832, [(2, 24), (18, 20)]) 1 real 0m1.645s (both on 10000-20000) from __future__ import generators r = range def f(rr, n): for c in rr: l = [] for a in r(1, int(c**(1/3.0))+2): a3 = a**3 if a3 > c: break b = int((c - a**3)**(1./3)+.5) if b < a: break #print a, b, c if a**3 + b**3 == c: l.append((a, b)) if len(l) == n: yield c, l break def main(): count = 0 for item in f(r(10000, 20000), 2): count = count + 1 print item print count main() From itamar at itamarst.org Sun Oct 6 13:51:32 2002 From: itamar at itamarst.org (Itamar Shtull-Trauring) Date: Sun, 6 Oct 2002 13:51:32 -0400 Subject: ANN: Twisted 0.99.3 - release candidate for Twisted 1.0 Developer Platform Message-ID: <20021006135132.58377c00.itamar@itamarst.org> The Twisted team is proud to announce Twisted 0.99.3, our release candidate for Twisted 1.0 Developer Platform. For more information, visit http://www.twistedmatrix.com, join the list at http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-python or visit us on #twisted at irc.freenode.net (also known as irc.openprojects.net). What is Twisted? ================ Twisted is an event-based framework for internet applications. It includes a web server, a telnet server, a chat server, a news server, a generic client and server for remote object access, and APIs for creating new protocols and services. Twisted supports integration of the Tk, GTK+, Qt or wxPython event loop with its main event loop. The Win32 event loop is also supported, as is basic support for running servers on top of Jython. Twisted works with Python 2.1 and Python 2.2. Twisted even supports the CVS versions of Python, so it is ready for Python 2.3. Twisted currently supports the following protocols, all implemented in pure python, most of them as both servers and clients: - SSH - FTP - HTTP - NNTP - SOCKSv4 (server only) - SMTP - IRC - telnet - POP3 - AOL's instant messaging TOC - OSCAR, used by AOL-IM as well as ICQ (client only) - DNS - MouseMan - finger - Echo, discard, chargen and friends - Twisted Perspective Broker, a remote object protocol - XML-RPC What's new in 0.99.3 ==================== - More fixes for HTTP - Continued work on Woven web framework - Got rid of remaining uses of deprecated APIs From aahz at pythoncraft.com Thu Oct 3 13:44:11 2002 From: aahz at pythoncraft.com (Aahz) Date: 3 Oct 2002 13:44:11 -0400 Subject: Decimal arithmetic, was Re: Python GUI app to impress the boss? References: Message-ID: In article , Tim Peters wrote: > >i'm-old-i-don't-need-to-be-liked-ly y'rs - tim Can I be you when I grow up? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From dsavitsk at e-coli.net Thu Oct 10 13:17:57 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Thu, 10 Oct 2002 17:17:57 GMT Subject: Another Python and Apache question References: Message-ID: <9Dip9.1940$qW4.715371@newssrv26.news.prodigy.com> "Gerhard H?ring" wrote in message news:slrnaqbdti.19u.gerhard.haering at lilith.my-fqdn.de... > dsavitsk wrote in comp.lang.python: > > I am asking this not knowing much of the background that I should, so I am > > just fishing for opinions ... > > > > Is it possible to write an Apache module in Python, > > mod_python exposes some of the Apache internals. > > > and is it even worth doing? Is there some sample code out there? > > I'd recommend you check out mod_python and if you really want to roll > your own solution, check with the mod_python folks on their mailing > list first. > > Which problem are you trying to solve, anyway? I was actually thinking of writing a mod_vb or mod_com to use some vb dlls. Why would i want to do this? Not sure really. Chance to learn about Apache I suppose. From skip at pobox.com Thu Oct 3 14:15:09 2002 From: skip at pobox.com (Skip Montanaro) Date: Thu, 3 Oct 2002 13:15:09 -0500 Subject: mailbox module broken! In-Reply-To: References: Message-ID: <15772.35117.817611.12236@localhost.localdomain> Stuart> The following trivial code to read through a unix mailbox skips Stuart> a little over 100 messages in the mailbox at Stuart> http://www.bmsi.com/python/test/inbox ... Stuart> import mailbox Stuart> f = open('inbox','r') Stuart> mbox = mailbox.UnixMailbox(f) ... Does the problem disappear if you use the mailbox.PortableUnixMailbox class? Many systems don't generate valid From_ lines. PortableUnixMailbox treats any line beginning with "From " as a From_ line. UnixMailbox uses a much stricter definition. -- Skip Montanaro - skip at pobox.com "Airplanes don't fly until the paperwork equals the weight of the aircraft. Same with i18N." - from the "Perl, Unicode and i18N FAQ" From =?iso-8859-5?Q?=DF=D5=DD=D3=E3=D8=DD=D8=E1=E2=D0?= at =?iso-8859-5?Q?=DC=D0=D8=DB?=.=?iso-8859-5?Q?=DD=D5=E2?=.=?iso-8859-5?Q?=DC=DA?= Thu Oct 17 18:33:57 2002 From: =?iso-8859-5?Q?=DF=D5=DD=D3=E3=D8=DD=D8=E1=E2=D0?= at =?iso-8859-5?Q?=DC=D0=D8=DB?=.=?iso-8859-5?Q?=DD=D5=E2?=.=?iso-8859-5?Q?=DC=DA?= (=?iso-8859-5?Q?=B4=D0=DC=F8=D0=DD_=B3=2E?=) Date: Fri, 18 Oct 2002 00:33:57 +0200 Subject: Where to get Makefile.pre.in? References: Message-ID: <3daf3ad5$1@news.mt.net.mk> > Where I can get Makefile.pre.in? > I have compiled python 2.2.1 from sources. Now I want to build zope, but it > says that this file is missing. I dont think Zope will work with python 2.2.x, at least thats wat their web site says. Zope 2.5.x works with 2.1.x only. -- ?????? 0 and 1. Now what could be so hard about that? From donkan7 at yahoo.com Tue Oct 22 04:59:19 2002 From: donkan7 at yahoo.com (Richard Bow) Date: Tue, 22 Oct 2002 01:59:19 -0700 Subject: best way to learn References: <3DB4EE56.5000203@mxm.dk> Message-ID: maxm wrote in news:3DB4EE56.5000203 at mxm.dk: > Richard Bow wrote: > > > Please explain what is meant by "refactor". > > It means to clean up a codebase. Rewrite it until it follows best > practice. Rewrite until it is beatiful, efficient and correct. > > You should do it without changing functionality. > > And a few links found on the amazing Google: > > http://emw.inf.tu-dresden.de/de/pdai/Forschung/refactoring/refactoring_h > tml/node26.html http://www.wikipedia.org/wiki/Refactor > http://ootips.org/refactoring.html > http://www.exciton.cs.rice.edu/comp410/books/refactoring.html Thanks very much for your short explanation, and the informative links. Richard Bow From anton at vredegoor.doge.nl Tue Oct 8 08:33:22 2002 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Tue, 08 Oct 2002 14:33:22 +0200 Subject: [OT} How to un-GPL parts of a GPL'd module. Message-ID: Hello All, how can I use a class or a function from a GLP'd module (cut-and-paste style) in a module with BSD or public domain style release? I guess I could e-mail the author for permission but if I would have to wait for them to answer, it would slow my coding process down to a snail's pace, and there's always the possibility of the author being unwilling. So that's not an option for me. I would rather rethink the problem and start writing a new script. But here's where the problem begins. Having seen the algorithm it's almost impossible for me to forget it and write code as if I had never seen it. On the other hand, is it enough to just cut and paste, change maybe a few variable names, credit the author for the original concept in the sourcode, send some email to inform the author and go on with life? I know a lot of people rely on writing sourcecode for a living but I have been unemployed as a programmer for so long know that the concept of owning sourcecode or getting payed for producing it is completely alien to me. I think I'll be writing free sourcecode till I die just hoping some pieces of my code will survive into eternity. If someone has a problem with that, hire me. Anton. From adalke at mindspring.com Fri Oct 18 16:29:54 2002 From: adalke at mindspring.com (Andrew Dalke) Date: Fri, 18 Oct 2002 14:29:54 -0600 Subject: SOAP frustrations References: <3DAC6F04.2030704@mindspring.com> <23891c90.0210170137.481cda6@posting.google.com> <3db01c6a$0$18871$afc38c87@news.optusnet.com.au> Message-ID: <3DB06F42.9050804@mindspring.com> Derek Thomson wrote: > I predict it won't be easier to run SOAP through firewalls for long. > Wait until sysadmins realize you are running RPC calls ever port 80, and > filter incoming SOAP requests out. > > I know forwarding thinking sysadmins already starting to do this, as > port 80 was *not* opened for RPC, and any attempt to use it as such > would violate their organization's security policies, and requires > explicit permission. Yeah? And when they find out I'm running CGI scripts accessible through port 80 then they'll shut down those RPCs too? Shouldn't the filtering be done on the URI for the SOAP request? That is, only requests to public/published requests should go through and others are blocked? It's besides the point in that the service I'm helping provide (I'm the OP for this thread) is all behind the firewall and only for internal users. Ditto for the CGI scripts. Though I don't know if they have internal firewalls. Andrew dalke at dalkescientific.com From phd at phd.pp.ru Tue Oct 29 05:57:52 2002 From: phd at phd.pp.ru (Oleg Broytmann) Date: Tue, 29 Oct 2002 13:57:52 +0300 Subject: On The Naming of Things Message-ID: <20021029105751.GA7836@phd.pp.ru> http://www.oreillynet.com/pub/wlg/2225 "I've been thinking recently about what accounts for the CPAN's success; well, that's not quite true. I've been trying to work out what accounts for the Ruby Application Archive and Python's Vaults of Parnassus comparative failure." "Definitive names discourage wheel reinvention. Descriptive names are best for libraries." "Shamans have long known the value of the correct and definitive naming of things; programmers of libraries and modules would do well to rediscover it." Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From ark at research.att.com Thu Oct 3 10:45:27 2002 From: ark at research.att.com (Andrew Koenig) Date: 03 Oct 2002 10:45:27 -0400 Subject: [Python-Dev] PEP239 (Rational Numbers) Reference Implementation and new issues In-Reply-To: References: <20021002221421.GA29958@thyrsus.com> Message-ID: Christopher> For what it's worth, the current implementation is Christopher> nothing this complicated. Like every other numeric Christopher> operation, compares of rationals with floats coerce to Christopher> floats. So as a result rational(x)==float(x) iff Christopher> float(rational(x))==float(x). Attractive as this strategy may be from an implementation viewpoint, it means that comparisons do not have the order-relation properties that algorithms such as sort expect. A similar problem exists today for comparisons between float and long, by the way. -- Andrew Koenig, ark at research.att.com, http://www.research.att.com/info/ark From whisper at oz.net Tue Oct 1 17:10:40 2002 From: whisper at oz.net (David LeBlanc) Date: Tue, 1 Oct 2002 14:10:40 -0700 Subject: Is the word "Python" copyrighted/trademarked? In-Reply-To: Message-ID: It maybe could have been to denote the language, but it's been used so many times without a claim alongside it, I doubt it would be granted protection by any court. David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of sismex01 at hebmex.com > Sent: Tuesday, October 01, 2002 13:13 > To: t_therkelsen at hotmail.com; python-list at python.org > Subject: RE: Is the word "Python" copyrighted/trademarked? > > > > From: Troels Therkelsen [mailto:t_therkelsen at hotmail.com] > > > > Hey everybody, > > > > My question is whether the word "Python" classifies as a PSF > > trademark or trade name? Eg., if I wanted to create a web > > server in Python (not that I want to), could I call it > > "Python Web Server" without breaking any rules? > > > > Regards, > > > > Troels Therkelsen > > > > Hmmm... "Python" is the name of a snake, and it's also > a common english word; I don't think it can be copyrighted. > > ?Can it? > > :-) > > -gustavo > > > > > > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list From i.linkweiler at web.de Thu Oct 31 16:27:25 2002 From: i.linkweiler at web.de (Ingo Linkweiler) Date: Thu, 31 Oct 2002 22:27:25 +0100 Subject: MySQL + Python. References: <3DC1783F.5000003@web.de> Message-ID: <3DC1A03D.8040403@web.de> Luca Bruderer schrieb: > Hi > > I'm using this one: http://sourceforge.net/projects/mysql-python. I think > it's good and easy. Untill now I didn't have several problems with it. I cannot use this, because there is no C-Compiler available on the server, and I can not use .exe or .rpm files. Ingo From gerhard.haering at gmx.de Thu Oct 17 22:03:53 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 18 Oct 2002 02:03:53 GMT Subject: Barre de progression References: <5jfnoa.94c.ln@farfadet.home.org> Message-ID: Meles MELES wrote in comp.lang.python: > Bonsoir ? tous, Bonjour. comp.lang.python est un group internationale ou on ?crit en anglais. Si tu cherches un group o? on parle le franceais, c'est fr.comp.lang.python > je suis ? la recherche d'exemple d'impl?mentation d'une ba rre de > progression en mode console Je n'en connais pas. wxPython en a, mais c'est graphique. (J'ai mis le "Followup-To" ? fr.comp.lang.python, pour y diriger la discussion.) -- Gerhard From lbrannma at cablespeed.com Thu Oct 3 21:29:14 2002 From: lbrannma at cablespeed.com (Lance) Date: Thu, 3 Oct 2002 18:29:14 -0700 Subject: Integer and String Dictionary Keys for Fast Access References: Message-ID: Yes... I suppose it doesn't matter if everything is a pointer. Lance "Sean 'Shaleh' Perry" wrote in message news:mailman.1033688407.10786.python-list at python.org... On Thursday 03 October 2002 16:18, Lance wrote: > Hi, > > I'd like each element of a dictionary to have two keys, one a string and > the other an integer. Each of course would be unique relative to the other > keys and associated with a single dictionary value. > > The advantage is that key lookups by integer are no doubt much faster than > by strings. At least that's what I find with GAUSS, a matrix programming > language. GAUSS let's users refer to a dictionary value by its string key > or integer key. Referring to the value by its integer key significantly > speeds execution in optimization routines. > > Any suggestions? > > Thanks in advance. > Lance test it out in python, you may be surprised. I don't think the type really matters for dictionary look ups. From TuxTrax at fortress.tuxnet.net Wed Oct 30 16:10:51 2002 From: TuxTrax at fortress.tuxnet.net (TuxTrax) Date: Wed, 30 Oct 2002 21:10:51 -0000 Subject: library defined exceptions References: Message-ID: On 30 Oct 2002 12:52:18 GMT, Gerhard H?ring Wrote in Steve Ballmers hair grease: > TuxTrax [2002-10-30 11:43 GMT]: >> Hi all. I am working on a program to download all headers from >> my news server and place them in a shelve file, called 'database', >> on the local hard drive. > > Sounds familiar :) > >> [...] here is the code section that I am having trouble with: [...] > >> except NNTPTemporaryError, errorarg: > >> If an exception is raised, I get something like: >> >> File "head.py", line 404, in ? >> except NNTPTemporaryError, errorarg: >> NameError: There is no variable named 'NNTPTemporaryError' > > You need to qualify the exception classes as well, if you use the "import > module" form. I. e. use "nntplib.NNTPTemporaryError". > > -- Gerhard it needs to read: try: except nntplib.NNTPTemporaryError, errorarg: and python will recognize the nntplib defined exceptions, in this case NNTPTemporaryError? Cheers, Mathew -- TuxTrax (n.) An invincible, all terrain, Linux driven armored assault vehicle that can take as much fire as it gives ;-) Yes, I am a Penguin cult high priest. Flipper readings upon request. ROT13 this email address to mail me: bar jbeq abg guerr - uvtu qrfreg zna, ng lnubb qbg pbz From i.linkweiler at web.de Tue Oct 15 14:27:46 2002 From: i.linkweiler at web.de (Ingo Linkweiler) Date: Tue, 15 Oct 2002 20:27:46 +0200 Subject: International APPs / pygettext Message-ID: <3DAC5E22.1060102@web.de> Hi, I want to write a program supporting multiple languages. The Python-Documentation refers to the module "gettext" (http://www.python.org/doc/2.2.1/lib/node206.html) and "pygettext". "gettext" is included in the Python 2.2 distribution, but where can I find "pygettext.py"? The download-link to (http://www.iro.umontreal.ca/contrib/po-utils/HTML/) ist down since several days. What do I need to edit the ".mo" files? Ingo From phr-n2002b at NOSPAMnightsong.com Wed Oct 2 21:20:40 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 02 Oct 2002 18:20:40 -0700 Subject: [Python-Dev] PEP239 (Rational Numbers) Reference Implementation and new issues References: <20021002221421.GA29958@thyrsus.com> Message-ID: <7x3crojp1z.fsf@ruckus.brouhaha.com> Guido van Rossum writes: > I'm all for adding rationals to the language -- but I'd like them > segregated until we have a lot more experience with how they behave. Maybe we need yet another new operator: 3 / 2 => 1.5 3 // 2 => 1 3 /// 2 => 3/2 This is half-joking, half serious. From dent at oofile.com.au Wed Oct 16 22:37:55 2002 From: dent at oofile.com.au (Andy Dent) Date: Thu, 17 Oct 2002 10:37:55 +0800 Subject: Report writer for Python? References: <3da7b63b@monitor.lanset.com> <3da9cd1d@monitor.lanset.com> Message-ID: In article <3da9cd1d at monitor.lanset.com>, "Adams-Blake Co." wrote: >I'm looking for an IDE similar to Crystal that >will help me to quickly layout the reports and which will interface with a >binary or a library or a whatever to allow me to feed the module an SQL >string and the module or library takes it from there to output the report The OOFILE report-writer was initially developed for a cross-platform project to replace Crystal. One of the requirements was to make maintenance easier for the developers - they had 150 templates in Crystal and were sick of fiddling with them. Based on a chapter in an an old favourite of mine "Programmers at Work" I decided that whilst a reportwriter can allow you to exactly specify layout, it should be able to produce reasonable results with no layout specification or with minor hints, by knowing the data types and working out relative column widths accordingly. Thanks for the feedback. -- Andy Dent BSc MACS AACM http://www.oofile.com.au/ OOFILE - Database, Reports, Graphs, GUI for c++ on Mac, Unix & Windows PP2MFC - PowerPlant->MFC portability From paul at boddie.net Thu Oct 3 06:29:03 2002 From: paul at boddie.net (Paul Boddie) Date: 3 Oct 2002 03:29:03 -0700 Subject: Decimal arithmetic, with example code References: Message-ID: <23891c90.0210030229.26d9ba2f@posting.google.com> Tim Peters wrote in message news:... > > That's a different issue. The results of the given expression are > platform-dependent even if float_res is exactly representable in binary fp. > For example, > > >>> '%0.2f' % 1.125 > '1.13' > >>> > > on Windows but produces '1.12' on most other platforms. This doesn't have > to do with representation error (decimal 1.125 is exactly representable in > binary fp), it has to do with tbe platform sprintf's *decimal* rounding > policy in "exactly halfway" cases. That varies across platforms, even with > identical FP HW. Well, you're the recognised master of floating point, so I'll bow to your expertise. In any case, my original point (or perhaps the intended meaning of my original point) still stands: verifying decimal arithmetic results using a combination of "unreliable" technologies (floating point arithmetic and various "uncontrollable" rounding and presentation techniques) isn't going to convince that many people that the decimal arithmetic is wrong. Paul From dsavitsk at e-coli.net Tue Oct 8 11:35:15 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Tue, 08 Oct 2002 15:35:15 GMT Subject: [OT} How to un-GPL parts of a GPL'd module. References: Message-ID: "Anton Vredegoor" wrote in message news:anus7e$44r$1 at news.hccnet.nl... > On Tue, 8 Oct 2002 09:03:44 -0400, "Steve Holden" > wrote: > > >"Anton Vredegoor" wrote in message > >news:anujeq$qdk$1 at news.hccnet.nl... > > > >> there's always the possibility of the author being > >> unwilling. > >> > >Indeed. Perhaps you should consider releasing your own code under the GPL > >rather than some other license. > That would solve the problem at the cost of passing on the problem to > the next coder. It's this kind of "chain letter like" property that I > want to adress. Perhaps you should not be reading the GPL'd code in the first place. The GPL is a quid-pro-quo agreement. You get insight into others code, and in exchange you contine to pass on the knowledge. If it seems unfair or burdensome to benefit others in the same way you were benefited then keep your eyes on your own paper. > >> I know a lot of people rely on writing sourcecode for a living but I > >> have been unemployed as a programmer for so long know that the concept > >> of owning sourcecode or getting payed for producing it is completely > >> alien to me. I think I'll be writing free sourcecode till I die just > >> hoping some pieces of my code will survive into eternity. If someone > >> has a problem with that, hire me. > >> > >Sort of like "send money or I'll shoot the dog"? Not a very promising > >aproach to potential employers. I would encourage you to contact the > >original author and see if you can't get permission to include the code > >under license terms acceptable to you. Otherwise you'll need a clean room > >implementation (which, if the algorithm is obvious, might be similar to the > >GPL'd code, but should be your own work rather than someone else's). > > > > In case it's not clear, the chance of me finding an employer is > remote. :-( > I don't agree with the "pass the > problem to the next guy" property of the GPL. Then don't read other's code. > Since the dog metaphore > was brought up, I would like to add the comparison of having a GPL dog > using a specific tree for some known purpose and forbidding any other > dog to use it for that same purpose ... The metaphore makes no sense, or rather, is misplaced. The better one might be a dog saying that there is a tree in the woods where peeing is extra fun. He will only tell you which one if you agree to tell the next dog under the same conditions. Thus, you can learn which tree for free, but you must pass on the knowledge, OR you can pee on every damn tree until you find the fun one. Your calculus, as you are generally selfish at heart, should be based on the number of trees and how quickly you can pee on them. In this case, you asked, and you can't give the knowledge back ... even if you make a showing of peeing on every tree. Your best out is probably if the code in question is generic and not copyright-able. From the length of the discussion this seems to not be the case. In the future, you should do less peeking to avaoid this problem. This is particularly the case as this discussion is archived and will be dug up if you are ever sued. -d From jb at cascade-sys.com Tue Oct 29 13:24:18 2002 From: jb at cascade-sys.com (James J. Besemer) Date: Tue, 29 Oct 2002 10:24:18 -0800 Subject: transform lists in strings?? References: <2074406325.1035915553546.JavaMail.nobody@webmail2.brturbo.com> Message-ID: <3DBED252.3010901@cascade-sys.com> jubafre at brturbo.com wrote: > i have this list: > x=['d', 'f', 'd', 's', 'f', 'd', 's', 'f', 'd', 's', 'f', 'd', 's', '\\(', '\\)', '\\^', '\\|', ';', '\\.', '\\$'] > > i want to transform x in a string like this: dfdsfdsfdsfds\\(\\)\\^\\|;\\\\$ > > How can i do this????/ "".join(x) > > > Juliano Freitas > www.gebrasil.hpg.com.br -- James J. Besemer 503-280-0838 voice 2727 NE Skidmore St. 503-280-0375 fax Portland, Oregon 97211-6557 mailto:jb at cascade-sys.com http://cascade-sys.com From TuxTrax at fortress.tuxnet.net Thu Oct 31 03:40:51 2002 From: TuxTrax at fortress.tuxnet.net (TuxTrax) Date: Thu, 31 Oct 2002 08:40:51 -0000 Subject: A shelve error: any ideas? Message-ID: Hi all. Still working on that database program that downloads all available headers from the server into a shelve file. I got this cryptic error, during a download of those headers. I had downloaded 25,246 full headers, and the routine was starting on 25,247, when it crashed for an unknown (to me) reason, apparently having something to do with an error internal to the shelve module. The file it was creating is: -rw-r--r-- 1 mat mat 90058752 Oct 30 15:01 HH.database and was not corrupted. I could access it just fine. the screen had this on it when I came back to check on the output: Creating database entry 25246 out of 27694 Traceback (most recent call last): File "head.py", line 401, in ? database[id] = list File "/usr/lib/python2.0/shelve.py", line 76, in __setitem__ self.dict[key] = f.getvalue() bsddb.error: (0, 'Error') [mat at fortress]$ Any ideas what this error means? Cheers, Mathew -- I am Microsoft Free. Operating_System: Mandrake Linux 8.0 kernel 2.4.3-20 Yes, I am a Penguin cult high priest. Flipper readings upon request. ROT13 this email address to mail me: bar jbeq abg guerr - uvtu qrfreg zna, ng lnubb qbg pbz From senux at senux.com Sat Oct 5 09:36:38 2002 From: senux at senux.com (Brian Lee) Date: Sat, 5 Oct 2002 22:36:38 +0900 Subject: CGI server by Python In-Reply-To: References: Message-ID: <20021005133638.GA3124@mercury.senux.com> On Thu, Sep 26, 2002 at 11:54:54AM +0000, Alex Martelli wrote: > Brian Lee wrote: > > > Hi, > > > > I tested CGIHTTPServer.py in Python 2.2 and found that cgi files in > > sub directory does not run. Does anybody know about this? > ... > > avante.xxx.co.kr - - [26/Sep/2002 19:20:24] code 403, message CGI script > > is not a plain file ('/cgi-bin/a') avante.xxx.co.kr - > > Exactly as it says, /cgi-bin/a is not a plain file (it's a directory!) > and CGIHTTPServer.py is written to support plain files right under > cgi-bin only. See the parsing in function run_cgi around line 100 > and following of that file in your Python library directory. If you > don't like the way it parses things, it ain't hard to modify... Hi Alex, thanks for your posting! I read carefully the code how it parse the directory. I modified it and it works. But I found environmental variable, $PATH_INFO is not match for my code. I searched on Google how PATH_INFO define and how to set the variable in server. But I can't find it and just wonder someone who know it. -- Brian Lee - http://www.senux.com/en/ From nadavh at envision.co.il Thu Oct 17 12:13:53 2002 From: nadavh at envision.co.il (Nadav Horesh) Date: Thu, 17 Oct 2002 18:13:53 +0200 Subject: Compiling python 2.2.2 with gcc 3.2 Message-ID: <3DAEE1C1.3080504@envision.co.il> >>I tried to compile python2.2.2 under RH 7.2 with gcc 3.2. I got weired >> error messages from >> incopatibility between "fpos_t" and "int", to obsoleteness of "tmpname". >> >> Did anyone succeed? > >Instead of saying that the messages are weired, could you perhaps just >quote them literally? > >Regards, >Martin You right, but I found also the solution: I finally converged to the following error message: c++ -Xlinker -export-dynamic -o python \ Modules/python.o \ libpython2.2.a -ldl -lpthread -lutil -lm /usr/bin/ld: Dwarf Error: Invalid or unhandled FORM value: 14. libpython2.2.a(posixmodule.o): In function `posix_tmpnam': /tmp/pytest1/Python-2.2.2/Modules/posixmodule.c:4505: the use of `tmpnam_r' is dangerous, better use `mkstemp' libpython2.2.a(posixmodule.o): In function `posix_tempnam': /tmp/pytest1/Python-2.2.2/Modules/posixmodule.c:4455: the use of `tempnam' is dangerous, better use `mkstemp' collect2: ld returned 1 exit status make: *** [python] Error 1 The problem was that I had to update the original binutils that came with RH7.2 from version 2.11 to version 2.13 as required by gcc 3.2. Two observations that I would like to get comments: 1. The file size of python2.2.2 compiled under RH7.2 gcc3.2 is about 3MB compared with 800K of the python2.2.1 from the python-site RPM. I made the minary by the following steps. ./configure # without any options .. edited the Makefile to add "-s -march=pentium3 -msse" to the OPT vatiable make thats all. 2. The gcc3.2 I got, compiled from the source seems to be more stable than the one comes with Mandrake 9.0 Nadav. From aleax at aleax.it Sat Oct 5 10:50:52 2002 From: aleax at aleax.it (Alex Martelli) Date: Sat, 05 Oct 2002 14:50:52 GMT Subject: CGI server by Python References: Message-ID: Brian Lee wrote: ... >> > I tested CGIHTTPServer.py in Python 2.2 and found that cgi files in ... > But I found environmental variable, $PATH_INFO is not match for my > code. I searched on Google how PATH_INFO define and how to set > the variable in server. But I can't find it and just wonder someone > who know it. I'm not sure what you mean. There's one statement: env['PATH_INFO'] = uqrest in CGIHTTPServer.py -- and uqrest is the urllib.unquote'd version of 'rest', which is determined at the start of method run_cgi by parsing self.cgi_info appropriately. What is it you can't find, and what problems are you experiencing? As CGIHTTPServer.py itself mentions, a reference page for environment variables expected by CGI scripts can be found at http://hoohoo.ncsa.uiuc.edu/cgi/env.html - that page says: """ PATH_INFO The extra path information, as given by the client. In other words, scripts can be accessed by their virtual pathname, followed by extra information at the end of this path. The extra information is sent as PATH_INFO. This information should be decoded by the server if it comes from a URL before it is passed to the CGI script. """ So, what is not working as this spec says it should work? Alex From arboleya at prontomail.com Mon Oct 21 05:36:21 2002 From: arboleya at prontomail.com (Juan Garcia) Date: 21 Oct 2002 02:36:21 -0700 Subject: somebody knows a group/mailing list about Zope? Message-ID: somebody can give me the name of a news group or a mailing list in which they speak about Zope? From mhammond at skippinet.com.au Sun Oct 20 21:06:18 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Mon, 21 Oct 2002 01:06:18 GMT Subject: PyFinalize problem from multiple DLLs - a possible work-around References: <3DB2C401.D97B5067@fxtech.com> Message-ID: Paul Miller wrote: > Hi folks. We're embedding Python and have come across a conflict when > multiple DLLs that link to Python are used. Here is the scenario: > > Application > Extension1.dll > python22.dll > Extension2.dll > python22.dll > > Although neither Extension knows about the other, they both link to > python, which seems to be sharing its global state between the two. This > causes problems when we do this: > > Application Startup > Extension1_Startup > PyInitialize > Extension2_Startup > PyInitialize > > Extension1_Shutdown > PyFinalize > Extension2_Shutdown > PyFinalize <--- oops I don't think the extensions should be initializing or finalizing Python itself. Simply have the application init and finalize Python - presumably the app must somehow bootstrap this Python import process, so it doesn't seem a burden. On the other hand, while I don't really believe *you* need it, a little safety in the init/term functions would not go astray. There is another unrelated bug caused by multiple PyInit/Final calls that _do_ actually init and term - eg, consider a server process that wants to "unload" Python when it has finished with it, but be able to "reload" it when it needs it again. In this scenario, there are certainly memory leaks, and other design issues that are much harder to solve (specifically, unless extension modules are informed of the finalize/reinitialize, their own internal structures or objects may become invalid) > 1. confirm this problem really exists > 2. agree my solution probably fixes it (I have the code to proove it) > 3. tell me where to submit the patch? The process should be: * Create a patch a python.sourceforge.net (use a patch rather than a bug) * Possibly mail python-dev at python.org with the URL to the patch, and a description of your specific problem Mark. From mcfletch at rogers.com Mon Oct 21 19:38:28 2002 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Mon, 21 Oct 2002 19:38:28 -0400 Subject: Aspell and References: Message-ID: <3DB48FF4.3090403@rogers.com> Kevin Atkinson wrote: ... >You misunderstand. word-list-compress simply compresses and decompresses >a sorted word list to save space. It is not used in any way by Aspell >itself. > I understood that word-list-compress was an offline utility, but I'm not sure what you're using to search the compressed word-list on disk. That is, how does _Aspell_ make use of the data once it's been compressed? Is it something like a bisect algo with an index somewhere on disk to the items in the file? (I gather by your reaction that the entire word-list is not all loaded into memory at run-time). >leditdistance != typo edit distance. leditdistance uses a different algo. >than the normal edit distance algorithm. The normal edit distance algorithm >"editdist.cpp" and the typo edit distance algorithm "typo_editdist.cpp" >are basically the same except for the weights. > Ah, I had thought those were older implementations that had been superceded by the leditdistance algorithm (mostly because of the greater number of comments in that one). I think for the moment I'll just leave the typo-distance code, and concentrate on the overall evironment. >>It would seem that you'd need >>each "swap" to be a lookup into the typo table. >> >> > >Yes that is correct. But it is not a "swap" but a replacement. A swap is >when the adjective letters are interchanged, "teh" vs. "the". > Thanks for the clarification, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From gerhard.haering at opus-gmbh.net Thu Oct 31 04:20:48 2002 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 31 Oct 2002 09:20:48 GMT Subject: email, unicode, HTML, and removal thereof References: <3DC0FB30.3000307@mindspring.com> Message-ID: Andrew Dalke [2002-10-31 09:43 GMT]: > Short version: > What should I do to strip out markup from an email'ed HTML > document so I can get just the text? (Yeah, it won't always > get only the text.) I'm having problems in how to handle > the charset. > > Solutions in pure Python or via calling a common (under unix) > external program are fine. For a Unix solution: lynx -dump w3m -dump links -dump ... if any of these text-mode browsers is installed. -- Gerhard From ken at hotmail.com Wed Oct 2 09:31:16 2002 From: ken at hotmail.com (Ken) Date: Wed, 2 Oct 2002 23:31:16 +1000 Subject: Easy way to break up a sentence? Message-ID: Hi all, I am trying to do a simple word search engine. Is there an easy way to break up a sentence into individual words so that I can use it to compare without traversing through every character? Eg, something like this: from: "This is an example" to: ["This", "is", "an", "example"] Thanks From andymac at bullseye.apana.org.au Sat Oct 5 23:05:12 2002 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Sun, 6 Oct 2002 14:05:12 +1100 (edt) Subject: Is it possible to 'compile' a script? Message-ID: On Fri, 4 Oct 2002, solosnake wrote: > This interests me in particular : > > Note that Python already compiles scripts internally > > to a bytecode before executing them, and does most > > things that are reasonably practical to interpret > > the bytecode as quickly as possible. > > So *in theory* at least what I am asking after is not impossible, and at > some level is already inside Python. My suggestion to those responsible for > maintaining Python is to differentiate between calling a script which is > then parsed and compiled into bytecode and executed, and calling a function > which will parse and create the bytecode, but return a handle to that (now > faster) bytecode and allow it to be executed through this handle. The basic approach for this in a scripting environment is as follows: 1) make your code a module, which has at the end something like this: if __name__ == '__main__': doit() where doit() is the main routine of your code. 2) compile the module by importing it from the interactive interpreter (gives you the .pyc file). 3) create a caller script like so: #!/usr/local/bin/python import .doit() With a large and/or complex chunk of code, this saves having to recompile everything except the caller script on each invocation. It is also prudent to ensure that all of Python's standard library has been compiled. I believe there have been examples of Linux distros not compiling the library when installing Python (using said distro's standard Python package), which tends to slow things down unnecessarily. -- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au | Snail: PO Box 370 andymac at pcug.org.au | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From donteventhinkaboutit_rochus at nono_vanderkleyn.com Thu Oct 31 01:47:59 2002 From: donteventhinkaboutit_rochus at nono_vanderkleyn.com (Iwan van der Kleyn) Date: Thu, 31 Oct 2002 07:47:59 +0100 Subject: Future of Jython? Message-ID: <3dc0d213$0$63815$e4fe514c@dreader1.news.xs4all.nl> Hi there, I'm busy sketching the broad outlines (pre-design) of a java-based middelware componment for a customer. Functionional requirements demand a scripting component and I would like to choose Jython. However, the latest release of Jython has been nearly a year ago, the site doesn't look very up to date and CVS on sourceforge has about 4 commits in 2002. So I'm definitely left with the impression that as a project Jython is dying. I hope I'm wrong , so could anyone fill me in about the "condition" of Jython? Does it have a future? Regards, Iwan From ivan.brkanac at hl.hinet.hr Wed Oct 16 08:54:40 2002 From: ivan.brkanac at hl.hinet.hr (Ivan Brkanac) Date: Wed, 16 Oct 2002 14:54:40 +0200 Subject: file operation question Message-ID: Hello I am making little application and in it I am processing some files and I decided to make code that rebuilds(fetch from Internet) file if it is not existing. But I get error message belov is part off the code and report off error. Problem is as I can see that win don't update file so fast and when script try to read file again it reads emptyy file. I used file.close() before opening file again for parsing. Is there any way to wait until file is closed so that it can be read again Regards Ivan try: self.inicijalizacija(open('./tecaji.dat','r')) except IOError: wxSetCursor(wxHOURGLASS_CURSOR) # Kursor U hourglas import urllib, urllister, urlparse f =urllib.URLopener().open(adresa) t = f.read() # U??itamo je u string f.close() parser = urllister.URLLister() parser.feed(t) parser.close() t = open('./tecaji.dat','w') f = urllib.URLopener().open(urlparse.urljoin(adresa , parser.urls[0])) t.write(f.read()) t.close f.close # close file wxSetCursor(wxSTANDARD_CURSOR) # postavimo normalni kursor self.inicijalizacija(open('./tecaji.dat','r')) # AGAIN # opening for procesing but it reads empty ?? D:\Documents and Settings\Administrator\My Documents\Python>python pretvorba.py Traceback (most recent call last): File "pretvorba.py", line 153, in ? app = MyApp(0) File "C:\Python\lib\site-packages\wxPython\wx.py", line 1587, in __init__ _wxStart(self.OnInit) File "pretvorba.py", line 148, in OnInit frame = MyFrame(NULL, -1, "Konverzija Valuta Tecaj od ") File "pretvorba.py", line 24, in __init__ self.inicijalizacija(open('./tecaji.dat','r')) File "pretvorba.py", line 104, in inicijalizacija datum = ND(tecaj[15:19]+tecaj[13:15]+tecaj[11:13]) File "C:\Python\lib\normalDate.py", line 82, in __init__ self.setNormalDate(normalDate) File "C:\Python\lib\normalDate.py", line 376, in setNormalDate raise NormalDateException("Bad integer: '%s'" % normalDate) normalDate.NormalDateException: Bad integer: '' From cam at stny.rr.com Wed Oct 2 21:52:11 2002 From: cam at stny.rr.com (Craig Mellen) Date: Thu, 03 Oct 2002 01:52:11 GMT Subject: Starting IDLE in SuSE 7.2 Message-ID: <3D9BA2DB.591E781A@stny.rr.com> Obviously, new to Python.....How do I start IDLE in SuSE 7.2? Installed are tix,tcl/tk,python, python-tkinter; What am I missing? From pj at engr.sgi.com Sun Oct 20 21:04:43 2002 From: pj at engr.sgi.com (Paul Jackson) Date: 21 Oct 2002 01:04:43 GMT Subject: How do I invoke IE browser from Python on Mac OS X? References: Message-ID: Brian wrote: > Don't know about Python directly, but open -a /path/to/app should work > from a shell. If you want to open it with a URL, though, that might not > be sufficient. That was fast - Thanks !! If I can do it from the shell, I can do it from Python with some variation of a "os.system(open -a /path/to/app)" call, I presume (I'm not near my Mac to try right now). I don't grok what you meant by "open it with a URL", but that probably doesn't matter ... ah - you mean "if I want to open the browser on a particular URL, as might happen when passing it a command line argument". With the hints you've given I found on a Google search: http://www.macosxhints.com/article.php?story=20020902074127468 Open URLs from the command line Mon, Sep 2 '02 at 10:41AM . from: Anonymous In the Terminal, type "open http://www.apple.com" and your default browser will launch and open this page. I think this is only possible in 10.2! [Editor's note: I don't think this worked in 10.1, either (at least not according to this hint). Run "man open" for some other possibilities.] A couple of link-hops away from this is Launcher: http://web.sabi.net/nriley/software/ Apple provides a simple command-line launching program called open with Mac OS X. It offers few options--launching applications by name or by path, launching TextEdit, or opening a number of applications, documents, folders, etc. With the exception of special support for TextEdit, launch does everything open does, and: * opens URLs, directly or in your preferred helper application * lets you specify applications by their four-character creator (e.g. 'ToyS') or Java-style bundle ID (e.g. com.apple.scripteditor), both of which allow you to move or rename an application without changing references to it * asks applications to print documents, something the OS X Finder doesn't let you do any more * launches applications in the background * launches Carbon applications in Classic * reports errors intelligibly * shows information about any item on disk, including its file type, creator, data and resource fork sizes, dates and bundle ID (where applicable). launch is useful by itself, but is even better when used in scripts. Assign a shell command to your favorite Mac OS text, graphics or resource editor. Browse your favorite Web site with a few keystrokes. launch requires Mac OS X 10.1 or later with Developer Tools installed. -- -- I won't rest till it's the best ... Programmer, Linux Scalability Paul Jackson 1.650.933.1373 From dent at oofile.com.au Thu Oct 17 20:43:59 2002 From: dent at oofile.com.au (Andy Dent) Date: Fri, 18 Oct 2002 08:43:59 +0800 Subject: Report writer for Python? References: <3da7b63b@monitor.lanset.com> <3da9cd1d@monitor.lanset.com> <3dae48b3@monitor.lanset.com> Message-ID: In article <3dae48b3 at monitor.lanset.com>, "Adams-Blake Co." wrote: >Andy Dent wrote: > >This is interesting but I didn't see a Python interface. No, as I said in the first response - I'm in the middle of Python integration with our various tools and was looking for people's feedback on how they would use it. >Besides, all I >need is a report generator (perhaps from SQL) and not a database Part of the revision of the product is making it easier to drop into existing applications. The report-writer can currently be driven from a purely RAM-based database, which a number of clients populate from other sources (including plain application code, no databases in sight). The revision was prompted by an experience using the report-writer in a client site with SQL Server and a homegrown (before I got there) C++ database interface. If I'm writing logic to intelligently interface the report-writer engine to SQL and perform the same reflective operations that our current database API supports, I'd rather put a flexible layer in there to allow users to customise the data mappings without having to get down and dirty in C++. Hence, the choice of Python as a logical language to customise the database connection. -- Andy Dent BSc MACS AACM http://www.oofile.com.au/ OOFILE - Database, Reports, Graphs, GUI for c++ on Mac, Unix & Windows PP2MFC - PowerPlant->MFC portability From anton at vredegoor.doge.nl Wed Oct 2 07:03:18 2002 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Wed, 02 Oct 2002 13:03:18 +0200 Subject: [ANN] screensaver References: Message-ID: On Wed, 2 Oct 2002 00:06:34 -0500, "Chris Gonnerman" wrote: >Tried it (Win98, Python 2.1), didn't work: Someone else posted a few fixes. I can't test if it works with Python 2.1 but I have made some modifications and uploaded a new version. Taking just a very short look at your posting history I find it hard to believe you couldn't make it work. So what did you do, throw it away, disgusted with it? Or did you make it work? But then again why didn't you post the fix? Maybe there's some other problem with it, please inform me. I also would like to know if it works now. Anton. From Padraig at Linux.ie Mon Oct 7 06:50:38 2002 From: Padraig at Linux.ie (Padraig Brady) Date: Mon, 07 Oct 2002 10:50:38 GMT Subject: Fast persistent dictionary References: <3d9ddc93@news.mt.net.mk> Message-ID: <3DA166B3.1040507@Linux.ie> ?????? ?. wrote: > I need a fairly fast and simple persistent dictionary for use in > a Python program. I'll only store two string values for each key > (a string also). It's important that the contents of the dictionary are > saved to disk as soon as possible so to survive system failures in a > consistent state. A python wrapper around tdb might be appropriate? Padraig. From 2002 at weholt.org Wed Oct 9 13:13:56 2002 From: 2002 at weholt.org (Thomas Weholt) Date: Wed, 09 Oct 2002 17:13:56 GMT Subject: SOT : & in XML-documents References: Message-ID: It's a tab-seperated textfile. The file is actually nothing more than a fancy ls -laRh > some.file ( the ls syntax may be wrong ). I'm working on a filesystem scanner, extracting as much info from files found during scanning as possible. Thomas "Bengt Richter" wrote in message news:anvkci$l3l$0 at 216.39.172.122... > On Tue, 08 Oct 2002 18:59:59 GMT, "Thomas Weholt" <2002 at weholt.org> wrote: > > >I'm trying to parse an old fileformat into xml. The problem is that the > >character & appears from time to time in the original file. Tried to put > > > What is your "old fileformat" ? > > Regards, > Bengt Richter From news at agapow.net Fri Oct 4 05:37:45 2002 From: news at agapow.net (Paul-Michael Agapow) Date: Fri, 4 Oct 2002 10:37:45 +0100 Subject: [Mac] Editor on Macintosh? References: <1fj7za2.1erbqps1uvzpj8N%news@agapow.net> Message-ID: <1fjhgwg.5vpin61u38xowN%news@agapow.net> Paul-Michael Agapow wrote: > Sadly, it seems like the excellent editor Pepper is going away. > So what are other MacPythonistas using? Following up my own posting, I've found two new possibilities: * mi A new and utterly free editor. Although it doesn't come with a Python mode, it allows users to define new language modes and markups. Looks quite good. One caveat - the author is Japanese and the documentation and webpages can be a little confusing. For example, the english page describing mi doesn't link to the download page. * irEdit Another Japanese program, that comes with a Python mode. Unfortunately this is a use-limited demo, but the price is nice and it looks quite good. -- Paul-Michael Agapow (news at agapow.net) From loewis at informatik.hu-berlin.de Tue Oct 8 08:28:39 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 08 Oct 2002 14:28:39 +0200 Subject: Unicode Debugging Hints? References: Message-ID: holger krekel writes: > does anyone have some small functions to answer > questions 'might this be latin1' or 'might this be utf8' > or 'is this definitely not latin1' and such? Some of these questions can be answered really simple def maybe_encoding(s, enc): try: unicode(s, enc) return 1 except UnicodeError: return 0 def is_ascii(s): return maybe_encoding(s, 'ascii') def is_utf_8(s): return not is_ascii(s) and maybe_encoding('utf-8') def maybe_latin_x(s): if is_ascii(s) or is_utf_8(s): return 0 for c in s: if 128 <= ord(c) < 160: return 0 return 1 Telling apart the Latin-x variants is not really possible. Regards, Martin From fperez528 at yahoo.com Sun Oct 13 17:42:58 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Sun, 13 Oct 2002 15:42:58 -0600 Subject: Numeric vs numarray speed References: <3da93684$0$1286$cc9e4d1f@news.dial.pipex.com> Message-ID: Nick B wrote: > Hi any Numeric users, > > I have some image processing code that runs fine under Py2.1 and Py2.2 with > Numeric. Trying the same thing under the upcoming successor numarray (just > global find-and-replace numarray for Numeric in my code) it runs, but way > slower than 1/10 the speed. So for now I'm sticking to Numeric. > > Anyone any ideas why. Is numarray full of debug code ? b/c Numarray is trying to solve the performance issues which Numeric has with _huge_ arrays. The tradeoff is that right now, the small array case is much worse in Numarray than in Numeric. But the developers are perfectly aware of this case, and befor numarray is officially released, they'll bring the performance back to par for small arrays. It's just that right now they are concentrating on the architecture and design issues, no optimizations have been done yet. It would be good if you could keep your test code around, and as numarray begins to get closer to public release, run it again. If you still see a performance difference, by all means report it to the dev team, as I'm sure they'll be interested. It's possible that your code stresses numarray in a way they haven't foreseen and uncovers particularly problematic corner cases. Cheers, f. From mongo57a at comcast.net Sat Oct 5 23:32:05 2002 From: mongo57a at comcast.net (mongo57a at comcast.net) Date: Sun, 6 Oct 2002 03:32:05 GMT Subject: Quick question on mysql-python References: <3d9f74b2$1_7@goliath.newsgroups.com> Message-ID: <3d9f9d4c$1_6@goliath.newsgroups.com> Ok, looks like I have a whole slew of MySQL libraries - but they are version 10. (Maybe the latest MySQL-Python hasn't been updated yet????). Is it possible to rebuild the mysql-python interface (MySQL-python-0.9.2-1.i386.rpm) to use the .10 libs? Can I use rpm to do so - and how? This is much preferable to symlink. TAI -----------== Posted via Newsfeed.Com - Uncensored Usenet News ==---------- http://www.newsfeed.com The #1 Newsgroup Service in the World! -----= Over 100,000 Newsgroups - Unlimited Fast Downloads - 19 Servers =----- From martin at v.loewis.de Fri Oct 4 18:15:35 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 05 Oct 2002 00:15:35 +0200 Subject: range or xrange disallowed for big numbers References: Message-ID: Chad Netzer writes: > Is there a reason (technical or philosophical) to disallow: > > range( 10000000000L, 10000000000L + 1L ) > > or > > xrange( 10000000000L ) > > etc...? A technical reason. A range object is defined as typedef struct { PyObject_HEAD long start; long step; long len; } rangeobject; Changing it would be a medium-sized object, and cost performance in the common case. Regards, Martin From robin at jessikat.fsnet.co.uk Mon Oct 7 13:52:43 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Mon, 7 Oct 2002 18:52:43 +0100 Subject: Strange compiler warning Message-ID: with 2.2.1 I get the message SyntaxWarning: name '_dbg' is assigned to before global declaration with the following code, but things seem to be working, so is the compiler wrong or too lazy to see the globals on all paths? How should one do this sort of on the fly local debugging? ...... if not globals().has_key('_dbg'): global _dbg _dbg=open('/tmp/_dbg.txt','w') else: global _dbg print >>_dbg,'=======================\n' + text -- Robin Becker From loewis at informatik.hu-berlin.de Thu Oct 31 04:58:53 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 31 Oct 2002 10:58:53 +0100 Subject: email, unicode, HTML, and removal thereof References: <3DC0FB30.3000307@mindspring.com> Message-ID: Andrew Dalke writes: > This didn't work because I get complaints about having characters > with ordinal value > 127. I needed to change the "cStringIO" to > use the following MyStringIO and change the htmllib.HTMLParser > to MyHTMLParser. Yes, cStringIO does not support Unicode. > I interpret the problem to HTMLParser reading a hex > escape and converting it to a string. The way I do > things above can create characters >127. Then when > it converts the string to unicode, it throws the exception. > > My workaround solves this by forcing the string to be > interpreted in latin-1 context. This comes from this fragment in sgmllib: def handle_charref(self, name): """Handle character reference, no need to override.""" try: n = int(name) except ValueError: self.unknown_charref(name) return if not 0 <= n <= 255: self.unknown_charref(name) return self.handle_data(chr(n)) > This solution doesn't feel correct. For example, I assume > Latin-1 but it could be in window's cp1252, so I'm not > doing the charset correctly. Actually, it is correct as far as it goes. All cp1252 data are already converted to Unicode in your code, so there are no traces of cp1252 left. If the document also contains a character reference, such as   then handle_charref will convert it to chr(160). If you now interpret this string as Latin-1, your interpretation is correct: it so happens that the first 256 Unicode characters coincide with Latin-1. Of course, the code will break if somebody comes along with € it will invoke unknown_charref, which will discard the data. So I would recommend to override def handle_charref(self, name): try: c = unichr(int(name)) except ValueError: c = '?' self.handle_data(c) So you won't get any non-ASCII byte strings from character references anymore. However, you will still get them from entity references, as htmlentitydefs has, e.g. 'Aacute': '\301' If it would instead have 'Aacute': u'\301' you won't need to redefine StringIO. htmlentitydefs has other problems, e.g. it contains 'Alpha': 'Α', This would be copied literally into the output, instead of expanding the character reference. So I guess you should modify entitydefs as follows: for k,v in entitydefs.items(): if v.startswith('&#'): v = int(v[2:-1]) else: v = ord(v) entitydefs[k] = unichr(v) With these changes, you should not need a specialized StringIO anymore. Regards, Martin From adam at cardaccess.com.au Sun Oct 13 20:38:25 2002 From: adam at cardaccess.com.au (Adam Rutkowski) Date: 13 Oct 2002 17:38:25 -0700 Subject: Using SaveThread and RestoreThread with callbacks References: <95959723.0210111654.5a55609c@posting.google.com> Message-ID: > Instead of PyEval_SaveThread/RestoreThread I'd say it's safer to use > the macro's Py_BEGIN_ALLOWTHREADS/Py_END_ALLOWTHREADS, because if you > forget or misplace one of them, you'll get a compile-time error. > These calls are only necessary in a multi-threaded application, and > only if the C-stuff may block other threads. If your C-stuff isn't > blocking, I don't see a reason to save/restore the thread state. > The application is multi-threaded, and the C code does block, so I have to use this to make it all work properly. The thing is, I didn't write the code, I'm just trying to fix it, so I wasn't entirely sure if the guy who wrote it was using the save and restore stuff correctly. I'll try using the macros instead, and see if that helps. Note that bug is that the app crashes occasionally with a fatal python error, and it looks like this is being caused by a state inconsistency, which is why I'm looking at this bit of the code. Thanks for the help so far! Adam From grante at visi.com Thu Oct 10 11:32:20 2002 From: grante at visi.com (Grant Edwards) Date: Thu, 10 Oct 2002 15:32:20 GMT Subject: No tabs in post PLEASE!!! (was Re: partial list sort) References: <20021009094141.GA852@jsaul.de> <2Rep9.19819$ne4.8631@fe05> Message-ID: <84hp9.763$YJ1.1739535@ruti.visi.com> In article , Daniel T. wrote: > While we are at it, let's bitch and moan because some people put LF/CR > at the end of each line, some only put LF and some only put CR. AFAIK, all the relevent RFCs (e.g. RFC 977 Network News Transfer Protocol) specify that all article lines must end in CR/LF. If somebody isn't following the standard, they deserve to get bitched at. > "Everybody, quit inserting/stripping [arbitrary ASCII character] because > some of us can't read your posts!" -- Grant Edwards grante Yow! Now that I have my at "APPLE", I comprehend COST visi.com ACCOUNTING!! From bobsedge at yahoo.com Thu Oct 17 02:55:33 2002 From: bobsedge at yahoo.com (Robbie Sedgewick) Date: 16 Oct 2002 23:55:33 -0700 Subject: Numeric arrays with named axes? Message-ID: I've been writing a lot of Numeric code lately that require arrays with many dimensions. I think I currently have 5 dimensional array. It is starting to get somewhat confusing which axis is which especially with the different slices of the arrays floating arround. I'm thinking what is needed is some wrapper around Numeric arrays that allow me to refer to the axes of the array by name. For example: >>> x = namedarray([[1, 2], [3, 4]], axis_names=["cow", "dog"]) >>> x[{"cow":1}] namedarray([3, 4] axis_names=["dog"]) >>> sum( x[{"cow"}:1] ) 7 Has anyone done anything like this? I started to write a wrapper class, but it is somewhat complicated to figure out all the different ways that numeric functions change the shape of the array. Anyone got any better idea how to do this? Thanks, Robbie From kanva at mantramail.com Tue Oct 22 12:19:48 2002 From: kanva at mantramail.com (Gururaj Joshi) Date: Tue, 22 Oct 2002 12:19:48 Subject: HELP Needed Message-ID: <1035269388.1035269388@ldap.dsf> Hi I donot know anything about python. But Iam making use of a python script in Winrunner(automated testing tool). This appln acts asa proxy between the Client & Server. I need a small change to be made in the python script, so that it meets my requirement. Iam sending a python file, change request description file along with this mail. Please go thru it & mail me the updated code. ********************************************** Command to run the code : python tcpwatch.py -p 8000 Make the changes in the browser for: proxy m/c name & port number as 8000 ************************************************* Thanx for ur time & help Gururaj Joshi From peter at engcorp.com Thu Oct 17 17:53:16 2002 From: peter at engcorp.com (Peter Hansen) Date: Thu, 17 Oct 2002 17:53:16 -0400 Subject: Question about output... References: Message-ID: <3daf3155$1@news.sentex.net> Bengt Richter wrote: > To make things even more like C (other than the lack of ';') Hey, what's wrong with using ";" ? ;-) > def printf(fmt, *args): > import sys > sys.stdout.write(fmt % args) > > printf("The average of %d and %d is %d\n", firstInt, secondInt, average) >>> printf("The average of %d and %d is %d\n", 10, 20, 15); The average of 10 and 20 is 15 -the-semicolon-is-silent-ly yr's, Peter From mwh at python.net Thu Oct 31 12:44:03 2002 From: mwh at python.net (Michael Hudson) Date: Thu, 31 Oct 2002 17:44:03 GMT Subject: lists, performance.. References: Message-ID: gabor writes: > hi, > > i'm working on a graphic application ( python + opengl).. > > and i have some lists of vertices... but that's not important.. > > let's say a have loooooooong ( long = 500 to 5000 ) lists of relatively That's not loooooooong. That's only just long, in my book. > simple objects.. > > 2 questions: > > 1. is a list implemented as a vector? i mean looking up the n-th element > is done in o[1] (constant time)? > > 2. i want to insert several lists into a big list.. better to say i want > to concatenate them... but i don't really like the 'extent' method, > because i want to do a deep-copy... for example: > list1 = [ ['a','b','c'], [1,2,3,4] ,[5,6,7]] > list2 = [] > list2.extend(list1) > but now if i modify an element in list1, list2 gets modified too.. > for now i'm doing: > > list1 = ... > list2 = ... > > for item in list2: > list1.append(item) > > but maybe this is too slow.. or isn't? ideally i'd like to have > something like reserve in c++.... > so let's say i have a list which len() is 30. now i want to insert > 20elements... wouldn't it be faster to somehow resize the list directly > to 50, and then add the elements? Use slices: >>> a = range(10) >>> a[10:] = range(10) >>> a [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9] > i'm worried about how many times would the list resize itself to be able > to contain the additional 20elements if i would add them one-by-one Standard advice here: don't worry about it now, write your program and if you find it goes too slowly, come back and speed up the bits that will make the most difference. Cheers, M. -- The Internet is full. Go away. -- http://www.disobey.com/devilshat/ds011101.htm From Paul.Casteels at ua.ac.be Fri Oct 18 15:57:58 2002 From: Paul.Casteels at ua.ac.be (Paul.Casteels at ua.ac.be) Date: 18 Oct 2002 21:57:58 +0200 Subject: win32com /makepy Message-ID: <3db067c6@news.uia.ac.be> This simple program works, but is slow when I start adding arrays : from win32com.client import Dispatch xlApp = Dispatch("Excel.Application") xlApp.Workbooks.Add() xlApp.ActiveWorkBook.SaveAs('tutu') xlApp.Quit() del xlApp After I run makepy, to speed it up, (Excel 9.0 Object Library), this program produces : Traceback (most recent call last): File "C:\DOCUME~1\paul\MYDOCU~1\Python\Cvt\testExcel.py", line 6, in ? xlApp.ActiveWorkBook.SaveAs(Filename = 'tutu') File "C:\Python22\Lib\site-packages\win32com\client\__init__.py", line 346, in __getattr__ raise AttributeError, attr AttributeError: ActiveWorkBook Why is ActiveWorkBook no longer available ? I had this with ActivePython 2.2.0, I have updated to 2.2.1 but the resut is the same. -- Paul Casteels Paul.Casteels at ua.ac.be Tel: +32.3.8202455 Fax: +32.3.8202470 University of Antwerp Dpt.Physics Universiteitsplein 1 B-2610 Wilrijk Belgium From mennsimons at gmx.net Mon Oct 7 12:57:42 2002 From: mennsimons at gmx.net (Ulli Stein) Date: Mon, 07 Oct 2002 18:57:42 +0200 Subject: unicode woes References: Message-ID: Matt Gerrans wrote: >> - Never mix byte strings and Unicode strings (unless the byte strings >> are restricted to bytes <127, perhaps). > > Could you elaborate a bit more on this point? I thought this was okay to > do, since the byte string will be promoted to unicode. For instance: > >>>> 'abcd' + u'zyxw' > u'abcdzyxw' > > Is this an acceptible thing to do? It would be very nice. But since the coercion would take the default encoding this is not acceptible. Ulli From tim.one at comcast.net Wed Oct 2 14:39:18 2002 From: tim.one at comcast.net (Tim Peters) Date: Wed, 02 Oct 2002 14:39:18 -0400 Subject: Decimal arithmetic, was Re: Python GUI app to impress the boss? In-Reply-To: <00d001c269c2$97f9d620$ba01010a@local> Message-ID: [Tim] >> Then please help Doug do that, including *defining* the >> rounding disciplines you think are needed; I was never able >> to bully those out of its users, [Chris Gonnerman] > I keep hearing this... what is the problem, exactly? I think the replies (including two of your own ) spoke more eloquently to this point than I could. The rules various commercial apps want are utterly arbitrary by any rational criterion ("always round up", "round up over 0.4", "round up over 0.7", "it depends on the *next* digit too", etc), but that doesn't mean an arbitrary piece of code satisfies the requirements. If I were still doing this, I expect I'd invent a way for users to plug in their own "final rounding" function, and explicitly disown responsibility for guessing what they want. From nomad*** at ***freemail.absa.co.za Fri Oct 4 17:41:00 2002 From: nomad*** at ***freemail.absa.co.za (Nomad) Date: Fri, 04 Oct 2002 23:41:00 +0200 Subject: PyGTK on Win32 References: <9be5e130.0210010514.5f3edd23@posting.google.com> Message-ID: <3eirpuc5rt6imttbfhaf3pp923t2hhai5h@4ax.com> On Wed, 02 Oct 2002 13:38:25 +0200, Thomas Guettler wrote: >Hemanth P.S. schrieb: >> Has anyone used PyGTK on Windows? >> How easy/difficult it is compared to wxPython? > >I prefere pygtk to wxPython. Unforunately >it is not that easy to get it running on win32. >You need to download a lot of libraries. > >I prefere it because there are not so many layers: > > wxpython - wxwindows - wxgtk - gtk (on unix) > > pygtk - gtk > > thomas Sure, but the OP is askign about Windows, and there you get: wxpython - win32api rather than pygtk - gtk - win32api (on win32) -- Nomad Wondering of the vast emptyness of the 'net in search of something cool. From maxm at mxm.dk Mon Oct 14 07:46:00 2002 From: maxm at mxm.dk (maxm) Date: Mon, 14 Oct 2002 13:46:00 +0200 Subject: info about list comprehension References: Message-ID: <3DAAAE78.8050707@mxm.dk> Fabrizio wrote: > Where can I find information about list comprehension (explaination, > tutorial, etc.) ? > > I have tried to browse the Python documentation and the tuttorial, but with > little results. It is really very simple, I don't think you will need a tutorial. A list comprehension is just a short form of an often re-occuring piece of code. # Common data start_list = [-5,-4,-3,-2,-1,0,1,2,3,4,5] # the usual way to do it result_list = [] for item in start_list: if item > 0: result_list.append(item) # list comprehension result_list = [item for item in start_list if item > 0] regards Max M From tjreedy at udel.edu Wed Oct 9 14:30:17 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 9 Oct 2002 14:30:17 -0400 Subject: partial list sort References: <20021009094141.GA852@jsaul.de> <20021009163345.GD1157@jsaul.de> Message-ID: "jsaul" wrote in message news:20021009163345.GD1157 at jsaul.de... > * Eddie Corns [2002-10-09 14:48]: > > Hint: list[x:y] is a COPY of the elements ie a new list. > > That's what I also thought initially. Then you were correct and should have programmed with that in mind. I gave you the fix you need. In Python, a slice of a builtin sequence type is a separate sequence of the same type. Period. No argument possible. User-defined classes can do otherwise. In Numerical Python, a slice of an array is not an array but a view into the same array. This is for efficiency when working with mega-item arrays, but it is not standard Python. >But if in 'sort_components' I introduce the assignment > > list[0][0] = 9 Irrelevant. The copy is a shallow (1 level) copy. Here you are reaching into and modifying a 2-list that is a member of both the original list and the slice extracted from it. Terry J. Reedy From teaandbikkie at aol.com Tue Oct 8 09:08:54 2002 From: teaandbikkie at aol.com (TeaAndBikkie) Date: 08 Oct 2002 13:08:54 GMT Subject: Python + Win32: Cut/Paste w/o GUI References: <3aAo9.18762$vg.53127@news-server.bigpond.net.au> Message-ID: <20021008090854.16948.00000333@mb-fd.aol.com> >Subject: Re: Python + Win32: Cut/Paste w/o GUI Mark Hammond wrote: >TeaAndBikkie wrote: >> I use the following variation, in case the clipboard contains other stuff >than >> text... does anyone know if this is necessary? >> >> def GetClipboardText(): >> import win32clipboard, win32con >> win32clipboard.OpenClipboard(0) >> clip_data = win32clipboard.GetClipboardData(win32con.CF_TEXT) >> clip_text = str(clip_data) >> win32clipboard.CloseClipboard() >> return clip_text >> >> --regards, Misha > >The docs for GetClipboardData say: > >Parameters >format=CF_TEXT : int > >So the param is not necessary. As the result is always a string object >(except when format is CF_UNICODETEXT), the str() is not necessary >either. If the clipboard contains non text information (such as a >bitmap), requesting it as such may will return a string, but requesting >it as CF_TEXT is likely to give an exception. Thanks for pointing this out Mark. I missed this the first time :) --Misha From chris.gonnerman at newcenturycomputers.net Wed Oct 30 08:57:49 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Wed, 30 Oct 2002 07:57:49 -0600 Subject: Did someone turn down the volume? References: <15800.4490.707995.313286@montanaro.dyndns.org> <002501c27bc2$76b2dae0$ba01010a@local> <15800.41069.748576.14291@montanaro.dyndns.org> Message-ID: <003101c2801c$596dc180$ba01010a@local> Hey, are they *ever* going to get that newsfeed fixed? Does anyone know? I miss my Python mail... Yes, I know I can just use a newsreader... but since, like, NOBODY on my ISP uses USENET they don't appear to have a feed set up. (I am emailing the support team to find out for sure.) I've grown accustomed to reading comp.lang.python via the python-list, though; I sure hope I can again soon. Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From maxm at mxm.dk Wed Oct 2 04:29:58 2002 From: maxm at mxm.dk (Max M) Date: Wed, 02 Oct 2002 10:29:58 +0200 Subject: future of python vs java? References: <3d9aabec@news.starhub.net.sg> Message-ID: <3D9AAE86.5070106@mxm.dk> 2cents wrote: > My questions: > -How is the future of python? (probably as compared to Java) It is very bright! In 3 years, 2 months, 4 days and 27 minutes Python will be the most widely used language in the world for building web applications. regards Max M ;-) -- > > > From glingl at aon.at Thu Oct 3 16:52:26 2002 From: glingl at aon.at (Gregor Lingl) Date: Thu, 03 Oct 2002 22:52:26 +0200 Subject: A challenge from the Mensa Puzzle Calendar References: Message-ID: <3D9CAE0A.5090600@aon.at> Chris Myers schrieb: > I have the "Mensa Puzzle Calendar" on my desktop, and one of the first > things I do in the morning, aside from checking my email, is to try to > solve the daily puzzle. Most of them are word-type problems, > cryptograms, anagrams, age problems, etc., but today's was a nice > numerical challenge that lent itself to writing a program to solve it: > > > The following multiplication example uses all the digits from 0 to 9, > and X's have been used to represent numbers, not the multiplication > sign. > > 7XX > XX > ----- > XXXXX > > > I wrote (IMHO) a very nice piece of python code to solve this for me, > and then generalized it a bit: What if the first digit (7) is not > given? How many unique solutions do we get and what are they? (I > included those numbers that started with 0 for consistency.) Just to contrast yours: a quick and dirty solution using at least on pythonesque feature: >>> def contains_all_digits(a,b,c): x = str(a)+str(b)+str(c) if len(x) == 9: x+="0" # if one of them has a leading 0 if len(x) != 10: return 0 for d in "0123456789": if d not in x: return 0 return 1 >>> print [(x,y,x*y) for x in range(1000) for y in range(100) if contains_all_digits(x,y,x*y)] [(138, 42, 5796), (157, 28, 4396), (159, 48, 7632), (186, 39, 7254), (198, 27, 5346), (297, 18, 5346), (297, 54, 16038), (345, 78, 26910), (367, 52, 19084), (396, 45, 17820), (402, 39, 15678), (483, 12, 5796), (495, 36, 17820), (594, 27, 16038), (715, 46, 32890), (927, 63, 58401)] Is this correct? Regards, Gregor L. > > I'm a puzzle kind of guy, so I thought some of you might be, too. > I'd be very curious to see the kind of solutions people come up with. > My solution ended up being a total of 19 lines of code, including a > print statement to give me a nice formatted output for each solution, > resembling the initial problem from the calendar. > > OK, folks. The gauntlet is down. Have at it! > > (NOTE: I realize this is not really a Python thingy, but more of an > algorithm design thingy, but nonetheless, fun.) From oeschger at netscape.com Sat Oct 5 19:49:53 2002 From: oeschger at netscape.com (Ian Oeschger) Date: 05 Oct 2002 16:49:53 -0700 Subject: PhotoImage: iterating over a list of images Message-ID: Why does the example below display only img4.gif and not any of the others. All of them are sitting in the same directory. Is there something wrong about the way that I iterate over the list?? If I give a different variable to each icon name and create PhotoImages and Buttons four different times, it seems to work. Thanks for any advice. .ian #! /usr/bin/env python from Tkinter import * import Pmw icon_list = ['img1.gif', 'img2.gif', 'img3.gif'] def makeBtn(icon): Button(root, width=24, height=24, image=PhotoImage(file=icon), command=sys.exit).pack(side=RIGHT, padx=5, pady=5) ################################################# root = Tk() root.title('test') icon = PhotoImage(file='img4.gif') main_btn = Button(root, width=24, height=24, image=icon).pack(side=RIGHT, padx=5, pady=5) for icon_name in icon_list: makeBtn(icon_name) ################################################## root.mainloop() -- Ian Oeschger Netscape Communications From fgeiger at datec.at Wed Oct 9 13:54:55 2002 From: fgeiger at datec.at (F. GEIGER) Date: Wed, 9 Oct 2002 19:54:55 +0200 Subject: [OT] XHTML -> XHTML: How can entities preserved? References: Message-ID: <3da46d76@news.swissonline.ch> Thank you, Harvey, this doesn't quite do the trick. '&nbsp;' in the DTD transforms ' ' into '&nbsp;', which shows up as ' ' in the browser. I could do a replacement of all '?' etc. into 'ö' etc. after the XSLT processor has done its job. The '&nbsp;' could then be replaced into ' '. Weird... Thanks again and best regards Franz GEIGER "Harvey Thomas" schrieb im Newsbeitrag news:mailman.1034156489.26032.python-list at python.org... F. GEIGER wrote > I do process XHTML files with a Python app, that calls a couple of > processing objects. > > One of them is a class called Shaper. The Shaper takes an > XHTML file as > input, processes all H1, H2, etc. elements and outputs it > again into an > XHTML file. It does so by calling an XSLT processor. > > The problem here is, that entities are converted, e.g. > ' ' becomes ' '. > This is not what I want. I want all entities being preserved for the > client's browser. > > As my app runs on a W2k box, I use the MS XSL processor. In > their help they > show a method to preserve entities: cdata-section-elements. > Actually all > data defined by cdata-section-elements are put into CDATA > sections. But this > is not for HTML output: "HTML does not recognize CDATA > sections. Do not use > this option when generating HTML." > > I guess this not an MS XSL issue but a general XML/XSL issue, right? > > Any idea? > > Many thanks and best regards > Franz GEIGER > This is an XML issue. The creators of XML decided in their wisdom that amongst the facilities of SGML they would drop was SDATA entities. This causes the type of problem you have when you don't want entities resolved to something other than themselves.   is not really an entity, it is a character reference I suspect that in you DTD you have Try replacing this and similar declarations in the DTD with Harvey _____________________________________________________________________ This message has been checked for all known viruses by the MessageLabs Virus Scanning Service. From bokr at oz.net Sun Oct 6 16:34:37 2002 From: bokr at oz.net (Bengt Richter) Date: 6 Oct 2002 20:34:37 GMT Subject: How to use the exec statement References: <3d9eca56_3@news.newsgroups.com> <3da02072_7@news.newsgroups.com> <020o9.15370$cS4.608697@news2.tin.it> <3da093bc_5@news.newsgroups.com> Message-ID: On Sun, 06 Oct 2002 20:09:06 GMT, Alex Martelli wrote: [...] >namespace = {} ># populate dict namespace with whatever you want, e.g.: >import math >namespace.update(math.__dict__) ># etc etc Just a style nit. How about namespace.update(vars(math)) ? ISTM all those long underscores look like insider hacks instead of standard usage, though I realize the __XXX___ convention is pervasive (and hopefully stable ;-) Regards, Bengt Richter From psimmo60 at hotmail.com Wed Oct 23 08:57:20 2002 From: psimmo60 at hotmail.com (Paul Simmonds) Date: Wed, 23 Oct 2002 12:57:20 +0000 Subject: Passing default class attributes across modules Message-ID: Greetings all, I've been working on this problem for a while now, and I'm not getting anywhere, so I think it's time I asked for some help. I've got a Tkinter Dialog box, which takes a list of class 'pointers' (I'm not sure what they're really called, that's just my C background creeping in) and it prints out all the class attributes in two side by side listboxes showing name and value, and allows the user to examine the contents of every member of the list. The Dialog itself allows the user to add/remove attributes to individual classes, or to add/remove class instances from the list. I managed to get the dialog working and everything for a single class def, but it bulked out the code in the master GUI window module, which I was intending to be a stepping stone/throw away prototype. So, I've moved the code into a general widgets module, and with a couple of changes, it works fine...except for the adding of new class instances. My classes are defined as the example below: class Knight(object): name="Lancelot" title="Sir" favcolour="Blue" What I really want is a way to pass the default values so I can put them straight into a new class instance. I have tried making the first member of the class list a default object, then putting the values from that into a blank class: import tkSimpleDialog class MemberDialog(tkSimpleDialog.Dialog): def __init__(self,parent=None,title=None,list=[]): self.toplist=list #List of classes-[0] contains defaults ## # Adds new program to registry def onNew(self): name=tkSimpleDialog.askstring("New Entry", "Type the name of the new registry entry") if name: self.toplist.append(self.BlankClass()) defaultcontents=dir(self.toplist[0])\ [14:len(dir(self.toplist[0]))] for entry in range(14,len(defaultcontents)): self.toplist[len(self.toplist)-1].\ __setattr__(contents[entry],self.toplist[0].\ __getattribute__(defaultcontents[entry])) class BlankClass(object): pass The code above assumes there's only ever going to be 14 builtin methods in a new-style class. If there's a quick fix for that, please let me know. When I run the code above with a class similar to the example, then later try to access the '.name' attribute of the new instance, I get a 'BlankClass object has no attribute name', and, sure enough, when I print the dir() contents of the last member of self.toplist, only the object builtin methods are shown. Any hints would be most welcome. Thanks in advance, Paul ********************************************** I used to have a handle on life, but it broke. ********************************************** _________________________________________________________________ Get a speedy connection with MSN Broadband.? Join now! http://resourcecenter.msn.com/access/plans/freeactivation.asp From peter at engcorp.com Thu Oct 3 08:08:06 2002 From: peter at engcorp.com (Peter Hansen) Date: Thu, 03 Oct 2002 08:08:06 -0400 Subject: Deleting the first element of a list References: <3d9b72c0_5@news.newsgroups.com> <3D9B78EC.B5316B9B@alcyone.com> <3d9b8082$1@news.sentex.net> <3D9BC6F0.4080500@cygnus-software.com> <3d9bd845@news.sentex.net> Message-ID: <3d9c3323@news.sentex.net> Alex Martelli wrote: > Peter Hansen wrote: >>Bruce Dawson wrote: >> >>>This changes it from O(n^2) to O(n), which could make it run thousands >>>of times faster. >> >>You're making assumptions, possibly good ones, about the implementation >>of the list object in Python. It's possible, though obviously unlikely, >>that the list is reallocated and copied every time it shrinks by even >>one element. (I'm just pointing this out for discussion purposes... >>no doubt it doesn't work that way.) That would leave it at O(n^2). > > Python does not specify the O()-behavior of its built-in type's operations > (the way C++'s standard library does), but I think I have the next best > thing -- Tim Peters' review of my forthcoming Nutshell book's chapter on > optimization, which does devote some time to documenting that behavior. > For x>0, "del somelist[x]" is O(len(somelist)-x) -- you can count on > that as well as you can count on most things in this sublunar orb. > > IOW, I don't think these "discussion purposes" serve any concrete > purpose in this context. Sure they did... they brought out your nice response. That is, after all, what "discussion purposes" means. ;-) > "del alist[0]" must copy N-1 references; "alist = alist[1]" must > perform the same copies plus one allocation and one freeing. So, > the former's performance "can't" (with reasonable certainty) be > worse than the latter's, but you can't predict how much better -- > surely not across platforms. Still, if you must choose between > the two ways of expressing functionality that is equivalent to > your application, the former is clearly better. Taking note again of Timothy Delaney's point that in fact the functionality is *not* equivalent: del alist[0] will throw an exception if the list is empty, while slicing will not. I think this all just reinforces the claim that these choices should generally be made on the basis of readability rather than performance. -Peter From logistix at zworg.com Thu Oct 31 16:11:56 2002 From: logistix at zworg.com (logistix) Date: 31 Oct 2002 13:11:56 -0800 Subject: Asking a user for the root password and executing root only commands... References: <3DC14181.BC7677D7@felis.uni-freiburg.de> Message-ID: > > > Is /home mounted nosuid on your system? > > The (few) Unices I know don't allow suid root > scripts. And they are right IMVHO. > What system do you've got? > BSD, specifically OpenBSD 3.2. Didn't occur to me that that 'feature' would be shut off in Linux (which I'm guessing the above poster uses since he doesn't have a wheel group). Of course you could always just setuid root on python itself ;) From mongo57a at comcast.net Tue Oct 8 15:55:54 2002 From: mongo57a at comcast.net (mongo57a at comcast.net) Date: Tue, 8 Oct 2002 19:55:54 GMT Subject: Python-mysql: Still stuck. Message-ID: <3da326da$1_4@goliath.newsgroups.com> Having (still) a problem getting MySQL and Python to work (MySQLdb), and I'm running out of hair to pull out. Downloaded and installed python2.2.1. (works fine) Downloaded and installed MySQLdb. Didn't work. Looking for libmysqlclient.so.9, and I've got so.10 installed (ls libmysqlclient* yields .....so.10). So I deleted the MySQL install, downloaded the source, built it using: python2.2 setup.py build python2.2 setup.py bdist_rpm and installed the package. Problem now is that the package is installing to my python1.5 directories - and not the 2.2. It probably also means that the build did not grab the ...so.10 libs. Any help would be appreciated.... -----------== Posted via Newsfeed.Com - Uncensored Usenet News ==---------- http://www.newsfeed.com The #1 Newsgroup Service in the World! -----= Over 100,000 Newsgroups - Unlimited Fast Downloads - 19 Servers =----- From aleax at aleax.it Thu Oct 10 05:37:28 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 10 Oct 2002 09:37:28 GMT Subject: No tabs in post PLEASE!!! (was Re: partial list sort) References: <20021009094141.GA852@jsaul.de> Message-ID: Terry Reedy wrote: ... > Tabs are bad for Usenet posting if you want stupid people like me who > use Outlook Express to read posted code. Seconded! They're almost as bad for (expletive deleted) people like ME, who use KDE's KNode (0.6.1 with KDE 2.2.2 at least, haven't tried more recent versions yet). PLEASE folks, even if you're tabs-maniacs, make SURE you turn them into spaces when posting or mailing your sources...!!! Alex From pobrien at orbtech.com Wed Oct 2 17:06:20 2002 From: pobrien at orbtech.com (Patrick K. O'Brien) Date: Wed, 2 Oct 2002 16:06:20 -0500 Subject: Need help porting Prevayler (Java) to Python In-Reply-To: Message-ID: [Michal Wallace] > I like the idea of persisting the commands, but the idea of > writing your own for every Add/Insert/Delete seems to be > java nastiness to work around the static typing. > > I don't think I would port it directly; it's just not very > pythonic. Instead, wouldn't you want something like: I was planning to make it more Pythonic/transparent after it was ported. There is more than one way to approach the issue of transparency and I was thinking that one or more solutions should be able to be layered on top of, or in addition to, the default command mechanism. > Anyway, doesn't ZODB do all this? And more. But ZODB isn't pure Python (uses some C code and therefore requires a C compiler or compiled binaries) and is a bit complex for some situations. That's not to say that I think there is anything wrong with ZODB. I don't. I was just looking for something simpler and Prevayler caught my eye. I figured I'd start with the Prevayler approach and see if/where/when it breaks. I think there is room in the Python persistence domain for an approach like Prevayler. It strikes me as fitting nicely between pickles and ZODB. PythonCard applications, for example, might benefit from a Prevayler type approach to persistence. And when you add Pyro (Python Remote Objects) to the mix, it could get really interesting. Pat -- Patrick K. O'Brien Orbtech ----------------------------------------------- "Your source for Python programming expertise." ----------------------------------------------- Web: http://www.orbtech.com/web/pobrien/ Blog: http://www.orbtech.com/blog/pobrien/ Wiki: http://www.orbtech.com/wiki/PatrickOBrien ----------------------------------------------- From martin at v.loewis.de Sat Oct 12 19:00:43 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 13 Oct 2002 01:00:43 +0200 Subject: Internationalization bug?? [Python 2.2.1, RedHat 8.0, Swedish] References: <7d546104.0210120857.3f4e3857@posting.google.com> Message-ID: urban.anjar at hik.se (Urban Anjar) writes: > >>> S = '???' > >>> print S > ??? > >>> print len(S) > 6 > Seems like every swedish character occupies 2 byte > and len() returns number of byte but not number of > characters... It appears you are using an UTF-8 locale. In UTF-8, every accented latin character takes two bytes; many characters (CJK in particular) even take three bytes. You are somewhat misguided assuming that each character takes only a single byte. If that was the case, you could only support 256 characters, but UTF-8 (and Unicode) supports many more characters. Perhaps you misinterpreted the meaning of the len function: For a byte string, it gives you the number of bytes, not (necessarily) the number of characters. To work with characters, you may want to try Unicode. If you do s = unicode(s,"utf-8") print len(s) you should see that you really have three characters only. > Of course I can analyze how characters are representated in detail > and make some kind of workaround, but I think this is not the Python > way. In assembler or C I have to think of things like that but do I > have to do that in Python? If you use byte strings, yes. If you use Unicode strings, you can revert the string on the character level. Of course, to print it on your terminal, you have to convert it back to the encoding your terminal uses, i.e. s = rev(s) print s.encode("utf-8") Regards, Martin From brueckd at tbye.com Tue Oct 8 12:21:08 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Tue, 8 Oct 2002 09:21:08 -0700 (PDT) Subject: Code marshalling question. In-Reply-To: Message-ID: On Tue, 8 Oct 2002 sismex01 at hebmex.com wrote: > I've had this question for a while. Is there a way to marshal > a segment of code into a string, which can then be transported > (via whatever method), such that the code segment can be > unmarshalled later and executed? The marshal module can marshal code objects: def f(x): print x import marshal marshal.dumps(f.func_code) But IMO an even better approach is to just send the .py file, save it to some local file, and then import that module. -Dave From martin at v.loewis.de Sun Oct 13 15:36:44 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 13 Oct 2002 21:36:44 +0200 Subject: building extensions with gcc and python 2.2 References: Message-ID: Ken Seehof writes: > Should I use Cygwin or Mingw? If you use Cygwin, your users will need a complete Cygwin installation, including the Python that comes with cygwin; you will not be able to use your extension modules with PythonLabs Python, ActivePython, or the Win32 extensions. If you use Mingw, it probably will not work without tricks being done to the import library. Regards, Martin From andrews at pcug.org.au Sat Oct 12 20:43:39 2002 From: andrews at pcug.org.au (Avery Andrews) Date: Sun, 13 Oct 2002 10:43:39 +1000 Subject: Monitor module imports?/AOQ In-Reply-To: References: Message-ID: I found that sys.modules in the program after all the modules would have been loaded will provide the info On Sun, 13 Oct 2002, Avery Andrews wrote: > > Does anyone know an easy way to record the modules that a Python program > is loading - the profiler records the Python ones but not extension > modules. What I'm interested is the possibility of producing 'MiniPy's > that contain only the stuff needed to run a given application. > > Thanks. > > > From mcfletch at rogers.com Wed Oct 9 11:02:10 2002 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Wed, 09 Oct 2002 11:02:10 -0400 Subject: Function GetData() in wxImage References: <41c203e.0210070707.15595d94@posting.google.com> <41c203e.0210090020.2bc13985@posting.google.com> Message-ID: <3DA444F2.8060406@rogers.com> Well, don't really know, I learned "on the job", so I've never had a particular place to look for it. The threading module docs give a fairly good overview of what Python offers (outside of micro-threading, which is a more exotic add-on) if you already know principles of threading. Good luck, Mike Anand wrote: >Hi Mike, > > Thanks for help > Could you kindly point me to resources where I can learn about python > multithreading ? > > >Anand > > ... From schneiker at athenalab.com Mon Oct 7 16:38:39 2002 From: schneiker at athenalab.com (Conrad Schneiker) Date: Mon, 07 Oct 2002 20:38:39 GMT Subject: Boa Constructor and CVS question References: Message-ID: "Simon Brunning" wrote: > > From: Conrad Schneiker [SMTP:schneiker at athenalab.com] > > > > I've done some groups.google searching around and have seen > > recommendations > > that the CVS version of Boa Constructor be used (since the .zip and > > win32.exe downloads are way out of date). After some further searching, I > > haven't found any concise documentation about how to go about doing this, > > although there is a considerable abundance of marginally related > > information > > to sift through. > > Have a look at . Ah, the "developer" link. I was thinking like a user. And perhaps relying too much on google. This is just the sort of thing I was looking for. Thanks much, Conrad From max at alcyone.com Tue Oct 22 16:30:08 2002 From: max at alcyone.com (Erik Max Francis) Date: Tue, 22 Oct 2002 13:30:08 -0700 Subject: maintaining order with cgi References: <40a8aa92.0210220509.6f9279ac@posting.google.com> <3DB5A9C0.430F886B@alcyone.com> <3DB5AF44.3030000@gazeta.pl> Message-ID: <3DB5B550.C905A4E0@alcyone.com> bromden wrote: > furthermore, the order of fields may depend on a browser, > and so relying on it seems to be a wrong approach Even if this were sensible, you still have to contend with browser bugs and/or bizarre behavior. For instance, I had a Web application using CGI which relied on being able to detect the buttons (the application kept track of which form was being displayed and which button was hit in order to decide what to do). To make this easier, I prefixed all button names with an underscore and ensured that no non-button controls had such a name. Of course, links (a text-based browser not to be confused with Lynx) has bugs where it will resubmit a query string concatenated to the end of a query, making it look like there are multiple buttons being submitted. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ The people are to be taken in very small doses. \__/ Ralph Waldo Emerson Bosskey.net: Quake III Arena / http://www.bosskey.net/q3a/ A personal guide to Quake III Arena. From eric.brunel at pragmadev.com Thu Oct 17 11:41:51 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Thu, 17 Oct 2002 17:41:51 +0200 Subject: Dynamic copy/paste using DDE with Python on Windows References: Message-ID: Eric Brunel wrote: > Thanks for the explanation, but there's apparently a little > misunderstanding: what I want to do is use the regular "Paste special..." > / "Paste link" feature in Word. In fact, the application is not only for > me: other people will have to use it and creating a macro acting as the > DDE client in each copy of Word for each person using this feature is > really impossible. > > Concerning your other post (DDE: supported or not? broken or not?), again > thanks, but what I'm interested in is just whether the mechanism used to > paste DDE links in Word is still used or not. Apparently, it's not: I > tried to copy a refrence to a DDE topic/item in the clipboard the way it's > described in the MSDN docs (custom clipboard format "Link", reference > formatted like "application\0topic\0item\0\0"), but Word refused to paste > anything from it. The DDE server seemed to work since inserting the DDE > reference in Excel ("application|topic!item") works. But the "paste link" > thing does not. My mistake: it does. I just forgot to include something else than the DDE link in the clipboard, so Word refused to open its "Paste special" box. So I've got it working for text: I can copy text as a DDE link in Python and paste the link in Word. I'll post the code to the Python Wiki when I've cleaned it up (and when I've figured out what is the best place to post it in...) Now, I want to do the same thing, but with a bitmap. A simple BMP would be OK. I've tried it, but I just can't figure out what I must return for the bitmap data (return value of the "Request" method in the object for the DDE topic, as in the DDE example in win32/demos/dde/ddeserver.py): . I've tried to return the handle to the bitmap like when putting the data in the clipboard (result of the GetHandle method on the PyBitmap object), but Word refuses to paste the link . I've tried to return the "bitmap bits" as returned by the GetBitmapBits method of the PyBitmap object: same result . I've tried to return the contents of the bitmap file as a binary string: it made Python crash Did anybody succeed in returning a BMP from DDE? If you did, how did you do it? TIA -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From cnetzer at mail.arc.nasa.gov Wed Oct 9 21:08:52 2002 From: cnetzer at mail.arc.nasa.gov (Chad Netzer) Date: Wed, 9 Oct 2002 18:08:52 -0700 Subject: Tkinter Query In-Reply-To: <7L1p9.484$su4.7497873@news-text.cableinet.net> References: <7L1p9.484$su4.7497873@news-text.cableinet.net> Message-ID: <200210100108.SAA03173@mail.arc.nasa.gov> On Wednesday 09 October 2002 15:05, Newt wrote: > Hi, > > I'm trying to build a form with some rows. [snipped] > In the code above, I'm trying to use svals to hold the values of sval as > they are created. > > When I run this, I get an error that svals is not a global. So two > questions: > 1. How do I make svals into a global? You don't. See below > 2. What is the correct way to implement what I'm trying to do? I haven't looked at what the code is trying to do, just a cursory scan to fix #1 for you. You want to make sval a part of the object state (ie. It stays with the object, and can be used in other member functions). To do this, you refer to it as self.svals, not just svals. The first adds it as a member of the object, the second declares it a local variable, which goes away when the member function returns. So, as a first step, change all the svals to self.svals. Then, since pos doesn't exist in the down() member function, change that too. I think you meant to use 'i'. In any case, the self.svals thing will get you started. -- Chad Netzer cnetzer at mail.arc.nasa.gov From sismex01 at hebmex.com Thu Oct 31 12:24:27 2002 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Thu, 31 Oct 2002 11:24:27 -0600 Subject: Newbie want Python CGI on Mac OS X10.2 Message-ID: > From: Mel Bohince [mailto:melbohince at attbi.com] > > I'm suspicious of the first line: > #!/usr/lib/python I've tried #!/usr/lib/ python, #!/usr/bin/python, > #!/usr/bin/env python > > what exactly is this to be? > Ehh, good reason to be suspicious about it! It's a specially-formatted comment, and it indicates the pathname of the interpreter. You have to look exactly where the "python" executable you need is, and place that full pathname after the "#!". -gustavo From claird at lairds.org Thu Oct 10 08:12:10 2002 From: claird at lairds.org (Cameron Laird) Date: Thu, 10 Oct 2002 12:12:10 +0000 (UTC) Subject: Tkinter Query References: <7L1p9.484$su4.7497873@news-text.cableinet.net> Message-ID: In article <7L1p9.484$su4.7497873 at news-text.cableinet.net>, Newt wrote: >Hi, > >I'm trying to build a form with some rows. Each row consists of a down >button, a label, and an up button. When the down button is pressed, I want . [questions on algorithms and references Alex answered with his usual precision] . . Is your true intent what others commonly call a "spinbox" ? -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From admin at e-tones.co.uk Mon Oct 21 13:09:40 2002 From: admin at e-tones.co.uk (e-tones.co.uk) Date: Mon, 21 Oct 2002 18:09:40 +0100 Subject: New to python References: <3db2fcc9$0$5803$fa0fcedb@lovejoy.zen.co.uk> <5ic6rusts9cruhoasccnsgrpar4ghihak3@4ax.com> Message-ID: <3db43524$0$5809$fa0fcedb@lovejoy.zen.co.uk> Thats spooky... Im not taz higgins, but i program delphi! :D wow, strange. Taz "Carl Caulkett" wrote in message news:5ic6rusts9cruhoasccnsgrpar4ghihak3 at 4ax.com... > On Sun, 20 Oct 2002 19:56:56 +0100, "e-tones.co.uk" > wrote: > > >Cheers, > >Taz > > Is that Taz Higgins aka "The Taz" ? If so, are you still doing Delphi > stuff? I haven't seen you on the Borland newsgroups for many a long > month. > > -- > Carl > From chris.myers at prov.ingenta.com Fri Oct 4 13:15:17 2002 From: chris.myers at prov.ingenta.com (Chris Myers) Date: 4 Oct 2002 10:15:17 -0700 Subject: A challenge from the Mensa Puzzle Calendar References: Message-ID: Thanks, all for your response to my challenge! I'm sufficiently humbled by looking at the quality of code I've read. Some of what I saw was pretty complex for my eyes (I'm still looking over some of it), but IMHO (as OP, judge, and jury for the contest), I choose Raymond Hettinger's entry, based on elegance, innovation and brevity: for a in range(700,800): for b in range(100): digits = list('%d%d%d' % (a, b, a*b)) digits.sort() if digits == list('0123456789'): print '%5d\n%5d\n-----\n%5d' % (a, b, a*b) Which can be easily generalized by changing the first line to for a in range(1000): and the 3rd line to digits = list('%.3d%.2d%.5d' % (a, b, a*b)) in order to catch those solutions with operands and results beginning with '0'. So, my generalized sol'n of Raymond's answer is: for a in range(1000): for b in range(100): digits = list('%.3d%.2d%.5d' % (a, b, a*b)) digits.sort() if digits == list('0123456789'): print '\n%5.3d\n%5.2d\n-----\n%5.5d' % (a, b, a*b) This generalized solution takes less than 4 seconds to run on my computer! My solution, below, took almost 4 MINUTES!! (Again, sufficiently humbled am I) def list_less(short_list): l = range(10) for i in short_list: l.remove(i) return l for a in list_less([]): for b in list_less([a]): for c in list_less([a,b]): for d in list_less([a,b,c]): for e in list_less([a,b,c,d]): for f in list_less([a,b,c,d,e]): for g in list_less([a,b,c,d,e,f]): for h in list_less([a,b,c,d,e,f,g]): for i in list_less([a,b,c,d,e,f,g,h]): for j in list_less([a,b,c,d,e,f,g,h,i]): if (100*a + 10*b + c) * (10*d + e) == \ 10000*f + 1000*g + 100*h + 10*i + j: (A,B,C,D,E,F,G,H,I,J) = (a,b,c,d,e,f,g,h,i,j) print "\n %d%d%d\nX %d%d\n-----\n%d%d%d%d%d\n" \ %(A,B,C,D,E,F,G,H,I,J) I originally thought this was a pretty solution -- not so much anymore. Again, thanks, all for accepting my challenge. Please, post more puzzles of this sort -- anyone. Cheers, Chris PS: Actual solutions to the generalized version of the puzzle: 138 * 42 = 05796 157 * 28 = 04396 159 * 48 = 07632 186 * 39 = 07254 198 * 27 = 05346 297 * 18 = 05346 297 * 54 = 16038 345 * 78 = 26910 367 * 52 = 19084 396 * 45 = 17820 402 * 39 = 15678 483 * 12 = 05796 495 * 36 = 17820 594 * 27 = 16038 715 * 46 = 32890 927 * 63 = 58401 I'm a number theory buff, so I noticed some fascinating things: two of the sol'ns use one of the same operands - 297 THREE of the sol'ns generated the same product!! How cool is that?! :-) From peter at engcorp.com Thu Oct 31 18:03:11 2002 From: peter at engcorp.com (Peter Hansen) Date: Thu, 31 Oct 2002 18:03:11 -0500 Subject: Python rulez References: Message-ID: <3dc1b6c5$1@news.sentex.net> Alessandro Bottoni wrote: > Alle 08:50, venerd? 25 ottobre 2002, Roman Suzi ha scritto: > >>Well... this is kinda test message (i'm checking if >>Python maillist is reaching my mailbox). > > > Welcome to the Python community! Heh heh... Roman's been here rather a while already. He should be saying that to *you*. :-) -Peter From Luis.Apiolaza at utas.edu.au Tue Oct 1 01:22:06 2002 From: Luis.Apiolaza at utas.edu.au (Luis Apiolaza) Date: 30 Sep 2002 22:22:06 -0700 Subject: Accessing MySQL *without* using MySQLdb Message-ID: Hi, I'm writing a few Python scripts for CGI. My hosting company sort of supports Python (it has Python 1.5.2 running in the server - Red Hat Linux + Apache) and MySQL. However, they are not very keen in installing new modules (e.g. MySQLdb). How can I access a MySQL database from Python, without installing new modules? Does anyone have a few pieces of code that would achieve this? Thanks, Luis From gerhard.haering at gmx.de Fri Oct 11 11:18:04 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 11 Oct 2002 15:18:04 GMT Subject: AttributeError with getmail. References: <3DA6A0A3.8010605@adept.be> Message-ID: Stefan - ZipKid - Goethals wrote in comp.lang.python: > except socket.error, txt: > AttributeError: 'module' object has no attribute 'error' > > The problem is NOT with getmail since an identical install on another > system works ok. Your Python installation is broken - it looks like a _socket.so is missing. > I am probably missing a lib or a file somewhere. As I now very > little about python, could someone point me in the correct direction > please. Try removing, then reinstalling Python on this machine. -- Gerhard From sismex01 at hebmex.com Fri Oct 11 13:22:17 2002 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Fri, 11 Oct 2002 12:22:17 -0500 Subject: Stringify object reference? Message-ID: > From: Alan Kennedy [mailto:alanmk at hotmail.com] > > Is there a specific reason why id()'s can't be turned back > into objects? Is it an implementation specific thing? Or is > it to stop people messing with pointers, etc? > > Regards, > > alan kennedy It's an implementation-specific thing to stop people from messing with pointers. ;-) Seriously tho.. Using a dict indexed by id(obj) seems to be the best solution for your particular use. Salutations. -gustavo From spahievi at vega.bg Sun Oct 13 16:01:57 2002 From: spahievi at vega.bg (Niki Spahiev) Date: Sun, 13 Oct 2002 22:01:57 +0200 Subject: How to get a list of table names for a database via ODBC in Windows using In-Reply-To: <7gd7oa.sl3.ln@ix.netcom.com> References: <7gd7oa.sl3.ln@ix.netcom.com> Message-ID: <8722645672.20021013220157@vega.bg> 10/11/2002, 22:49:11, Dennis Lee Bieber wrote: DLB> I tried reading the mxODBC web pages, but couldn't find any way to DLB> override that 6 pt typeface Use minimum font size preference in Mozilla. HTH Niki Spahiev From paul at boddie.net Fri Oct 11 04:36:41 2002 From: paul at boddie.net (Paul Boddie) Date: 11 Oct 2002 01:36:41 -0700 Subject: Python Forms? References: <23891c90.0210100233.48e92d6d@posting.google.com> Message-ID: <23891c90.0210110036.7b8bd7d6@posting.google.com> Ian Bicking wrote in message news:... > On Thu, 2002-10-10 at 05:33, Paul Boddie wrote: > > http://www.python.org/cgi-bin/moinmoin/WebProgramming > > Aha! That page is why I've been seeing people use WebWare all over the > place (instead of the correct Webware). Especially if the incidence of bad capitalisation has increased over the past few weeks. Anyway, I've fixed this on the WebProgramming site now. Paul From shalehperry at attbi.com Thu Oct 31 10:45:33 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Thu, 31 Oct 2002 07:45:33 -0800 Subject: lists, performance.. In-Reply-To: <1036072193.1771.31.camel@wintermute.atriaky.sk> References: <1036072193.1771.31.camel@wintermute.atriaky.sk> Message-ID: <200210310745.33834.shalehperry@attbi.com> On Thursday 31 October 2002 05:49, gabor wrote: > 2. i want to insert several lists into a big list.. better to say i want > to concatenate them... but i don't really like the 'extent' method, > because i want to do a deep-copy... for example: > list1 = [ ['a','b','c'], [1,2,3,4] ,[5,6,7]] > list2 = [] > list2.extend(list1) > but now if i modify an element in list1, list2 gets modified too.. > for now i'm doing: > > list1 = ... > list2 = ... > > for item in list2: > list1.append(item) > >>> import copy >>> print copy.deepcopy().__doc__ Deep copy operation on arbitrary Python objects. From john at splange.freeserve.co.uk Wed Oct 16 08:53:38 2002 From: john at splange.freeserve.co.uk (John Arundel) Date: Wed, 16 Oct 2002 13:53:38 +0100 Subject: How to print an integer with commas; E.g., 3,056,789 In-Reply-To: <20021016120633.22956.56736.Mailman@mail.python.org> References: <20021016120633.22956.56736.Mailman@mail.python.org> Message-ID: <20021016125338.GA7920@homer> On 2002-10-16 at 08:06:33, Padraig Brady warbled: > >Given any integer n, how can I convert str(n) to a string with commas in > >the appropriate places? For example, if n is 3056789, I'd like to convert > >str(3056789) to "3,056,789", for better readability of output. > > Yes wouldn't it be nice to have: > > >>> i=3056789 > >>> print "%h %.2m %.2M %.2k %.2K" % i, i, i, i, i > 3,056,789 3.06M 2.92Mi 3056.79K 2985.15Ki How about: def commaise(seq): if len(seq) <= 3: return seq else: return "".join(commaise(seq[:-3]) + ',' + seq[-3:]) >>> commaise("3056789") '3,056,789' -- "I was an only child... eventually." - Steven Wright --------------------------------------------------------------------- I prefer encrypted mail - http://www.splange.freeserve.co.uk/pgp.html --------------------------------------------------------------------- From hades at silentone.com Tue Oct 15 20:29:44 2002 From: hades at silentone.com (Culley Angus) Date: Wed, 16 Oct 2002 00:29:44 GMT Subject: SOAP frustrations References: <3DAC6F04.2030704@mindspring.com> Message-ID: <3dacafe5.535113252@news.wlg.ihug.co.nz> I guess the SOAP.py module does have it's quirks, and I have also had several frustrating experiances with it. But for me it was the only logical choice, once we made the decision that python was the language of choice (for many other reasons than it's SOAP support). Although it is no longer supported by a commercial concern, the state of the SOAP.py code is far from immature. I am currently running it in a python client application, and it works almost seamlessly with the latest release version of the Apache Axis framework, which we are running on the server. We havn't had to change any major functional area of it at all (we did have to update it a little for python 2.2.1). It did take a while to figure out how it worked, and we are using a seperate wrapper module to access it, but it seems to work just fine. All the best. From ark at research.att.com Fri Oct 18 16:12:19 2002 From: ark at research.att.com (Andrew Koenig) Date: Fri, 18 Oct 2002 20:12:19 GMT Subject: Idiom for 'the lesser of the two'? References: Message-ID: Gordon> There's got to be something simple I'm missing... You Gordon> obviously can't do a < b ? a : b and this a if a < b else b is Gordon> a syntax error. I started playing with lambda functions but I Gordon> didn't have any luck there either. How about min(a, b)? -- Andrew Koenig, ark at research.att.com, http://www.research.att.com/info/ark From abidnego25 at yahoo.com Mon Oct 14 16:46:04 2002 From: abidnego25 at yahoo.com (les) Date: 14 Oct 2002 13:46:04 -0700 Subject: tricky sorting Message-ID: <653cf871.0210141246.607fcef9@posting.google.com> Hi, suppose I have a list of following ########################################## abdng I 10-11 abdns IV 43-45 rshts I 1201-1210 qurst XIII 87-98 .. andng IX 18293-19283 etc ################################# I would like to sort by two fields: first sort by the second column (which is in roman numerals) and then I would like to sort by the last column (only the "from" part only) so the above result would be abdng I 10-11 rshts I 1201-1210 abdns IV 43-45 qurst XIII 87-98 andng IX 18293-19283 I can do this in C with a compare function but i don't know how to write this special compare function in python. can some one help me do this ? thanks From cliechti at gmx.net Tue Oct 1 14:42:21 2002 From: cliechti at gmx.net (Chris Liechti) Date: 1 Oct 2002 20:42:21 +0200 Subject: file open verification References: <9eabe547.0209270710.17ca112d@posting.google.com> <3d99213c.521452@nntp.surry.net> Message-ID: cstrickland at surry.net (Charles W. Strickland) wrote in news:3d99213c.521452 at nntp.surry.net: > On 27 Sep 2002 19:30:38 +0200, Chris Liechti wrote: > >>python473 at yahoo.com (John Howard) wrote in >>news:9eabe547.0209270710.17ca112d at posting.google.com: >> >>> Two questions - somewhat related: >>> >>> Situation - I have several files on an apache server that are being >>> accessed by >>> python programs that are receiving data from html forms. >>> >>> q1: How can the status of a file be checked? If two forms have been >>> submitted >>> and the data is being added to a common file, how do I know that >>> data from both forms are being written correctly to the common file? >> >>don't ever write simultaneous from two processes to one file. your >>choices are: >>- use "locks", so that only writes at a time >>- one server writes the file, logs are directed to that server (like >>syslog on linux) > > Not sure what you mean here. Are you saying that if a server file is > used, then it is not a problem? what's a server file? what i mean is that _somewhere_ there must be a lock than guarantees that one entry is written after an other. there are many solutions for that problem. one is that you use a server that writes the file. all client programs send their messages to that server. or you can do locks on your own, in each of you client programs. when two programms run a the same time, they have to communicate somehow so that only one accesses a resource (e.g. you logfile) at a time. one easy solution is to use a lockfile. (that seems to be an example for lockfiles: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65203) you can avoid lockfiles with a logging server (but somehow there is a lock involved) such a server can use a Queue (in python module with the same name) and one thread that writes the file and many threads that collect the data (e.g. from sockets) and put it in the Queue. > Is that related to his apache > question? Does the apache server handle locks? i dont think that the server does this four your CGI programs. apache has such a logging server which is used to write access and error logs, but i don't think they are available to user CGIs. chris >>all these options ensure that one writes after the other. avoiding >>problems is better than fixing. >> >>> q2: Related to above - really more of a cgi question - does the >>> apache server keep all these file accesses separate some way? >> >>don't know apache. if you manage to limit it on one thread, only one >>can access the file. but iin that case the performace of the server is >>poooooor ;-) -- Chris From cnetzer at mail.arc.nasa.gov Tue Oct 8 15:39:58 2002 From: cnetzer at mail.arc.nasa.gov (Chad Netzer) Date: Tue, 8 Oct 2002 12:39:58 -0700 Subject: Do Tkinter and PIL exclude each other? In-Reply-To: References: Message-ID: <200210081939.MAA30625@mail.arc.nasa.gov> On Sunday 06 October 2002 20:05, Torsten Mohr wrote: > i just installed a new version of my distribution and it seems > that Tkinter and PIL mutually exclude each other. You didn't tell us what distribution (I'm assuming Linux) you are using. RedHat, Mandrake, Debian, Windows? They should work together.: Python 2.2.1 (#2, Sep 13 2002, 23:25:07) [GCC 2.95.4 20011002 (Debian prerelease)] on linux2 >>> import PIL >>> import Tkinter >>> -- Chad Netzer cnetzer at mail.arc.nasa.gov From mstenner at phy.duke.edu Tue Oct 1 16:40:37 2002 From: mstenner at phy.duke.edu (Michael Stenner) Date: Tue, 1 Oct 2002 16:40:37 -0400 Subject: Is the word "Python" copyrighted/trademarked? In-Reply-To: ; from sismex01@hebmex.com on Tue, Oct 01, 2002 at 03:12:32PM -0500 References: Message-ID: <20021001164037.B8452@phy.duke.edu> On Tue, Oct 01, 2002 at 03:12:32PM -0500, sismex01 at hebmex.com wrote: > > From: Troels Therkelsen [mailto:t_therkelsen at hotmail.com] > > > > Hey everybody, > > > > My question is whether the word "Python" classifies as a PSF > > trademark or trade name? Eg., if I wanted to create a web > > server in Python (not that I want to), could I call it > > "Python Web Server" without breaking any rules? > > Hmmm... "Python" is the name of a snake, and it's also > a common english word; I don't think it can be copyrighted. > > ?Can it? Copyright? No. Trademark? Probably. Trademarking is specific to a market. For example, even if it is trademarked in this case, I could still certainly manufacture and sell a "Python" bike pump. For example, "Windows" is trademarked by Microsoft. That is in more common usage than "python" and also refers to a common object. -Michael (Actually, windows isn't a great example because "window" IS common also in the "close that popup window" sense. Just ignore that here. The "there's a draft" sense is not problematic.) -- Michael Stenner Office Phone: 919-660-2513 Duke University, Dept. of Physics mstenner at phy.duke.edu Box 90305, Durham N.C. 27708-0305 From surfdargent at free.fr Mon Oct 14 23:56:31 2002 From: surfdargent at free.fr (=?ISO-8859-1?Q?St=E9phane_Vaxelaire?=) Date: 14 Oct 2002 20:56:31 -0700 Subject: Boost.python from v1 to v2 ? Message-ID: Hello, I'm not a boost.python expert yet but I wondered if migration from boost.python v1 to v2 is easy. In fact I saw some headers not here anymore and changes... Regards, Stephane From xucs007 at yahoo.com Mon Oct 21 14:30:35 2002 From: xucs007 at yahoo.com (Xu, C.S.) Date: 21 Oct 2002 11:30:35 -0700 Subject: how to use smtp starttls() encryption? References: <8f41cfd.0210101719.ad47c7@posting.google.com> <8f41cfd.0210120805.6ced204a@posting.google.com> <8f41cfd.0210162236.3e5c970a@posting.google.com> Message-ID: <8f41cfd.0210211030.33365530@posting.google.com> Hi, > Please upgrade to Python 2.2.2. If that's not possible, get a smtplib.py > of Python 2.2.2 and use it instead. I downloaded Python 2.2.2, compiled and installed. Now starttls() generate problem: > send: 'STARTTLS\r\n' > reply: '220 OpenSSL/0.9.5beta go ahead\r\n' > reply: retcode (220); Msg: OpenSSL/0.9.5beta go ahead > Traceback (most recent call last): > File "aa", line 12, in ? > server.starttls() > File "/usr/local/lib/python2.2/smtplib.py", line 591, in starttls > sslobj = socket.ssl(self.sock, keyfile, certfile) > AttributeError: 'module' object has no attribute 'ssl' Any help? From mwh at python.net Mon Oct 21 05:36:11 2002 From: mwh at python.net (Michael Hudson) Date: Mon, 21 Oct 2002 09:36:11 GMT Subject: Using Python for blogging References: Message-ID: hwlgw at hotmail.com (Will Stuyvesant) writes: > Hello all ! > > reStructuredText (reST) looks cool! So I was thinking about doing > blogging (web logging, sort of keeping a diary at your ISP) with > Python. The existing blogging software I know of positively stinks > IMHO. Hey, I just had that idea! > My ideal thing would be to be able to edit a file at home using reST. > Then I need some scripts to transform that into html and send it to my > ISP. For turning reST into html there are example scripts in the reST > Tools directory. > > I now have some scripts that work. For every day there is a reST file > with name e.g. 291002.txt for date 19 october 2002. And it is in a > directory with name 1002 (guess what:). So you just edit the files > using reST and you write scripts to turn that into html (could just > use html.py in the reST Tools directory). > > But! The resulting html does not really look like I want, I mean I do > not like the fonts and the sizes etc. Unfortunately I do not know > much about HTML so I have a question: How to improve this? > Recommandations? Use CSS? Any pointers on that? Use CSS. Cheers, M. -- For the record, the NTL telephone voicemaze jail is almost as well-planned. I dialled the status recording, which is information- rich in much the same way as 10 Angstroms is a long way... -- Dan Barlow vs NTL: http://ww.telent.net/diary/2002/6/#18.8983 From johnfkeeling at yahoo.com Fri Oct 18 16:01:51 2002 From: johnfkeeling at yahoo.com (John Keeling) Date: 18 Oct 2002 13:01:51 -0700 Subject: SOAP frustrations References: <3DAC6F04.2030704@mindspring.com> <35b736b9.0210180325.3b6e5904@posting.google.com> <3db01b05$0$18872$afc38c87@news.optusnet.com.au> Message-ID: <35b736b9.0210181201.732ffc53@posting.google.com> Derek, I totally agree with you. The only extra that I can offer to what you are saying is that when the organizational politics is sorted, SOAP/HTTP will offer better a compromise to all parties than CORBA/IIOP, in general. This is due to the issue that each CORBA server on a host must have its own port, and the typical implementation of a CORBA system uses multiple servers per host and hence multiple ports. SOAP systems are typically designed with much more conservative use of ports. Cheers, John Derek Thomson wrote in message news:<3db01b05$0$18872$afc38c87 at news.optusnet.com.au>... > Hi John, > > John Keeling wrote: > > > > Over the internet, you really want to use Web Services rather than > > CORBA, because CORBA/IIOP uses multiple ports that have to be > > explicitly allowed on the firewall ( on both the client and server > > side). This is an admin and security issue. > > Yes. It *is* a security issue. By misusing port 80 for remote procedure > calls, you are violating the contract between you and your sysadmin, and > quite likely violating your organization's (our your client's) security > policy. That port was opened to allow web pages to be served up, not to > run bits of arbitrary code on request. > .... From martin at v.loewis.de Wed Oct 16 16:00:38 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 16 Oct 2002 22:00:38 +0200 Subject: Tcl8.3 Problem: Can't find correct init.tcl file References: <4378fa6f.0210161155.264f6474@posting.google.com> Message-ID: mnations at airmail.net (Marc) writes: > And: Where can I change Python to include the paths where it should > look? Try setting the TCL_LIBRARY library? Regards, Martin From timothy.williams at nvl.army.mil Thu Oct 3 11:25:24 2002 From: timothy.williams at nvl.army.mil (Tim Williams) Date: 3 Oct 2002 08:25:24 -0700 Subject: Tix.FileEntry directory Message-ID: I'm trying to use the Tix.FileEntry widget. I can set the default value, but how do I specify what directory to initially look in? From nadavh at envision.co.il Wed Oct 16 08:05:48 2002 From: nadavh at envision.co.il (Nadav Horesh) Date: Wed, 16 Oct 2002 14:05:48 +0200 Subject: Compiling python 2.2.2 with gcc 3.2 Message-ID: <3DAD561C.3060703@envision.co.il> I tried to compile python2.2.2 under RH 7.2 with gcc 3.2. I got weired error messages from incopatibility between "fpos_t" and "int", to obsoleteness of "tmpname". Did anyone succeed? Nadav. From mwh at python.net Mon Oct 21 08:53:40 2002 From: mwh at python.net (Michael Hudson) Date: Mon, 21 Oct 2002 12:53:40 GMT Subject: Most efficient method to search text? References: Message-ID: bokr at oz.net (Bengt Richter) writes: > Thanks. I wonder what would happen if you used word lists and files > guaranteed *not* to have any hits, so they'd all be searched to the end. > Or what was your mix (no of search words, length of files, hit distribution)? Oh, no hits at all. I was making up random words of length 10. > >I'm sure Tim once said something along the lines of "Python doesn't > >give much advice for getting good performance, beyond a not-so-subtle > >hint to exploit dicts for all they're worth" but I can't find it now. > > > There's probably a lot to learn from the dictionary implementation code > ... one of these days ;-) Not as much as there is to be learnt from using it, I suspect. Cheers, M. -- I've even been known to get Marmite *near* my mouth -- but never actually in it yet. Vegamite is right out. UnicodeError: ASCII unpalatable error: vegamite found, ham expected -- Tim Peters, comp.lang.python From 2002 at weholt.org Fri Oct 4 22:38:25 2002 From: 2002 at weholt.org (Thomas Weholt) Date: Sat, 05 Oct 2002 02:38:25 GMT Subject: What a mess! References: <3d9e2b8f$1_8@goliath.newsgroups.com> Message-ID: Perhaps not what you want to hear, but if you're not a fanatic RedHat-user you might want to try Mandrake Linux instead. The latest version, 9.0, has Python 2.2.1, Emacs/XEmacs and VIM with python-mode installed and much more. Very up to date. Never had any trouble with it and it's a breeze to install ( at least in my experience ). I find it a very python-friendly linux-distro and a good development platform. Thomas wrote in message news:3d9e2b8f$1_8 at goliath.newsgroups.com... > On Redhat 7.3. Downloaded latest Python binaries (rpm) and tried to install. > Got lots of errors like: > > "file /usr/lib/python2.2/........ from install of python2-2.2.1-1 conflicts > with file from package python2-2.2-16" > > Got the same errors on install or update. > > So in my infinite wisdom (or lack of....) I decided to try and uninstall > Python and start over. So I manually (isn't there a way to automatically > uninstall ????) deleted the install (directories) for 2.2. That left me > still with directories for Python 1.5 and Python2. > > Started over with an rpm install of 2-2.2.1-1. Got the same errors. There > must be more going on here than I understand. > > Thanks. > > > -----------== Posted via Newsfeed.Com - Uncensored Usenet News ==---------- > http://www.newsfeed.com The #1 Newsgroup Service in the World! > -----= Over 100,000 Newsgroups - Unlimited Fast Downloads - 19 Servers =----- From ghowland at lupineNO.SPAMgames.com Tue Oct 22 00:51:41 2002 From: ghowland at lupineNO.SPAMgames.com (Geoff Howland) Date: Tue, 22 Oct 2002 04:51:41 GMT Subject: best way to learn References: Message-ID: On Mon, 21 Oct 2002 20:20:20 -0700 (PDT), ed wrote: >Hey all. I'm a python newbie, but I have experience >in other very high level languages, mainly php. >I was wondering what is the best way to become >proficient in python quickly? I would say this is similar for all languages. You should pick a project that interests you, but is not so complex you cant just start working on it, and that will drag you along having to learn the language. >Should I get a book, if so which one? >"Learning python", "programming python", "python >cookbook"? >Or can I get pretty much everything I need on the web, >like a lot of good tutorials and some good language references? I found the python tutorial pages on the python.org site, and the modules to answer a lot of my inital questions. So they are a good part of it. I also bought 'Core Python Programming' by Wesley J. Chun (Prentice Hall) and it's been very useful. I use its tables on dict/string/list functions enough I should probably photocopy them, or get a memory. :) >If I get a book I'd like to get one that works as a >newbie tutorial but by the end of the book deals with some advanced >topics and will also work somewhat well as a reference. Is that >asking too much? Might be, others may have advice on books that actually do this. I haven't found many that actually seem to work at the right pace for the amount of material they have to cover in a coherent manner. That's why I suggest the 'pick a project' method. Once you've done one, refactor it and/or do another and keep going. Making things work in a non-trivial project will cause you to hit your toe against quite a few walls until you find your light switch. Then new programs explore new territory... -Geoff Howland http://ludumdare.com/ From david at no.westcontrol.spam.com Tue Oct 8 06:38:01 2002 From: david at no.westcontrol.spam.com (David Brown) Date: Tue, 8 Oct 2002 12:38:01 +0200 Subject: Misc questions about type objects and Python 3.0 References: Message-ID: > > 1. Is it the plan that Python 3.0 be binary compatible with Python > 2.x? > > 2. If it isn't (I'm guessing it will be), is it the plan to keep > reference counting? It seems to me that getting rid of reference > counting might be the first step to getting rid of the GIL. First, I would think that removing reference counting would wildly change the way Python works (correct me if I'm wrong here - I program with Python, but I haven't studied its implementation). I don't see how you can get efficient garbage collection without some sort of reference counting. Second, why do you want to get rid of the GIL? There was a thread a while back (I know, because I asked the question) about threading and the GIL, and as far as I learned from the thread, there are no real disadvantages of the GIL (and many big advantages) except on heavily cpu-instensive python code running on SMP computers where the underlying C routines don't release the GIL (well-behaved time-consuming C functions do release the GIL). > > 3. The docs say types choose their member resolution order (?), but > I'm wondering if that's just a temporary hack to support both > old-style and new-style classes. After old-style classes are > dropped, will MRO be fixed for all types? (And is it really that > useful for it to be customizable?) > > 4. What is the point of having both tp_base and tp_bases in the type > structure? > > 5. What's the deal with unification of numeric types? What's expected > or planned or hoped for in 3.0? > > > -- > CARL BANKS > http://www.aerojockey.com From forodejazz at yahoo.es Thu Oct 3 11:59:40 2002 From: forodejazz at yahoo.es (=?ISO-8859-1?Q?David_Asorey_=C1lvarez?=) Date: 3 Oct 2002 08:59:40 -0700 Subject: PyGTK on Win32 References: <9be5e130.0210010514.5f3edd23@posting.google.com> Message-ID: <1759581e.0210030759.3e87da9c@posting.google.com> hemanth_sethuram at yahoo.com (Hemanth P.S.) wrote in message news:<9be5e130.0210010514.5f3edd23 at posting.google.com>... > Has anyone used PyGTK on Windows? > How easy/difficult it is compared to wxPython? > Yes, I've found some nice packages: wGlade 0.1: http://wingtk.sourceforge.net/ PyGTK 0.6: ftp://ftp.logilab.org/pub/win32/pygtk/pygtk_py21/setup.exe Python 2.1.3: http://www.python.org/ftp/python/2.1.3/ The look is very "Gtk", not native. It can be a penalty for your users. I think (IMHO) that pyGtk's API is easiest than wxPython, and there is Glade, a good tool. Regards. -- David Asorey ?lvarez. Madrid (Spain) forodejazzNO at SPAMyahoo.es From rmunn at pobox.com Thu Oct 17 09:59:25 2002 From: rmunn at pobox.com (Robin Munn) Date: Thu, 17 Oct 2002 13:59:25 GMT Subject: Modules - problem References: Message-ID: In article , A wrote: > Hi, > I would like to access a variable in one module from another module.For example > > The main module is like this > ############# > #Main modul z1.py > import z3 > print "x variable=", z3.x > ########### > > where z3.py module is like > > ######## > #My module z3.py > global x > x=11 > ######### > Now if I run z1.py for the first time it prints properly > > x variable= 11 > > but if I do any change in z3 module , it has no effect > For example If I change in z3 > x=12 > I still get > x variable= 11 > Why? Modules are only imported once no matter how many times the 'import' statement shows up. If you really want to re-import the z3 module, try doing a 'reload z3'. > Thank you for help. > Is it possible to name module with a different extension from py? For example is it possible > to import z3.cod file? > Ladislav I don't know; maybe someone else can answer this one. For myself, I think you would have to recompile your Python interpreter to change this, and I can't conceive why you would want to be deliberately incompatible with everyone else like that. -- Robin Munn rmunn at pobox.com From spam at fisher.forestry.uga.edu Tue Oct 22 15:56:43 2002 From: spam at fisher.forestry.uga.edu (Chris Fonnesbeck) Date: 22 Oct 2002 12:56:43 -0700 Subject: What a mess! References: <3d9e2b8f$1_8@goliath.newsgroups.com> <3d9f4271_7@goliath.newsgroups.com> Message-ID: I have just tried making RH 8.0 RPMs from the SRPM. Though the compilation went well, trying to install them was unsuccessful. The SRPM makes RPMs of python packages with the prefix "python2-2.2.2" rather than just "python-2.2.2". This causes all sorts of dependency problems on 8.0, since the 1.x version is no longer part of the distribution as it was in the 7.x releases. Is there any way to make RPMs that are "python-2.2.2", so that the rpm installer doesnt complain? mongo57a at comcast.net wrote in message news:<3d9f4271_7 at goliath.newsgroups.com>... > Thanks. I'll see if I can untangle myself from this. > > > -----------== Posted via Newsfeed.Com - Uncensored Usenet News ==---------- > http://www.newsfeed.com The #1 Newsgroup Service in the World! > -----= Over 100,000 Newsgroups - Unlimited Fast Downloads - 19 Servers =----- From tismer at tismer.com Sun Oct 6 17:55:16 2002 From: tismer at tismer.com (Christian Tismer) Date: Sun, 06 Oct 2002 14:55:16 -0700 Subject: How to use the exec statement References: <3d9eca56_3@news.newsgroups.com> <3da02072_7@news.newsgroups.com> <020o9.15370$cS4.608697@news2.tin.it> <3da093bc_5@news.newsgroups.com> <3da09bf9_5@news.newsgroups.com> Message-ID: <3DA0B144.2030802@tismer.com> JB wrote: > Alex Martelli wrote: > > Thx. > There is one thing I do nt understand, though. (It is late > and I am tried. I may understand it tomorrow.) > > In thet new namespace there will be a function f. The user > must be able to call f via exec. > But f needs a global variable, otherwise it cannot > communicate with the rest of my program. If the user can > access this variable and overwrites it... > How to solve this? I don't see a problem here. You give the user access to your global variable, wghich means you put it into the proposed namespace object. The user can only overwrite it in that namespace, but that's of no concern for you. Another problem might in fact be that the user now might modify the variable's contents in some unwanted way. I'd be very careful here and build an extra object that only has the properties which you wish to give access to. Then, after calling the user code, you might decide which of the changed attributes you want to back-copy into your 'real' object, if at all. Make sure to never open a backdoor into an area that the user should not touch. Careful, this may happen much easier and without your prior knowledge. Make sure that you never copy dictionary contents which you know exactly, or it may happen easily that you inadvertently publish a globals dict, and you're probably hosed. Never publish something that contains the sys module, since that opens everything up quickly. Never carry a traceback around into user space. Tracebacks give acces to frames, and frames give access to globals... ciao - chris -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 pager +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From spam at fisher.forestry.uga.edu Tue Oct 15 23:10:09 2002 From: spam at fisher.forestry.uga.edu (Chris Fonnesbeck) Date: 15 Oct 2002 20:10:09 -0700 Subject: number comparison problem Message-ID: I am using python to code an optimization function that requires numbers to be compared to one another, as is common in many algorithms. However, the comparison operators (<,>,<=,>=,==) seem not to be working properly. Regard the following: >>> print fb,fc 0.132945911028 0.132945911028 >>> print fb>fc 1 These numbers look the same to me; what do I have to do to be able to test numbers accurately in python? TIA, cjf From hennie at nospam.sabinet.co.za Tue Oct 22 08:41:31 2002 From: hennie at nospam.sabinet.co.za (Hennie Rautenbach) Date: 22 Oct 2002 12:41:31 GMT Subject: Python 2.2.1, Solaris 8, gcc compile question Message-ID: <3db5477b$0$18843@hades.is.co.za> Hi there folks, Sure this is a faq but haven't been able to find the answer. I'm configuring and compiling the Python-2.2.1 distribution on a Sun Sparc running Solaris 8 using the gcc compiler (3.0.3). It configures and compiles fine. However when I install and run python and import a module I get the following error: $ /usr/local/bin/python Python 2.2.1 (#1, Oct 22 2002, 14:27:46) [GCC 3.0.3] on sunos5 Type "help", "copyright", "credits" or "license" for more information. >>> import time Traceback (most recent call last): File "", line 1, in ? ImportError: ld.so.1: /usr/local/bin/python: fatal: libgcc_s.so.1: open failed: No such file or directory >>> It has been pointed out to me that it relates to not having specified the LD_LIBRARY_PATH variable or not having used -G during compile time. I have very little experience in the use of LD_LUIBRARY_PATH and its associated evils. My question is, what parameters should I pass to configure to get it to create the proper Makefile that would compile a happy python which has all the proper libraries linked ? Any help will be appreciated very much. Regards, Hennie (clueless...) From mongo57a at comcast.net Sat Oct 5 20:38:52 2002 From: mongo57a at comcast.net (mongo57a at comcast.net) Date: Sun, 6 Oct 2002 00:38:52 GMT Subject: Quick question on mysql-python Message-ID: <3d9f74b2$1_7@goliath.newsgroups.com> Just finished downloading Python 2.2.1. Appears to be working fine. To complete the installation, I downloaded and executed MySQL-python-0.9.2-1.i386.rpm. MySQLdb shows up in /usr/lib/python2.2/site-packages (as it should). When I attempt to import MySQLdb I get the following error: libmysqlclient.so.9: cannot open shared object file: no such file or directory File "MySQLdb/__init__.py, line 27 ? import _mysql Well I looked, and _mysql.so is located in site_packages. I also verified environment with sys.path and the paths are correct as well. And I am logged in as "root" so there should be no permissions issue. Any idea what's wrong???? Thanks. -----------== Posted via Newsfeed.Com - Uncensored Usenet News ==---------- http://www.newsfeed.com The #1 Newsgroup Service in the World! -----= Over 100,000 Newsgroups - Unlimited Fast Downloads - 19 Servers =----- From jepler at unpythonic.net Thu Oct 3 20:12:38 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 3 Oct 2002 19:12:38 -0500 Subject: Integer and String Dictionary Keys for Fast Access In-Reply-To: <200210031638.42148.shalehperry@attbi.com> References: <200210031638.42148.shalehperry@attbi.com> Message-ID: <20021003191238.A2605@unpythonic.net> On Thursday 03 October 2002 16:18, Lance wrote: > > The advantage is that key lookups by integer are no doubt much faster than > > by strings. On Thu, Oct 03, 2002 at 04:38:42PM -0700, Sean 'Shaleh' Perry wrote: > test it out in python, you may be surprised. I don't think the type really > matters for dictionary look ups. Timings: 0.286319971085 # d[1] 0.23636496067 # d[1000] 0.231885075569 # d['a'] 0.233772993088 # d['a' * 10000] 0.216398954391 # l[1] 0.232298016548 # l[1000] so not only is it about the same speed to get a string or int key from a dict, it's about the same speed to get an int index from a list. This is independant of the length of the key. of course, within functions, locals are accessed by simple indexing of a C array with C ints which should be a bit faster still. It's possible that in the future this could be extended to methods of new-style classes which use __slots__ for instance variables. When no assignment to the first local is seen, then LOAD_FAST self / LOAD_ATTR a could be optimized into LOAD_SLOT a. Besides needing whole-function analysis (but isn't this already provided to know eg that exec is not called?) the problem here is that the slot number for the attribute 'a' depends on the class, but you are free to write class C: pass def f(self, ...): pass C.f = f There are probably other wrinkles that I've not considered that make this harder than it sounds... Jeff import time def test(d, k): for i in range(100000): d[k] keys = (1, 1000, 'a', 'a' * 10000) d = dict([(k, None) for k in keys]) for key in keys: t0 = time.time() test(d, key) t1 = time.time() print t1-t0 l = [None] * 1001 for key in (1, 1000): t0 = time.time() test(l, key) t1 = time.time() print t1-t0 From paul at boddie.net Tue Oct 1 12:32:35 2002 From: paul at boddie.net (Paul Boddie) Date: 1 Oct 2002 09:32:35 -0700 Subject: Decimal arithmetic, with example code References: Message-ID: <23891c90.0210010832.7a93913a@posting.google.com> "Chris Gonnerman" wrote in message news:... > """fp-test.py -- fixedpoint versus float comparison""" It's interesting to compare the results from FixedPoint with ScaledDecimal and with FixedPoint objects that have increased precision. Many issues in the supplied program can explain the apparent difference between rounded floating point results and the FixedPoint results. Here are some example results from an extended version of the original program: PCT AMT Fixed Fixed Fixed Scaled Scaled Float 2dp 4dp -> 2dp 2dp 4dp 0.01 0.50 0.00 0.0050 0.00 0.01 0.0050 0.01 0.02 0.25 0.00 0.0050 0.00 0.01 0.0050 0.01 0.05 0.10 0.00 0.0050 0.00 0.01 0.0050 0.01 0.05 0.50 0.02 0.0250 0.02 0.03 0.0250 0.03 0.05 0.70 0.04 0.0350 0.04 0.04 0.0350 0.03 0.05 0.90 0.04 0.0450 0.04 0.05 0.0450 0.05 0.06 0.75 0.04 0.0450 0.04 0.05 0.0450 0.05 0.09 0.50 0.04 0.0450 0.04 0.05 0.0450 0.05 0.10 0.05 0.00 0.0050 0.00 0.01 0.0050 0.01 0.10 0.25 0.02 0.0250 0.02 0.03 0.0250 0.03 0.10 0.35 0.04 0.0350 0.04 0.04 0.0350 0.03 0.10 0.45 0.04 0.0450 0.04 0.05 0.0450 0.05 0.10 0.65 0.06 0.0650 0.06 0.07 0.0650 0.07 0.10 0.85 0.08 0.0850 0.08 0.09 0.0850 0.09 When the floating point result is only a "wafer thin mint" below 0.35 (on this Pentium III laptop running Windows 2000), the rounded, truncated result is given as 0.3. Such conditions could be seen to be a flaw when attempting to highlight problems with the FixedPoint implementation. Meanwhile, ScaledDecimal's reliance on the long integer arithmetic in Python, as well as the automatic extension of precision in certain operations, do seem to help it produce the results you were *probably* expecting. """fp-test.py -- fixedpoint versus float comparison""" # You need the fixedpoint.py module installed # http://fixedpoint.sourceforge.net # and the ScaledDecimal.py module installed # http://www.boddie.org.uk/python/downloads/ScaledDecimal.py from fixedpoint import FixedPoint from ScaledDecimal import ScaledDecimal print "PCT AMT Fixed Fixed Fixed Scaled Scaled Float" print " 2dp 4dp -> 2dp 2dp 4dp" # I'm checking percentages, from 1% to 10% inclusive, # multiplied by "money" amounts from 0.01 (one cent) # to 1.00 (a buck). # Given appropriate precision, this problem applies # to other monetary systems than just USA. for percent in range(1,11): fixed_pct = FixedPoint(percent) fixed_pct /= 100 fixed_pct_ext = FixedPoint(percent, 4) fixed_pct_ext /= 100 # Think of it as 1..11 * (10 ** -2) scaled_pct = ScaledDecimal(percent, -2) float_pct = percent / 100.0 for amount in range(1,101): fixed_amt = FixedPoint(amount) fixed_amt /= 100 fixed_amt_ext = FixedPoint(amount, 4) fixed_amt_ext /= 100 scaled_amt = ScaledDecimal(amount, -2) float_amt = amount / 100.0 ############################################################## # Now for the crux of the matter: fixed_res = fixed_amt * fixed_pct # rounding is implicit here fixed_res_ext = fixed_amt_ext * fixed_pct_ext fixed_res_ext_rounded = fixed_res_ext.copy() fixed_res_ext_rounded.set_precision(2) scaled_res = scaled_amt * scaled_pct # precision is increased float_res = round(float_amt * float_pct, 2) ############################################################## # That's it, let's see if they match: if str(fixed_res) != ("%0.2f" % float_res) or \ str(scaled_res.round(-2)) != ("%0.2f" % float_res): print "0.%02d 0.%02d %-6s %-6s %-6s %-6s %-6s %-6.2f" % \ (percent, amount, fixed_res, fixed_res_ext, fixed_res_ext_rounded, scaled_res.round(-2), scaled_res.round(-4), float_res) # end of file. From aahz at pythoncraft.com Mon Oct 7 20:20:29 2002 From: aahz at pythoncraft.com (Aahz) Date: 7 Oct 2002 20:20:29 -0400 Subject: Python threading? References: Message-ID: In article , Mark Hammond wrote: >Aahz wrote: >> In article , >> Robert Oschler wrote: >>> >>>Also, what is a reasonable number of threads to expect to be able to run >>>before context switching overhead becomes a problem (I'm using a PIII 500 >>>Mhz with 512MB ram if that helps). >> >> It depends. For pure Python-based computation, more than one thread >> will cost you more than you gain. If it's almost pure I/O (file or >> socket stuff), you might be able to use as many as a couple of hundred >> threads. Mostly, you're probably best off somewhere between five and >> thirty threads, depending on what you're doing. > >I would have thought that a brave call. If you are performing lots of >IO and need many many connections, you are almost certainly better off >using an "asynchronous" approach, much like asyncore. With a large >number of threads (where "large" can be as low as single figures) the OS >overhead of switching will be greater than your internal overhead of a >more complicated design. I've got no practical experience with asyncore, but I do with threads. While I accept the conventional wisdom that asyncore will frequently do better than threads for performance, I stand by my claims for what will work well with threads. >A "one thread per connection" model is doomed from the start - >therefore, in most applications, I would consider 5 threads a large >number - particularly when all are actively doing something. OTOH, if >you are willing to accept that your first version will accept a max of >~20 connections, the brain-power saved by using threads beats the >additional OS overhead by a mile ;) Overall, yes, but a lot of I/O is bursty, and with a number of blocked threads, up to a hundred or so can work well. Note carefully that I *am* assuming a thread pool to avoid startup costs. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From abidnego25 at yahoo.com Fri Oct 11 14:09:09 2002 From: abidnego25 at yahoo.com (les) Date: 11 Oct 2002 11:09:09 -0700 Subject: forcing list garbage collection Message-ID: <653cf871.0210111009.5128832a@posting.google.com> Hi, dictionaries have a clear() method, do lists have something similar? i would like to list to empty and memory recollected right away. thanks From wlfraed at ix.netcom.com Wed Oct 2 20:11:44 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Wed, 02 Oct 2002 17:11:44 -0700 Subject: Decimal arithmatic, was Re: Python GUI app to impress the boss? References: Message-ID: <102gna.2ra.ln@ix.netcom.com> Brian Quinlan fed this fish to the penguins on Wednesday 02 October 2002 12:48 am: >> When I took science classes, I'd have been dinged a few >> points > if >> I turned in 0.035 -- the rule was to report results to the same >> significance as the inputs. >> >> 0.7 * 0.05 => 0.0 in those science classes. > > I'll be that you were really taught to answer 0.04 > > Otherwise I fear for your scientific education :-) > I suspect those classes were rigged where all measurements were to the same significance (not necessarily decimal places). 123000 * 0.00321 => 1.23E5 * 3.21E-3 -> 3.95E2 -> 395 So yes, on that basis, both 0.7 and 0.05 are 1 signicant digit, giving 0.04 to one significant digit. Then again, when I was taking those classes, I ran a slipstick and was thereby automatically limited to ~2.5 significant digits (depending on which end of the stick). My math instructor of the time actually started the year off with a declaration that answers only needed to be to that significance -- his background would have been slipstick. Calculators were too expensive for us poor folk... Nowadays the calculator is lunch money, getting a good slipstick is two+ weeks of lunch. -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < From sholden at holdenweb.com Thu Oct 10 07:29:00 2002 From: sholden at holdenweb.com (Steve Holden) Date: Thu, 10 Oct 2002 07:29:00 -0400 Subject: Python-mysql: Still stuck. References: <3da326da$1_4@goliath.newsgroups.com> <3da4fd6c_6@goliath.newsgroups.com> Message-ID: wrote in message news:3da4fd6c_6 at goliath.newsgroups.com... > Well, after pulling nearly all of my hair out, I finally have the answer: > The build process must use internal python directives which reference > "python" and not "python2.2" or whatever version you have installed. So I > have python1.5, 2, and 2.2 installed on my RH7.3 system. But "python" is a > cp of "python1.5". > > And it does not matter that you build with the correct version (i.e. > python2.2 setup.py build). > > So the trick is to rename your current distribution (in my case "python2.2" > a.k.a "python2.2.1") to "python". And it all comes together. > > Thanks for all of your help. Glad you found the problem. If you think this may be a problem specific to MySQLdb you should report it as a bug on the http://sourceforge.net/projects/mysql-python site. Or, if it's a bug in distutils, report it on http://sourceforge.net/projects/python. If you need any help reporting the bug you can email me. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- From paul at boddie.net Mon Oct 7 12:03:11 2002 From: paul at boddie.net (Paul Boddie) Date: 7 Oct 2002 09:03:11 -0700 Subject: cgi and form NEED HELP! References: Message-ID: <23891c90.0210070803.30bd763a@posting.google.com> "CheapSkate" wrote in message news:... > hi, need a little help here. > I'm having a list of items with checkboxses in them. > the name attribute is unknow for each one(generated automatically). > > now what I want to do is that > in the cgi.FieldStorage(), I want it to contain all the names of the checked > boxes. > any idea? That means that inside a single field in the FieldStorage object, you want a list of all the items where a checkbox was selected. > Here's the code for the checkbox: > print '%s'% > (filename, fullname, filename) > > where filename is the filename of the file e.g apple > and fullname is the fullpath to the file e.g C:\windows\desktop\apple Since you're probably varying the filename and fullname for each generated checkbox, this won't satisfy that criteria I gave above - each checkbox in this case will have a different "name" attribute, and you therefore won't get all the filenames in a single field entry from FieldStorage. Instead, you'll get a single entry for each filename in the FieldStorage object with a value of "on" (or whatever the HTML forms standard says) associated with it, if the checkbox for that filename was selected. What you need to do is to choose a common name for all the checkboxes and then to put the filename into the "value" attribute for each checkbox, like this: print '%s'% (filename, fullname, filename) Then, under the entry for "files" (in this case) in the FieldStorage object, you'll get a list of filenames whose checkboxes were selected. Paul From mwh at python.net Fri Oct 4 05:32:00 2002 From: mwh at python.net (Michael Hudson) Date: Fri, 4 Oct 2002 09:32:00 GMT Subject: Love "Python Cookbook" References: <3d9c4c2a$0$230$4d4ebb8e@news.nl.uu.net> Message-ID: "Gumuz" writes: > ok, I just ordered it : D > > there was one thing that impressed me a lot when i first started out with > Python and this newsgroup.... > > MY QUESTIONS WERE BEING ANSWERED BY THE PEOPLE WHO WROTE THE BOOK I HAD ON > MY LAP THAT MOMENT. > > > that, was sooooo cool :) This is a cool thing about this group. It happened to me back in '98 (wow, my first post here was almost 4.5 years ago...). Cheers, M. -- You sound surprised. We're talking about a government department here - they have procedures, not intelligence. -- Ben Hutchings, cam.misc From hwlgw at hotmail.com Sat Oct 19 06:06:39 2002 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 19 Oct 2002 03:06:39 -0700 Subject: Using Python for blogging Message-ID: Hello all ! reStructuredText (reST) looks cool! So I was thinking about doing blogging (web logging, sort of keeping a diary at your ISP) with Python. The existing blogging software I know of positively stinks IMHO. My ideal thing would be to be able to edit a file at home using reST. Then I need some scripts to transform that into html and send it to my ISP. For turning reST into html there are example scripts in the reST Tools directory. I now have some scripts that work. For every day there is a reST file with name e.g. 291002.txt for date 19 october 2002. And it is in a directory with name 1002 (guess what:). So you just edit the files using reST and you write scripts to turn that into html (could just use html.py in the reST Tools directory). But! The resulting html does not really look like I want, I mean I do not like the fonts and the sizes etc. Unfortunately I do not know much about HTML so I have a question: How to improve this? Recommandations? Use CSS? Any pointers on that? ''' Keep a diary and one day it'll keep you. -- Mae West ''' From gry at ll.mit.edu Tue Oct 8 11:45:50 2002 From: gry at ll.mit.edu (george young) Date: Tue, 8 Oct 2002 11:45:50 -0400 Subject: Initializing class variables with a file References: <2d3crhfedm.fsf@synapse.hut.fi> Message-ID: <20021008114550.6148f34e.gry@ll.mit.edu> On 08 Oct 2002 12:50:45 +0300 Karthikesh Raju wrote: > 1. i want to initialize all the class variable thro the __init__(self) > method, but it should be initialized thro a file. > i set up the parameters for the expt in the file and the > self.a,b,c = are assigned by reading this file You might try the ConfigParser module, it maintains a nicely readable ascii file of "configuration variables". I cannot think why the whole bed of the ocean is not one solid mass of oysters, so prolific they seem. Ah, I am wandering! Strange how the brain controls the brain! -- Sherlock Holmes in "The Dying Detective" From phr-n2002b at NOSPAMnightsong.com Thu Oct 3 11:13:04 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 03 Oct 2002 08:13:04 -0700 Subject: [Python-Dev] PEP239 (Rational Numbers) Reference Implementation and new issues References: <20021002221421.GA29958@thyrsus.com> Message-ID: <7xlm5flfnj.fsf@ruckus.brouhaha.com> python-pep at ccraig.org (Christopher A. Craig) writes: > That is, of course, much more permissive than if we coerced the other > way and had rational(x)==float(x) iff rational(x)==rational(float(x)). I don't think you can do it that way without kludges to deal with rational(NaN), rational(Inf), etc. From marco at mfa.mohr-i.nl Mon Oct 21 10:07:51 2002 From: marco at mfa.mohr-i.nl (marco) Date: 21 Oct 2002 07:07:51 -0700 Subject: python Newbie Question: key-press capturing. Message-ID: Hi, I just started with programming in python. I used to work with Qbasic.I already made some little functions in Python but I can't fix this problem with keyboard capturing. I want to make a simple sequenser function that prints "pulse" and stops when a key (forexample "q") is pressed. I tried to use the functions "raw_input" and "sys.stdin.read()" but they somehow it blocks out the rest of the code, the print "pulse" line doesn't work anymore. #------------------------------------------------------ key="" x=0 while 1: key = raw_input() x =x+1 if x > 100000: print "pulse" x=0 if key == "q": break print "q pressed" #------------------------------------------------------ Thanks 4 your attention. M. Theunissen marco at mfa.mohr-i.nl From aleax at aleax.it Sat Oct 5 06:23:05 2002 From: aleax at aleax.it (Alex Martelli) Date: Sat, 05 Oct 2002 10:23:05 GMT Subject: range or xrange disallowed for big numbers References: Message-ID: Chad Netzer wrote: > > Is there a reason (technical or philosophical) to disallow: > > range( 10000000000L, 10000000000L + 1L ) > > or > > xrange( 10000000000L ) > > etc...? Slowing down common cases of range and xrange (by keeping PyObject's or Python longs rather than C-level long's) is an unpleasant prospect, although the generality of looping easily over whatever range one may want can sometimes be useful. Maybe rather than fixing either type a new, perhaps Python-coded built-in generator could be added: def genrange(start, stop=None, step=1): if step == 0: raise ValueError, "step can't be 0" if stop is None: start, stop = 0, start if step > 0: while start < stop: yield start start += step else: while start > stop: yield start start += step Alex From F.L.Burton at bio.gla.ac.uk Sat Oct 19 10:34:31 2002 From: F.L.Burton at bio.gla.ac.uk (Francis Burton) Date: Sat, 19 Oct 2002 15:34:31 +0100 Subject: Books on scientific/numeric programming in Python? References: <3DB005F8.CD96D868@bio.gla.ac.uk> Message-ID: <3DB16D77.38BC7C80@bio.gla.ac.uk> Fernando P?rez wrote: > Look at > http://pathfinder.scar.utoronto.ca/~csca57/ > > They have 'An Elementary Introduction to Scientific Computing', the text is > incomplete. I wasn't terribly impressed by it, but it does have a pyhton > focus. It's not too bad at all as a course text, imho. Obviously someone put considerable effort into writing it. However, I had in mind something much more like a cookbook - not so much a "Numerical Recipes in Python" (although that would be quite nice!) as a collection of more general purpose code snippets and modules that show how Python idioms could be applied in the scientific/numerical field. So it would include lots of database, graphical and GUI examples and maybe have rather less of a web slant. I like the "Python Cookbook" style of exposition. Francis From marklists at mceahern.com Tue Oct 15 21:55:08 2002 From: marklists at mceahern.com (Mark McEahern) Date: Tue, 15 Oct 2002 20:55:08 -0500 Subject: Newbie: Inheritance of accessors In-Reply-To: Message-ID: [Will Fitzgerald] > I'm curious about accessors being inherited from parent classes. Given > the code that follows, and I create an instance: > > e=S() > > How do I access the inherited default 'x' in e (inherited from R)? In the most natural way imaginable, of course: e.x = 1 print e.x etc. // m - From blarson at crary.com Sun Oct 13 18:51:49 2002 From: blarson at crary.com (Bradley D. Larson) Date: Sun, 13 Oct 2002 17:51:49 -0500 Subject: realtime design References: <83it06i7zq.fsf@panacea.canonical.org> Message-ID: <3DA9F905.648AE801@crary.com> Real-time does not always mean "micro" or nano second response. The granularity is dependent upon the need of the underlying system. The underlying premise is that the calculations are done..."in order that results of the computation can be used in guiding the physical process" (see gov def below). If you can calculate appropriate results in 30 minutes and they are used to make changes to the process every 45 minutes... That is real time. In the following definition I would underline: "user senses as sufficiently immediate" but don't want to get yelled at by those utilizing deficient email readers. Real time is a level of computer responsiveness that a user senses as sufficiently immediate or that enables the computer to keep up with some external process (for example, to present visualizations of the weather as it constantly changes). Real-time is an adjective pertaining to computers or processes that operate in real time. Real time describes a human rather than a machine sense of time. In the days when mainframe batch computers were predominant, an expression for a mainframe that interacted immediately with users working from connected terminals was online in real time. Source: http://whatis.techtarget.com/definition/0,289893,sid9_gci214344,00.html Government Definition: real time: 1. The actual time during which a physical process occurs. (188) 2. Pertaining to the performance of a computation during the actual time that the related physical process occurs, in order that results of the computation can be used in guiding the physical process. Source: http://www.its.bldrdoc.gov/fs-1037/dir-030/_4450.htm Chris Liechti wrote: > ... what you need is an underlying realtime OS, that guaratees that the real > time tasks get enough CPU power at the right time. without that absolutely > no programming language can help out. > > chris > -------------- next part -------------- A non-text attachment was scrubbed... Name: blarson.vcf Type: text/x-vcard Size: 400 bytes Desc: Card for Bradley D. Larson URL: From duncan at rcp.co.uk Mon Oct 21 04:42:19 2002 From: duncan at rcp.co.uk (Duncan Booth) Date: Mon, 21 Oct 2002 08:42:19 +0000 (UTC) Subject: Zope: What difference between "&dtml-var" and "&dtml.-var" References: Message-ID: chunyu wrote in news:m2elakwe6u.fsf at itr.hit.edu.cn: > > when i view_source in a zope host, i find two format "&dtml-var" and > "&dtml.-var" to insert dtml variable. but what's the difference? > > Thanks any way! You will probably get Zope answers more reliably if you subscribe to the main Zope mailing list. However, in this case I can refer you to the ZopeBook, Appendix A: DTML Reference, Section 'var: Inserts a variable' which documents the syntax of &dtml-var; and in particular describes the meaning of the dot. You can purchase a copy of the ZopeBook from your local bookstore, or download it from http://www.zope.org/Documentation/Books/ZopeBook/ I suggest you download the PDF version, I find it easier to read than the annotated HTML. If you search for the phrase "HTML quoting" you should find the relevant section quickly enough. From aleax at aleax.it Sun Oct 13 15:26:36 2002 From: aleax at aleax.it (Alex Martelli) Date: Sun, 13 Oct 2002 19:26:36 GMT Subject: Internationalization bug?? [Python 2.2.1, RedHat 8.0, Swedish] References: <7d546104.0210120857.3f4e3857@posting.google.com> <7d546104.0210131059.6821d111@posting.google.com> Message-ID: Urban Anjar wrote: > len() was not an issue, just a symptom of my problem. I was playing > with a useless program to reverse a string and got funny results with ???. > Found out that some characters were two-byte and of course it will be > funny if I reverse the bytes in a two-byte character... I'd code this differently: temp = list(unicode(str, 'utf-8')) temp.reverse() print ''.join(temp).encode('utf-8')) but of course that's not the point -- your life is much simpler if, internally, you keep all strings in Unicode, and convert them only if and when needed for input/output purposes. > I still think this should be built-in in any way. I don't want > to think about how things are coded internaly when doing Python > programming, than I could chose C or assembler or something like > that... I want to be able to tell kids 'n students that Python is > easy and straightforward even for Swedish people... Unfortunately, many different encodings are in use for input and output of Unicode -- apparently your terminal wants utf-8, mine wants iso-8859-15, yet another text terminal will want yet another encoding. You do have to deal with that, one way or another. The simplest way, IMHO, is to use module codecs' EncodedFile to wrap sys.stdin and sys.stdout appropriately (i.e., with 'utf-8' in your case, 'iso-8859-15' in mine, and so forth) and only manipulate Unicode strings internally. It makes no difference whether you're French, Swedish, Italian, German, Danish, or Spanish -- and only very little if you're Turkish, Estonian, Russian, and so forth; Unicode is the same for all -- you only need to set the input/output codec however appropriate for your system, and uniformly manipulate Unicode strings, only, in your programs. The wrapping of stdin and stdout may usefully be performed in sitecustomize.py (create it for the purpose if you don't have it yet). Alex From tdelaney at avaya.com Thu Oct 10 20:15:09 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Fri, 11 Oct 2002 10:15:09 +1000 Subject: Concrete classes -- stylistic question Message-ID: > From: Alex Martelli [mailto:aleax at aleax.it] > > http://tinyurl.com/1wq1 Wow - that's better than http://makeashorterlink.com/ ... http://makeashorterlink.com/?O2BA22212 Tim Delaney From mongo57a at comcast.net Thu Oct 3 00:23:03 2002 From: mongo57a at comcast.net (andy surany) Date: Thu, 03 Oct 2002 00:23:03 -0400 Subject: string.join question Message-ID: <005e01c26a94$91959a80$2502a8c0@emily.ewndsr01.nj.comcast.net> Damn you're good!!!!!! You just saved me the trouble of having to write the update and delete as well! Thanks again!!!! -----Original Message----- From: Michal Wallace To: andy surany Cc: python-list at python.org Date: Wednesday, October 02, 2002 11:16 PM Subject: Re: string.join question >On Wed, 2 Oct 2002, andy surany wrote: > >> I'm accessing MySQL from Python. This is for an insert >> statement which looks like this: > >Aha... :) Maybe this will help: > >http://cvs.sabren.com/sixthdev/cvsweb.cgi/storage/MySQLStorage.py?rev=1.7 > >Cheers, > >- Michal http://www.sabren.net/ sabren at manifestation.com >------------------------------------------------------------ >Switch to Cornerhost! http://www.cornerhost.com/ > Low Priced, Reliable Blog Hosting, With a Human Touch. :) >------------------------------------------------------------ > From grahamd at dscpl.com.au Mon Oct 7 00:55:34 2002 From: grahamd at dscpl.com.au (Graham Dumpleton) Date: 6 Oct 2002 21:55:34 -0700 Subject: Python/Tkinter on MAC OS X Aqua (not X11) Message-ID: Is anyone successfully using Python/Tkinter on MAC OS X 10.2.1 with native Aqua GUI interface (ie. not X11). I have installed Tcl/Tk 8.4 for MAC OS X Aqua (8.4a4-2 snapshot) from: http://sourceforge.net/projects/tcl I have then installed latest Python 2.2.1 tarball from the Python website. I did need to tweak a couple of things, but otherwise seemed to install okay. Now when I go run a Tkinter program, eg: import sys win = Tkinter.Tk() b = Tkinter.Button(win,text="hello",command=sys.exit) b.pack() win.mainloop() I get the following errors from deep inside Tk when I click on the Window to try and get it focus. bash-2.05a$ python ex.py SetFrontProcess failed,-606 SetFrontProcess failed,-606 ^CTraceback (most recent call last): File "ex.py", line 6, in ? win.mainloop() File "/Library/Frameworks/Python.framework/Versions/2.2/lib/python2.2/lib-tk/Tkinter.py", line 929, in mainloop self.tk.mainloop(n) KeyboardInterrupt End result is that window can't get focus and is thus unusable. Have there been any changes in version of tkinter in CVS since 2.2.1 which fix this? BTW, demo Tk scripts work okay, only Tkinter in Python giving a problem. Thanks. From c_ullman at yahoo.com Sat Oct 19 12:05:30 2002 From: c_ullman at yahoo.com (Cayce Ullman) Date: 19 Oct 2002 09:05:30 -0700 Subject: SOAP frustrations References: <3DAC6F04.2030704@mindspring.com> Message-ID: <73c9b534.0210190805.559c4b92@posting.google.com> I am one of the authors of SOAP.py. Andrew Dalke wrote in message news:<3DAC6F04.2030704 at mindspring.com>... > Hey all, > > I've been working with one of my clients trying to get a SOAP > interface going for a project. I've had a rather frustrating time > trying to get it to work, and am using this as a chance to vent. > snip > In addition, SOAP.py has similar coding style pecularities, and there's > some bug that comes up in Python 2.2 because of changes in Python's > type/class system. (We're using Python 2.1 so it isn't yet a problem. > I also haven't tested ZSI to see if this is a problem.) > I apologize for the insanity that is SOAP.py's code. One of our issues is we decided to use SAX over DOM for perfomance reasons, that made the XML bits of SOAP.py mind bending. On the plus side, you can generally parse and fire a SOAP message with SOAP.py faster than DOM can even validate the XML. > Finally, it seems that neither SOAP.py nor ZSI are actively developed. > There hasn't been a recent release of either package, and the CVS logs > show little change. > > All in all, it's rather discouraging for me to work with SOAP in > Python, and that's given a rather non-trivial amount of experience > in doing Python. I would think others have worse problems. > > It's such that the more CS-y people at my client's site believe that > web services in Python are still very immature and want to switch the > project over to Java and WebLogic(!). (I did point out that developing > the library I did was still less time than setting that up, but there > are other factors in the mix as well.) > > > What I don't get is, I figure there's enough people doing web services/ > SOAP with Python that there shouldn't be these problems. Why then am > I so frustrated with it? > > Andrew Dalke > dalke at dalkescientific.com Andrew, I appreciate your frustrations, and I do still get the occasional email complaining about some feature/bug of SOAP.py (I guess you get what you pay for :). Unfortunately, my current job has little to do with SOAP, so I can no longer afford to maintain it. We gave it a BSD-style license for a reason. Feel free to fix it and fork it. For that matter, let this serve as an open call to anyone who would like to take over as the maintainer of the "official" SOAP.py. From jason at tishler.net Wed Oct 9 10:28:53 2002 From: jason at tishler.net (Jason Tishler) Date: Wed, 09 Oct 2002 10:28:53 -0400 Subject: Can't run NumTut on cygwin-hosted python In-Reply-To: <186164aa.0210071414.5283dc97@posting.google.com> References: <186164aa.0210071414.5283dc97@posting.google.com> Message-ID: <20021009142853.GD1704@tishler.net> On Mon, Oct 07, 2002 at 03:14:40PM -0700, Jeff Perry wrote: > Not sure what to try next. Any suggestions? See the following: http://cygwin.com/ml/cygwin/2002-10/msg00425.html Jason From loewis at informatik.hu-berlin.de Sun Oct 13 08:19:17 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 13 Oct 2002 14:19:17 +0200 Subject: Internationalization bug?? [Python 2.2.1, RedHat 8.0, Swedish] References: <7d546104.0210120857.3f4e3857@posting.google.com> Message-ID: "Paul Watson" writes: > If len() returns the number of bytes, what can Urban Anjar use to get the > number of characters? As I said: s = unicode(s,'utf-8') print len(s) Regards, Martin From tjreedy at udel.edu Tue Oct 8 13:47:05 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 8 Oct 2002 13:47:05 -0400 Subject: [OT} How to un-GPL parts of a GPL'd module. References: Message-ID: "Chris Watson" wrote in message news:mailman.1034093591.24440.python-list at python.org... > I love the GNU "Play by my rules or i'm taking my toys and going home" > attitude. It's so beneficial to humanity. I love the Statist "Play by our rules or we'll shoot you" attitude. Ditto for the Corporatist "Play by our rules or we'll sue you until you wish you *had* been shot" attitude. > If it was about passing on knowledge it would be in the public domain > commons for the benefit of man. About 10 years ago, the US Patent office issued a patent something like the following: Method for Getting the Correct CDRom into a Computer CD Drive while correct CD is not in CD drive: ask user to put correct CD in CD drive . . . . . . Looking for more? Sorry, that's it, the patented software algorithm. So much for public domain commons when Statists help Corporatists to fence it in. > As someone stated earlier the GPL is a political statement. As is, it seems to me, GPL bashing. Well, back to Python, Terry J. Reedy From wlfraed at ix.netcom.com Fri Oct 4 18:34:35 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Fri, 04 Oct 2002 15:34:35 -0700 Subject: $PYTHONHOME ??? References: Message-ID: David Lloyd-Jones fed this fish to the penguins on Thursday 03 October 2002 09:21 am: > > Or is .bashrc even what I want to be working on? > I'd suspect what you need to change (if any) is in the crontab itself. -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < From donnal at donnal.net Thu Oct 31 06:25:31 2002 From: donnal at donnal.net (Donnal Walter) Date: 31 Oct 2002 03:25:31 -0800 Subject: Python certification? References: Message-ID: <918bc22f.0210310325.7ec7d073@posting.google.com> "DG" wrote: > Python is OSI (Open Source Initiative) certified, but are there any other > certifications (e.g. ISO) which Python has, or is aspiring to? As an industry outsider, I know little or nothing about the industry standardization processes, but in principle I believe in public standards. In that regard, I derive a sense of reassurance from the efforts of the Python Software Foundation and the Python Business Forum. http://www.python.org/psf/mission.html http://www.python-in-business.org/about/ Donnal Walter Arkansas Children's Hospital University of Arkansas for Medical Sciences From Oschler at earthlink.net Sun Oct 20 06:02:28 2002 From: Oschler at earthlink.net (Robert Oschler) Date: Sun, 20 Oct 2002 10:02:28 GMT Subject: SOAP questions References: Message-ID: "Emmett" wrote in message news:e0da462e.0210182105.4f11c6fb at posting.google.com... > It sounds to me that you need a parser that can read the stream > and create the Delphi equivalent to a Java JDOM or DOM representation > of the results. Then your tool should chain XSL transformations > as needed to provide data for the gui. > > Again, if possible use the fact that everything is in XML and stay with > XSLT solutions as much as possible. Stay away from building a lot > of code from scratch. > I'm puzzled. The user either codes in XHTML, HTML, XSLT, or XML. > But not HTML/XML. Now, XSLT which generates XHTML can be made to look > very XHTML like. You'd hardly recognize the XSLT was XHTML except for > statements. > > You need to do something which will do a post to the SOAP server, > create a Delphi XML representation (equivalent to JDOM or DOM) > which is then transformed with chained XSLTs to fill in the > HTML/XML. To do that I'd think you'd want the HTML/XML to be XSLT > which looks like XHTML. > Emmet, Let me clarify things a bit. The app that the user uses to _design_ the web page is in Delphi. But, the Delphi app generates HTML or XML/XSLT or Javascript (if I seem fuzzy hear is I'm not sure what will be best yet) pages that they will upload to their web server (Apache, etc.). It is those generated pages that will contain the preformatted SOAP requests and I'm hoping there is a way they can also deal with the incoming SOAP response. That's the part that throws me. My knowledge of web programming isn't nearly good enough yet to understand how a web page can "intercept" (?) the returned SOAP response before the browser gets hold of it and reformat it into renderable web page using XSLT or whatever. That is why I fear that I may end up having to have some kind of CGI module on the user's web server that handles the SOAP transactions instead and serves up the content to a web site visitor. If I could find a way to pull this off completely on the client side, i.e. inside the web visitor's browser, I'd be overjoyed. thx From maschio_77 at hotmail.com Sun Oct 20 15:53:40 2002 From: maschio_77 at hotmail.com (Maschio_77) Date: Sun, 20 Oct 2002 19:53:40 GMT Subject: data from a web page Message-ID: <8RDs9.14810$TD1.676374@news2.tin.it> how can I get data from a web page? I'm a python learner and I was trying using socket but I don't understand how they works so can someone give me an example please? Thanks From phoebe_1 at worldnet.att.net Wed Oct 9 21:23:42 2002 From: phoebe_1 at worldnet.att.net (Phoebe 1) Date: Thu, 10 Oct 2002 01:23:42 GMT Subject: Building Python 2.2.1 for HP Tru64 UNIX V4.0F References: Message-ID: Narendra, Did you hack the makefile to add the options? Then it will *not* work. I think Martin had suggested CC trick, I usually hack the configure.ac to set the flags since I have lots of different OS/Archs to support. Did you do this: $ make distclean $ CC="cc -std1 -msg_disable longlongtype" $ export CC $ ./configure --with-pydebug If you did not run configure again (with distclean) it will *not* work. Anyways I am using DEC/Compaq/HP C compiler V6.2 > . I have it working with Tru64 Unix 4.0E, 5.0A, 5.1,5.1A (yes, I have all those versions). I don;t have a 4.0F system, maybe it is specific to that OS version. Or it could be your C compiler version, try to download the new compiler from the ftp site, there were some issuses with the early version of 6.0, I have the 6.2 and 6.3 compilers and I have had no problems. Cheers "Narendra Raavi" wrote in message news:ao2flt$6n39 at kcweb01.netnews.att.com... > > All, Thanks for the several suggestions. > > 1.a: I am using the --with-pydebug option for configure. > 1.b: I have the same problem with gcc3.1. > 1.c: Using "-std1 -msg_disable longlongtype" did not work for Python2.2.1 or > Python2.2.2b1. > 1.d: For Python2.2.2b1 the error occurs even earlier: > > cc -c -O -Olimit 1500 -I. -I./Include -DHAVE_CONFIG_H -o > Objects/unicodeobject. > o Objects/unicodeobject.c > cc: Error: Objects/unicodeobject.c, line 1235: Invalid expression. (badexpr) > nallocated = Py_SAFE_DOWNCAST(sizeof(stackbuf), size_t, int); > ---------------------^ > cc: Error: Objects/unicodeobject.c, line 1235: Invalid statement. (badstmt) > nallocated = Py_SAFE_DOWNCAST(sizeof(stackbuf), size_t, int); > ---------------------^ > cc: Error: Objects/unicodeobject.c, line 1293: Invalid expression. (badexpr) > nneeded = Py_SAFE_DOWNCAST(p - stackbuf, long, int); > ------------------^ > cc: Error: Objects/unicodeobject.c, line 1293: Invalid statement. (badstmt) > nneeded = Py_SAFE_DOWNCAST(p - stackbuf, long, int); > ------------------^ > cc: Error: Objects/unicodeobject.c, line 1299: Invalid expression. (badexpr) > nneeded = Py_SAFE_DOWNCAST(p - PyString_AS_STRING(v), long, int); > ------------------^ > cc: Error: Objects/unicodeobject.c, line 1299: Invalid statement. (badstmt) > nneeded = Py_SAFE_DOWNCAST(p - PyString_AS_STRING(v), long, int); > ------------------^ > *** Exit 1 > Stop. > > 2. The problem seems to be (a) the cpp translation of this macro OR (b) the > __assert implementation (i'm using the example I provided): > > p = (VALUE, WIDE, NARROW) (if ((int) ((WIDE)(NARROW)(VALUE) == (VALUE))) ; > else __assert("(WIDE)(NARROW)(VALUE) == (VALUE)", "x.c", 17), > (NARROW)(VALUE))(c, int, char) ; > > > 3. My main motivation in using the --with-pydebug option is to be able to > dump internals to inspect them. Just learning. > > 4. BTW, I love the way the code (that I have looked at - about 35%) is > written. Clean, easily understood, uncluttered. The Python developers > deserve kudos for this. > > 5. It appears that there is a bug report that has not been fixed. One fix is > to replace the assert with a function that actually returns something. I'll > try to get this working and see if the Python folks would like a fix. > > "Holden Caulfield" wrote in message > news:c2595393.0210091225.3a3d4d at posting.google.com... > > "change" wrote in message > news:... > > > Hi, > > > > > > I'm trying to build Python 2.2.1 for HP (COMPAQ) Tru64 UNIX V4.0F with > the > > > debug option. > > > > > > The build fails in Python/marshal.c: > > > > > > cc -c -O -Olimit 1500 -I. -I./Include -DHAVE_CONFIG_H -o > Python/marshal.o > > > Python/marshal.c > > > cc: Error: Python/marshal.c, line 64: Invalid expression. (badexpr) > > > *p->ptr++ = Py_SAFE_DOWNCAST(c, int, char); > > > ----------------------------^ > > > cc: Error: Python/marshal.c, line 64: Invalid statement. (badstmt) > > > *p->ptr++ = Py_SAFE_DOWNCAST(c, int, char); > > > ----------------------------^ > > > *** Exit 1 > > > Stop. > > > > > > > > > The problem seems to be the definition of Py_SAFE_DOWNCAST in > > > Include/pyport.h > > > > > > #ifdef Py_DEBUG > > > #define Py_SAFE_DOWNCAST(VALUE, WIDE, NARROW) \ > > > (assert((WIDE)(NARROW)(VALUE) == (VALUE)), (NARROW)(VALUE)) > > > #else > > > #define Py_SAFE_DOWNCAST(VALUE, WIDE, NARROW) (NARROW)(VALUE) > > > #endif > > > > > > > > > I also wrote a simple c program mimicking this behavior: > > > > > > #include > > > #include > > > > > > > > > #define SAFE_DOWNCAST(VALUE, WIDE, NARROW) (assert > ((WIDE)(NARROW)(VALUE) > > > == (VALUE)), (NARROW)(VALUE)) > > > > > > main () { > > > > > > char p ; > > > int c ; > > > > > > c = 65 ; > > > p = SAFE_DOWNCAST(c, int, char) ; > > > > > > printf ("INT is: %d and CHAR is: %c\n", c, p) ; > > > > > > } > > > > > > > > > This program does not seem to compile with the cc or the gcc compilers. > Is > > > there a problem with my C compilers or the switches I use with them? > > > > > > Thanks, > > > > > > Narendra > > > > > > All right do this: > > > > CC="cc -std1 -msg_disable longlongtype" > > export CC > > ( I am assuming you are bourne/Korn shell) > > Then run configure again. It will compile fine with or w/o the Debug > > option > > enabled. > > Explanation of the options: > > -std1 : This enforces strict compliance with ANSI C standard. Python > > seems to be one of the few apps that I have had success using the > > flag. Anyways, it is good thing to be compliant with the standard :) I > > guess > > -msg_disable longlongtype: > > All this does is reduce the noise on the long long type being a > > language extension (it is Informational and *not* warning btw). > > > > Now, as to why '-std1' would work. I have not had the time to shift > > through this. What it does do is define the macro __STDC__ = 1. > > > > cheers > > From jens.farmer at kodak.com Wed Oct 16 15:33:17 2002 From: jens.farmer at kodak.com (Jens Farmer) Date: Wed, 16 Oct 2002 15:33:17 -0400 Subject: debugging python extension modules with MS vc++ 6.0 References: <3DAC86D9.93AFEE62@kodak.com> Message-ID: <3DADBEFC.F6088766@kodak.com> Hmmm. I certainly used the "python_d.exe" for my "Executable for debug session." However, I'm not sure what to give the shell's "progam arguments." Certainly you don't mean that I should give the shell the name of my extension with no other commandline switches. Doing so only causes the shell to complain about syntax errors as it tries to interpret my extension as an ascii python module. I find your recollection about "program arguments" intriguing. If you'd be so kind, could you follow up with more specifics on those switches / args? (you can open a DOS window and type "python_d -h" for a reminder on what the shell supports) Thanks for any help, Jens From cnetzer at mail.arc.nasa.gov Fri Oct 4 23:07:09 2002 From: cnetzer at mail.arc.nasa.gov (Chad Netzer) Date: Fri, 4 Oct 2002 20:07:09 -0700 Subject: What a mess! In-Reply-To: References: <3d9e2b8f$1_8@goliath.newsgroups.com> Message-ID: <200210050307.UAA00255@mail.arc.nasa.gov> On Friday 04 October 2002 19:38, Thomas Weholt wrote: > Perhaps not what you want to hear, but if you're not a fanatic RedHat-user > you might want to try Mandrake Linux instead. Or even upgrade to the just-released RedHat 8.0. They apparently also have python 2.2 (finally moving on from 1.5), and the usual goodies. -- Chad Netzer cnetzer at mail.arc.nasa.gov From mongo57a at comcast.net Fri Oct 4 21:14:28 2002 From: mongo57a at comcast.net (mongo57a at comcast.net) Date: Sat, 5 Oct 2002 01:14:28 GMT Subject: What a mess! Message-ID: <3d9e2b8f$1_8@goliath.newsgroups.com> On Redhat 7.3. Downloaded latest Python binaries (rpm) and tried to install. Got lots of errors like: "file /usr/lib/python2.2/........ from install of python2-2.2.1-1 conflicts with file from package python2-2.2-16" Got the same errors on install or update. So in my infinite wisdom (or lack of....) I decided to try and uninstall Python and start over. So I manually (isn't there a way to automatically uninstall ????) deleted the install (directories) for 2.2. That left me still with directories for Python 1.5 and Python2. Started over with an rpm install of 2-2.2.1-1. Got the same errors. There must be more going on here than I understand. Thanks. -----------== Posted via Newsfeed.Com - Uncensored Usenet News ==---------- http://www.newsfeed.com The #1 Newsgroup Service in the World! -----= Over 100,000 Newsgroups - Unlimited Fast Downloads - 19 Servers =----- From lbrannma at cablespeed.com Sat Oct 19 19:24:22 2002 From: lbrannma at cablespeed.com (Lance) Date: Sat, 19 Oct 2002 16:24:22 -0700 Subject: hostid? References: Message-ID: Thanks all for your advice. Magnus Lycka provided the solution, for Windows XP: If you by MacID mean MAC address, or Media Access Control address, i.e. the hardware address in the network card, this could work on Win 2000 for instance. The solution on unix/linux is very similar. Please note that some machines have several network cards (or none) which makes life more difficult. >>> import os, re >>> pattern = re.compile(r'\w\w-\w\w-\w\w-\w\w-w\w-\w\w') >>> text = os.popen('ipconfig /all').read() >>> m = pattern.search(text) >>> m.group(0) '00-01-02-E0-FF-FF "Lance" wrote in message news:ur2ok51jlan72f at corp.supernews.com... > Hi All, > > I'd like to retrieve a computer's hostid. Does anyone know how to do this? > > Thanks in advance. > > Lance > > From tismer at tismer.com Thu Oct 3 14:55:03 2002 From: tismer at tismer.com (Christian Tismer) Date: Thu, 03 Oct 2002 11:55:03 -0700 Subject: Decimal arithmetic, was Re: Python GUI app to impress the boss? References: <7xd6qwqtgz.fsf@ruckus.brouhaha.com> <7xelbcgo56.fsf@ruckus.brouhaha.com> <3D9A5DC4.9030704@tismer.com> <00c601c269c1$7afe83a0$ba01010a@local> <3D9B5B97.4020106@tismer.com> <003301c26a8b$39388900$ba01010a@local> Message-ID: <3D9C9287.4080307@tismer.com> Chris Gonnerman wrote: > ----- Original Message ----- > From: "Christian Tismer" > > >>(On bases: Actually, the primes (2, 3, 5) would give a quite >>nice numeric base. They have lots of nice properties >>concerning harmony, and the multiples of the prime factors >>produce numbers people consider as "nice", most of the time. >>So my number base would be at least 30 :-) ) > > > Didn't the ancient Babylonians use 60? I've read we have > them to blame for 360 degrees in a circle. > > Just has another factor of 2... they must have been pretty > sharp mathematicians. Right. And see how simple they built their positional system, using just two symbols: http://www-gap.dcs.st-and.ac.uk/~history/HistTopics/Babylonian_numerals.html Base ten is embedded into base 60. They could have done it with 30 as well, but I have no idea why they have choosen this, exactly. The above article gives some discussion abou that. ciao - chris -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 pager +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From jmiller at stsci.edu Tue Oct 8 15:35:51 2002 From: jmiller at stsci.edu (Todd Miller) Date: Tue, 08 Oct 2002 15:35:51 -0400 Subject: Mac porting advice? Message-ID: <3DA33397.6070903@stsci.edu> Porting numarray to the Macintosh has been on our TODO list at STSCI for a while and we're finally doing it. Right now, I have a shell account on a Mac running OS-X down the hall. Installing the "UNIX version" of Python and using the distutils to re-compile and install numarray, almost everything "just works." But since I'm not a Mac developer, I have a ton of questions: 1. If I build a binary distribution of numarray using the "UNIX version" of Python under Mac OS-X, can it be used with a native Mac version of Python? Looked at as a package, numarray includes both native python code and C extension modules. 2. The only hard part porting numarray to the Mac was floating point exception handling. On Linux, we use "fenv.h" to provide the FP exception handling functions. I found an "fenv.h" in the FlatCarbon header directory. Using that, and -framework Carbon in a manual link, everything worked. But... a. Should I be using Carbon? Are there any other ways to get the equivalent of fenv.h? b. Assuming I want to, how do I build a Python that just uses Carbon automatically in distutils? c. How do I "trick" the distutils into using "-framework Carbon" to link for any Mac Python? The extension options I know about *append* to the command line, which doesn't seem to work for -framework Carbon. 3. What are the CPP macros for detecting Mac-hood? I see "darwin" used in the Python source, but I had to add it to distutils myself as an extra_compile_arg: -Ddarwin 4. How good is the free C development IDE for the Mac? (Am I wasting my time in a shell account?) Is OS-X 10.2 worth getting? We have 10.1 now. Thanks in advance, Todd -- Todd Miller jmiller at stsci.edu STSCI / SSB From Marek at biosolveit.de Thu Oct 17 05:43:17 2002 From: Marek at biosolveit.de (Thomas M.) Date: Thu, 17 Oct 2002 11:43:17 +0200 Subject: pickling Message-ID: i am programming a database-server for a calender and have a probling with the pickling modul. i have the class "server", which i bequest to the class "DBserver", that class start for every connection a new thread with the object "ConnectionHandler". And now, the "ConnectionHandler" should pickle a "Event" object to a string and send it to the Client. But when i unpickle the object "Event", it have their own attributes but the methods of lthe class "server"!!! why ?! Thanks, thomas From magnus at thinkware.se Thu Oct 31 14:06:24 2002 From: magnus at thinkware.se (=?ISO-8859-1?Q?Magnus_Lyck=E5?=) Date: Thu, 31 Oct 2002 20:06:24 +0100 Subject: Ruby and Python (was Re: Why is Python a good first scripting language?) References: Message-ID: Michael Hudson wrote: > It seems to be three-and-a-bit times quicker than yours (and it may be > algorithmically better too, not sure). The *fastest* I know is due to > Christian Tismer, and is completely out of control: > > def tissieve6(n): > if n < 2: return [] > candidates = range(-1, n+1, 3) > # yes they are wrong, adjusted later. > sq = math.sqrt(n) > end = sys.maxint > candidates[:2] = [0, 0] > for p in candidates: > if p: > if p%2==0: p=p-1 > if p>sq : break > dist = p2 = p+p > if p%3 == 1: dist=dist+dist > dist = dist/3 > try: # indexing too far > for q in xrange( (p*p+3)/3, end, p2):\ > candidates[q] = 0 ;\ > candidates[q+dist] = 0 > except:pass > candidates[:2] = [2, 3] > candidates = filter(None, candidates) > for i in xrange(1, len(candidates)): > if candidates[i]%2 == 0:\ > candidates[i] = candidates[i]-1 > return candidates I tried this, with surprising result... (Python 2.2.1) The surprise isn't the speed, but that Tismer's version finds more primes, like 25, 35, and 49... Something missing? Alex Martelli Version 0.000488050855626 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97 Tim Peters Version 0.000227682568595 [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97] Christian Tismer Version 0.000374907984115 [2, 3, 5, 7, 11, 13, 17, 19, 23, 25, 29, 31, 35, 37, 41, 43, 47, 49, 53, 55, 59, 61, 65, 67, 71, 73, 77, 79, 83, 85, 89, 91, 95, 97] From bokr at oz.net Sat Oct 12 18:31:08 2002 From: bokr at oz.net (Bengt Richter) Date: 12 Oct 2002 22:31:08 GMT Subject: Ignoring comments - Parsing input file References: <3da7ec64$0$33885$e4fe514c@dreader4.news.xs4all.nl> Message-ID: On Sat, 12 Oct 2002 11:32:12 +0200, Yigal Duppen wrote: >Simon Faulkner wrote: > >> I am writing a script which reads it's input from a text file >> >> What is the easiest way to make it ignore lines that start with # or >> blank lines? > I suspect Simon would want to count ' # blah ... ' as "starting with #" too, so, (untested ;-) ># python2.2 code ># untested :-) >for line in inputfile: sline = line.strip() if not sline or sline.startswith('#'): continue > if not line.strip(): > # blank line, ignore > continue > > if line.startswith("#"): > # comment line, ignore > continue > > # line is not empty, not a comment > process_line(line) > > >Hope this helps, Ditto Regards, Bengt Richter From newsfroups at jerf.org Thu Oct 17 21:35:03 2002 From: newsfroups at jerf.org (Jeremy Bowers) Date: Fri, 18 Oct 2002 01:35:03 GMT Subject: About Python Syntax References: Message-ID: On Thu, 17 Oct 2002 12:31:09 +0700, Hung, Le Khanh wrote: > The more important reason for introduction of new control structures for > Python is the possibility of making a fullly visual interactive IDE for > Python. Programmer would be not able to make syntax errors! You seriously underestimate the ingenuity of programmers. And I'm at a loss to connect the need for your control statements with making a "fullly [sic] visual interactive IDE". In fact, your whole post kind of skirts the edge of comprehensibility. Granting you the benefit of the doubt, which has taken deliberate effort on my part (the urge to be sarcastic is nearly irresistable), you really, really need to better explain yourself, what you are doing, and exactly what you want before you'll get anything sensible in reply. Also, I am willing to personally guarentee you the answer is not to re-write Python's control structures, which are the way they are for quite good reasons. From ark at research.att.com Wed Oct 2 21:10:52 2002 From: ark at research.att.com (Andrew Koenig) Date: Wed, 2 Oct 2002 21:10:52 -0400 (EDT) Subject: [Python-Dev] PEP239 (Rational Numbers) Reference Implementation and new issues In-Reply-To: <200210030020.g930KBT06090@pcp02138704pcs.reston01.va.comcast.net> (message from Guido van Rossum on Wed, 02 Oct 2002 20:20:11 -0400) References: <20021002221421.GA29958@thyrsus.com> <200210030020.g930KBT06090@pcp02138704pcs.reston01.va.comcast.net> Message-ID: <200210030110.g931AqP07405@europa.research.att.com> Guido> [Andrew Koenig] >> Much as I like APL, I'd rather use Scheme's numeric model. Guido> I've heard that before, but I've also heard criticism of Guido> Scheme's numeric model. "It works in Scheme" doesn't give me Guido> the warm fuzzy feeling that it's been tried in real life. ...and "It works in APL" does? More seriously, there aren't that many languages with infinite-precision rationals, which means there aren't all that many precedents. I find the partial ordering among Python's types interesting. If we use "<" to mean "is a strict subset of", then int < long < rational (except perhaps on machines with 64-bit int, which opens a different can of worms entirely) int < float < rational float < complex Excluding complex, then, adding rational to the numeric types makes the numeric types a lattice. We could make all of the numeric types a lattice by adding a "complex rational" type: complex rational | \___ | \ rational complex / \ ____/ / \ / long float \ __/ \ / \ / int What's nice about a lattice is that for any two types T1 and T2, there is a unique minimum type T of which T1 and T2 are both subsets (not necessarily proper subsets, because T1 could be a subset of T2 or vice versa). From see_reply_address at something.invalid Thu Oct 3 21:46:21 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Fri, 04 Oct 2002 13:46:21 +1200 Subject: [Python-Dev] PEP239 (Rational Numbers) Reference Implementation and new issues References: <7xlm5flfnj.fsf@ruckus.brouhaha.com> <15772.24761.92493.82590@localhost.localdomain> Message-ID: <3D9CF2ED.3020507@something.invalid> Fernando P?rez wrote: > Chad Netzer wrote: > > In expressions that go to 0/0, > you need to figure out which one (num/den) goes faster to 0 to be able to > answer. Long faded memories of calc. classes trickle in ... My own faded memory says: L'Hopital's Rule. Differentiate top and bottom and take the limit of that instead. Repeat until top and bottom don't both go to 0. There's no doubt some terribly good reason why this works, but I can't remember it, if I ever knew... -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From tjreedy at udel.edu Wed Oct 9 08:50:00 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 9 Oct 2002 08:50:00 -0400 Subject: partial list sort References: <20021009094141.GA852@jsaul.de> Message-ID: "jsaul" wrote in message news:20021009094141.GA852 at jsaul.de... > Hi there, > > I am looking for the proper way to sort a list range-wise. The > scenario is as follows: I am reading a list of data elements > triple-wise component A, B and C, then the next triple A, B, C and > so on. Each list element has a component identifier which takes > the values "A", "B", or "C". What I want is to sort the components > within each *triple*, but *not* the while list, so that I can > assure an order of A-B-C no matter what the original order in the > data was, which can as well be B-C-A or whatever. > > Here is a simplified version of my script illustrating the > problem: > > list=[ [1,'C'], [2,'B'], [3,'A'], [4,'C'], [5,'B'], [6,'A'] ] > print list Don't use list as a variable name. It is a builtin type name. I will call this lis3. > def sort_components (list): > def cmp_comp (data1, data2): > if data1[1] == data2[1]: return 0 > elif data1[1] < data2[1]: return -1 > return 1 > print list > list.sort(cmp_comp) > print list > return Tabs are bad for Usenet posting if you want stupid people like me who use Outlook Express to read posted code. > for k in range(0, len(list), 3): > # sort over ranges: > sort_components(list[k:k+3]) for k in range(0, len(lis3), 3): #not tested tem = lis3[k:k+3] sort_components(tem) lis3[k:k+3] = tem ... > want [[3, 'A'], [2, 'B'], [1, 'C'], [6, 'A'], [5, 'B'], [4, 'C']] ... > Can anybody give me a hint about what I have overlooked? That you must copy sorted slice back into list. All of this would be much easier if list were organized as list of explicit triples and if pairs had sort key first. IE (tested) lis3=[ [['C',1], ['B',2], ['A',3]], [['C',4], ['B',5], ['A',6]] ] for triple in lis3: triple.sort() >>> lis3 [[['A', 3], ['B', 2], ['C', 1]], [['A', 6], ['B', 5], ['C', 4]]] Since you presumably want to process triples after sorting, I would suggest going this route. IE >>> listin=[ [1,'C'], [2,'B'], [3,'A'], [4,'C'], [5,'B'], [6,'A'] ] >>> for item in listin: item.reverse() ... >>> listin [['C', 1], ['B', 2], ['A', 3], ['C', 4], ['B', 5], ['A', 6]] >>> worklist=[[listin[i],listin[i+1],listin[i+2]] for i in range(0,len(listin),3)] >>> worklist [[['C', 1], ['B', 2], ['A', 3]], [['C', 4], ['B', 5], ['A', 6]]] >>> for triple in worklist: triple.sort() ... >>> worklist [[['A', 3], ['B', 2], ['C', 1]], [['A', 6], ['B', 5], ['C', 4]]] Terry J. Reedy From aleax at aleax.it Thu Oct 10 17:42:51 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 10 Oct 2002 21:42:51 GMT Subject: Combinatorics References: <3D9B1953.3030109@moving-picture.com> Message-ID: Peter Dobcsanyi wrote: > Alex Martelli wrote: >> Incidentally, if you do a lot of combinatorics and need reasonable >> performance, you may want to look at gmpy.sf.net: > > Actually, I do. Thank you for the pointer. Peter was also kind enough in followup mail to point out that the gmpy he downloaded doesn't handle GMP 4.* (which changed a field name in a struct) -- so it seems the code I have in the sourceforge CVS gmpy.c, i.e., only relevant snippet: if(resob) { #if __GNU_MP__ >= 4 mpz_set(resob->z, randstate->_mp_seed); #else mpz_set(resob->z, randstate->seed); #endif result = (PyObject*)resob; didn't make it to the last release -- I apologize and I'll try to make another release package next week -- meanwhile I suggest that people who want to try GMPY and have problems with GMP 4 could try getting the CVS gmpy (it's stable, solid, tested) and build that. Sorry for the inconvenience, everybody!-( Alex From spirit_of_amiga at h-o-t-m-a-i-l.com Wed Oct 9 17:25:22 2002 From: spirit_of_amiga at h-o-t-m-a-i-l.com (Spirit of Amiga) Date: Wed, 9 Oct 2002 17:25:22 -0400 Subject: encoding python scripts Message-ID: <291p9.17755$ZO1.822767@news20.bellglobal.com> Hi everyone, I'm sure this question has been asked before but I thought I'd troll for some fresh perspectives. I was wondering what approaches python developers have taken to encode and thus protect their commercial applications? I'm looking to migrate from PHP, which has Zend Encoder (and several others), but is a bit lightweight for my needs. In Python I believe I've found the light: code that reads like comments, however first I'd like to ascertain that I can protect my future commercial interests. Does such an avaricious mentality even exist in the Python community? Rick From donnal at donnal.net Sat Oct 12 15:49:52 2002 From: donnal at donnal.net (Donnal Walter) Date: 12 Oct 2002 12:49:52 -0700 Subject: indirect argument assignment Message-ID: <918bc22f.0210121149.4dc14e0c@posting.google.com> The following example is contrived in order to pose a few specific questions; the actual application I have in mind is more complicated. In a given class I want to create a large number of attributes (say 10-50) of different types (different classes) but with similar constructor signatures. After each attribute is created I want to do something else with it (such as add it to a list as in this example). class ACompositeClass: def __init__(self): self.objectList = [] self.attr1 = UserClassA('spam', 23) self.objectList.append(self.attr1) self.attr2 = UserClassZ('eggs', 42) self.objectList.append(self.attr2) ... Although this code is straightforward enough, the following syntax essentially reduces the number of lines in the __init__ statement by half, at the expense of adding only a three-line method. class ACompositeClass: def __init__(self): self.objectList = [] self.Add(UserClassA, 'attr1', 'spam', 23) self.Add(UserClassZ, 'attr2', 'eggs', 42) ... def Add(self, type, name, arg1, arg2): self.__dict__[name] = type(arg1, arg2) self.objectList.append(self.__dict__[name]) In the real application from which this made-up example was derived, the Add() method does a lot more work that would be cumbersome to do in the __init__() method, so my questions are not really about efficiency (or even about clarity) but about safety and acceptability. 1. In Tutorial Section 9.2 it says, "Most namespaces are currently implemented as Python dictionaries, but that's normally not noticeable in any way (except for performance), **and it may change in the future**." (emphasis mine) Therefore, is the following statement safe as far as future compatibility is concerned? self.__dict__[name] = type(arg1, arg2) Is there a better Python idiom to do the same thing? Is there a more Pythonic way to write the third line of the Add() method? 2. I read somewhere once that one should avoid using local names that are common Python words (such as "type") even if they aren't Python keywords. Instead of positional arguments for Add(), however, I intend to use keyword arguments, and "type" seems to be the most intuitive argument name. Is this likely to get me in trouble? From jdavis at empires.org Thu Oct 10 05:20:02 2002 From: jdavis at empires.org (Jeff Davis) Date: Thu, 10 Oct 2002 09:20:02 GMT Subject: force variable declaration? References: Message-ID: <6Dbp9.69869$X9.12557473@twister.socal.rr.com> what do you mean force variable declaration? you mean type checking? You can't really force python to limit you like that. That type of checking is better served by a tool independent of the interpreter. For example, pychecker is great for spotting probable errors in your code, even when the interpreter doesn't complain. See if pychecker is able to help spot your error. That way, we have the flexibility of python's dynamic typing, but we can spot our errors quickly as well. Regards, Jeff > Hi, > > is it possible to force variable declaration in python (like it is for > example in perl)? A few days ago I had an anoying error because of a > typing error of a variable... > > Regards, > Peter From pinard at iro.umontreal.ca Thu Oct 10 14:24:59 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: Thu, 10 Oct 2002 14:24:59 -0400 Subject: No tabs in post PLEASE!!! (was Re: partial list sort) In-Reply-To: <15781.35354.220462.463800@montanaro.dyndns.org> (Skip Montanaro's message of "Thu, 10 Oct 2002 09:09:30 -0500") References: <20021009094141.GA852@jsaul.de> <15781.35354.220462.463800@montanaro.dyndns.org> Message-ID: [Skip Montanaro] > (defun untab-buffer () > (untabify (point-min) (point-max))) > > (add-hook 'mail-send-hook 'untab-buffer) It happens, sometimes, that you ought to preserve TABs. For example, when you are sending diffs. So the rule should not be burned too deep in your outgoing mailer. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From neal at metaslash.com Tue Oct 1 17:53:00 2002 From: neal at metaslash.com (Neal Norwitz) Date: Tue, 01 Oct 2002 21:53:00 GMT Subject: How to build debuggable executable on Solaris? References: Message-ID: On Tue, 01 Oct 2002 16:33:25 -0400, Skip Montanaro wrote: > > Dbx seems okay with the executable (it doesn't warn about not finding > any debug symbols), but "stop main" doesn't work as I remembered from > ages ago: > > For information about new features see `help changes' To remove this > message, put `dbxenv suppress_startup_message 7.0' in your > .dbxrcReading python Reading ld.so.1 > Reading libsocket.so.1 > ... > Reading libCstd_isa.so.1 > detected a multithreaded program > (dbx) b main > b: not found > (dbx) stop main > dbx: anachronism: Use 'stop change ' or 'stop cond > '. Event specifications without keywords will not be > accepted in future releases dbx: 'main' is a function or procedure, > expected variable (dbx) run I think it should be: stop in main There is a way to tell dbx to use gdb commands. I don't remember exactly what you need to do, but you need to add a line to your .dbxrc file like: gdb on http://wwws.sun.com/software/sundev/archive/developer/documentation/mr/READMEs/dbx.html Neal From tismer at tismer.com Wed Oct 2 19:13:57 2002 From: tismer at tismer.com (Christian Tismer) Date: Wed, 02 Oct 2002 16:13:57 -0700 Subject: PEP239 (Rational Numbers) Reference Implementation and new issues References: <20021002221421.GA29958@thyrsus.com> Message-ID: <3D9B7DB5.4000702@tismer.com> Fran?ois Pinard wrote: > [Eric S. Raymond] > > >>>1) Should future division return rationals rather than floats. >> > >>+1 for returning rationals. It's the right thing -- and if it fails, >>it will fail noisily, right? +1 here, too! > While I agree with the theoretical arguments, I have the practical fear that > rationals could grow very big, rather quickly, in the course of a long > computation involving them in various ways. By big, I mean the numerator > and denominator of the fraction taken in isolation, not the number itself. > Consider inversions of an integer matrices, approximations with truncated > series, or worse things like, maybe, discrete Fourier transforms. Yes, this fear is right. I think this is just great. Let it grow! Let the user feel what precision he's carrying around, and how much they throw away when they reduce down to float. No I think this is really of advantage. Exact is better than small, and it is all in the user's hand. Make a float() and you're done. > Bigger rationals are, slower they become, and more memory they take. The > danger is that programmers may get surprised or hurt by Python performance > degradation, raising frequent and recurrent questions here and elsewhere. > > On the other hand, I would love if Python was not loosing precision on > non-truncating integer division, so let me try a bit to destroy my own > fears. On average, most programs will not use matrices of rational numbers, > nor play with series. Moreover, most programs do not use so many different > numeric variables anyway, nor perform long computations involving them. > Many programs do not go beyond adding or subtracting one, once in a while! I don't think one was considering to go rationale, all the time, just as the result of integer divide? To me, rationales would be the natural superclass of integers. Floats would stand somewhere else, really different animals. > So, I would guess that _on the average_, using rational numbers might be > acceptable and go almost unnoticed by most people. So it might be more > worth accepting as a community to warn programmers who are more prone to > numerical algorithms of the intrinsic dangers of integer division in Python. > > But those feelings are no proof of anything. How do we get the confirmation > that using rationals in Python would be easy going and innocuous in > practice, beforehand? It would surely be nice relying in such a feature! I'm all for it. Get correct results in the first place. Cut precision explicitly when needed, or for optimization. BTW., Mathematica did the same thing. Very handy if you are doing symbolic operations on polynomials, and you can easily keep exact coefficients for a long time. Another point is that a long division would never give an overflow. Overflow since floats are too limited is an effect I don't find funny. ciao - chris -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 pager +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From andrew at acooke.org Tue Oct 15 16:14:11 2002 From: andrew at acooke.org (andrew cooke) Date: 15 Oct 2002 13:14:11 -0700 Subject: suggestion for "improving" prng implementation Message-ID: hi, i know that this isn't a bug - i understand a little about multiplicative congruential generators and know that there is not intended to be any guarantee of independence between sequences from different seeds (hence the jumpahead functionality etc). however, random numbers are used in a wide range of applications. while many require careful thought about the statistical properties, others only need something that is "fairly random". so if there's a simple way to make the implementation of the prng more useful in the latter group, without harming the former group, then it seems worth thinking about. if you look at the output i'll paste below, you'll see that the first couple of values of sequences with neighbouring seed values are strongly correlated across sequences (this is understandable, given the algorithms used). but if the first few (4?) values after seeding were automatically generated and dropped, then this correlation would be unimportant to "fairly random" applications. a change like this would let a someone writing a game (say) use seeding to generate "different" sequences without needing to worry that (say) the first move of the computer controlled alien will be to the same on successive level, etc etc... (there is one danger - if people require repeatable sequences from seeds across python versions. this change would break that repeatability). i just want to repeat again that this is simply to make life easier for "quick and dirty" uses of the prng. i am not claiming that this change will improve the prng for "serious" use. cheers, andrew >>> random.seed(123) >>> for i in range(10): print random.random(), ... 0.711800244467 0.717910754873 0.78581128287 0.248291539217 0.927000874956 0.767848388239 0.163218671249 0.989680083335 0.492734220966 0.941375396456 >>> random.seed(124) >>> for i in range(10): print random.random(), ... 0.71744958868 0.683948615391 0.978285431339 0.16137092737 0.0635762491011 0.122237367062 0.763734050019 0.677809853067 0.162924845037 0.543972112568 >>> random.seed(125) >>> for i in range(10): print random.random(), ... 0.723098932894 0.649986475908 0.170759579808 0.0744503155232 0.200151623246 0.476626345885 0.364249428789 0.365939622798 0.833115469108 0.146568828681 >>> random.seed(126) >>> for i in range(10): print random.random(), ... 0.728748277107 0.616024336425 0.363233728276 0.987529703676 0.336726997391 0.831015324709 0.96476480756 0.0540693925296 0.503306093179 0.749165544793 >>> random.seed(127) >>> for i in range(10): print random.random(), ... 0.734397621321 0.582062196943 0.555707876745 0.900609091829 0.473302371537 0.185404303532 0.56528018633 0.742199162261 0.17349671725 0.351762260905 >>> random.seed(128) >>> for i in range(10): print random.random(), ... 0.740046965534 0.54810005746 0.748182025214 0.813688479982 0.609877745682 0.539793282355 0.165795565101 0.430328931992 0.84368734132 0.954358977017 >>> random.seed(129) >>> for i in range(10): print random.random(), ... 0.745696309748 0.514137917978 0.940656173683 0.726767868135 0.746453119827 0.894182261178 0.766310943871 0.118458701724 0.513877965391 0.556955693129 From skip at pobox.com Thu Oct 31 12:09:47 2002 From: skip at pobox.com (Skip Montanaro) Date: Thu, 31 Oct 2002 11:09:47 -0600 Subject: Overcoming regex memory limits? In-Reply-To: <88caaeda.0210310727.3fd2fcd9@posting.google.com> References: <88caaeda.0210310727.3fd2fcd9@posting.google.com> Message-ID: <15809.25563.766044.228690@montanaro.dyndns.org> yin> I've heard that it may be possible to match without using the (.*?) yin> construct and this may solve the problem. Any suggestions short of yin> a rewriting the parsing routine would be appreciated. If you can give us an example of a regular expression which blows up and an example of the text you expect to feed it, perhaps someone can make some suggestions. -- Skip Montanaro - skip at pobox.com http://www.mojam.com/ http://www.musi-cal.com/ From bfordham at socialistsushi.com Fri Oct 25 08:17:48 2002 From: bfordham at socialistsushi.com (Bryan L. Fordham) Date: Fri, 25 Oct 2002 08:17:48 -0400 Subject: CGI: How do I do this? References: Message-ID: <3DB9366C.2070404@socialistsushi.com> Doru-Catalin Togea wrote: [snip] > print header(), start_html(); > my @fields = CGI::param(); <-- how do I do this > in Python? > print "

\n"; > foreach my $k (@fields) { > my $v = param($k); > print "$k -> \"$v\"
"; > } [snip] from http://www.python.org/doc/current/lib/node297.html -- > form = cgi.FieldStorage() > if not (form.has_key("name") and form.has_key("addr")): > print "

Error

" > print "Please fill in the name and addr fields." > return > print "

name:", form["name"].value > print "

addr:", form["addr"].value > ...further form processing here... You can also do form.keys() The cgi module docs are pretty helpful; poking around in there should show you everything you want to know 8) --B From tjones at tolisgroup.com Thu Oct 31 15:40:22 2002 From: tjones at tolisgroup.com (Tim Jones) Date: Thu, 31 Oct 2002 13:40:22 -0700 Subject: Successfully Compiling 2.2.2 w/Tkinter under OS X References: Message-ID: <3DC19536.5000800@tolisgroup.com> Actually, it's AquaTK with tcl/tk 8.4.1 in Aqua mode (tcl/tk apps from my Solaris and Linux systems work okay with the built version). macpython-sig answers were to use macpython. Unfortunately, this only provide Tkinter support under Classic, not OS X. Queries to other Mac and OS X oriented lists have resulted in silence. I'm sure that someone has gotten Python and Tkinter working under Aqua on OS X. Michael Hudson wrote: > Tim Jones writes: > > >>Does anyone have information to share on getting Python 2.2.2 to >>recognize a built and installed tcl/tk 8.4.1 installation under Jaguar? >> >>The TCL/TK and Python builds complete successfully, but Python does >>not locate the TK installation > > > Is that AquaTk or an X11 one? > > Anyway, the pythonmac-sig is probably a better place for this question > (or maybe its archives are the place to hit). > > Cheers, > M. > -- --------- Tim Jones tjones at tolisgroup.com From aleax at aleax.it Thu Oct 10 06:37:44 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 10 Oct 2002 10:37:44 GMT Subject: apache+ python ? References: Message-ID: eugene kim wrote: > hi.. > > i'd like to use python on my website.. > i read there are several ways of doing it? (cgi/mod_python) > > can u give me some advice which way i have to go? Use WebWare, specifically the WebKit part of it. Once you code to the WebKit APIs, you can later decide to make your Python programs cooperate with your server in any of many different ways (cgi, mod_python, mod_webkit, etc). Alex From cnetzer at mail.arc.nasa.gov Fri Oct 4 17:16:52 2002 From: cnetzer at mail.arc.nasa.gov (Chad Netzer) Date: Fri, 4 Oct 2002 14:16:52 -0700 Subject: making a class return None from __init__ In-Reply-To: <3D9DFE13.5040500@mxm.dk> References: <3D9DFE13.5040500@mxm.dk> Message-ID: <200210042116.OAA05044@mail.arc.nasa.gov> On Friday 04 October 2002 13:46, Max M wrote: > Rajarshi Guha wrote: > > (where v will fail) I always get <__main__.Graph instance at > > 0xXXXXXX> Is there any way to make the constructor return a None > > object? > > def noner(): > return ie. Create a factory function that returns the initialized class when everything goes well, or None upon failure: class MyClass: def __init__( self, arg1, arg2, arg3 ): return def MyClassFactory( arg1, arg2, arg3 ): if valid_args( arg1, arg2, arg3 ) return MyClass( arg1, arg2, arg3 ) else: return None Note - this is arguably bad style, UNLESS it is clear that you are invoking a factory rather than a class constructor. Typically, you use a factory to have flexibility in choosing which class is actually instantiated, NOT because you need to test error conditions. Better to use exceptions in the __init__, and abort the class initialization if you cannot use the class. Returning either a class or None, just doesn't feel right, especially if the user is assuming only one specific class to be created. -- Chad Netzer cnetzer at mail.arc.nasa.gov From bobsedge at yahoo.com Fri Oct 18 19:09:13 2002 From: bobsedge at yahoo.com (Robbie Sedgewick) Date: 18 Oct 2002 16:09:13 -0700 Subject: Numeric arrays with named axes? References: Message-ID: "Duncan Smith" wrote in message news:... > >>> cow = Variable(['friesan', 'charolet'], 'cow') > >>> dog = Variable(['whippet', 'terrier'], 'dog') > >>> values = Numeric.array([[0, 2], [3, 5]]) > >>> t = NumTable(values, [cow, dog]) I like the way you name the elements as well as the axes. That would be very useful as well. Good idea. > > I assume you'll be doing something different, so your code will be > different. But it's certainly doable. Yeah, I'd kinda like something that works like Numeric, other then the extra names, so that I could use it unmodified in many different products. I'll play around with it when I get some free time. Thanks for the ideas.... Robbie From aahz at pythoncraft.com Thu Oct 31 12:28:03 2002 From: aahz at pythoncraft.com (Aahz) Date: 31 Oct 2002 12:28:03 -0500 Subject: lists, performance.. References: Message-ID: In article , gabor wrote: > >i wanted to deep-copy because the created big list will be used in a >different thread than the small ones... so i thouhgt let's have it as >safe as it can be... That's a tricky question. If you eventually want to reflect the changes in the big last back to the smaller lists, you may be better off doing locking instead of copying. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From wilk-spamout at flibuste.net Fri Oct 11 03:35:19 2002 From: wilk-spamout at flibuste.net (William) Date: 11 Oct 2002 09:35:19 +0200 Subject: Another Python and Apache question References: Message-ID: <87d6qhzavc.fsf@flibuste.net> "dsavitsk" writes: > I am asking this not knowing much of the background that I should, so I am > just fishing for opinions ... > > Is it possible to write an Apache module in Python, and is it even worth > doing? Is there some sample code out there? Why don't you use a python webserver directly rather than apache ? like twistedmatrix for example, it will be easier to extend in python. wil From gerhard.haering at gmx.de Sun Oct 20 18:32:54 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Mon, 21 Oct 2002 00:32:54 +0200 Subject: data from a web page In-Reply-To: <5IFs9.15414$TD1.699474@news2.tin.it> References: <8RDs9.14810$TD1.676374@news2.tin.it> <3DB321E6.4020508@gazeta.pl> <5IFs9.15414$TD1.699474@news2.tin.it> Message-ID: <20021020223254.GA20381@lilith.ghaering.test> * Maschio_77 [2002-10-20 22:00 +0000]: > "bromden" wrote: > > what do you exactly mean? > > [...] > > - you just want to read a webpage? look here: > > http://www.python.org/doc/current/lib/module-httplib.html > > > > The first: I want to read the web page content from my little > > program to take some data gerhard at gargamel:~$ python Python 2.2.2 (#1, Oct 18 2002, 03:24:30) [GCC 2.95.4 20020320 [FreeBSD]] on freebsd4 Type "help", "copyright", "credits" or "license" for more information. >>> import urllib >>> print urllib.urlopen("http://www.python.org/").read() [...] More in the docs about the urllib module. HTH, -- Gerhard From brian at sweetapp.com Sun Oct 13 21:40:28 2002 From: brian at sweetapp.com (Brian Quinlan) Date: Sun, 13 Oct 2002 18:40:28 -0700 Subject: realtime design In-Reply-To: Message-ID: <006a01c27322$ad14f7b0$df7e4e18@dell1700> Chris wrote: >> CPython uses malloc/free to allocate/deallocate Python objects. >> The malloc routine must search a free list for a memory block >> of sufficient size. So the timing of trivial Python operations >> can vary significantly, depending on the malloc implementation >> and the history of previous memory allocations/deallocations. > ok, sure. but i want to make clear that has nothing to do with > Python suitability for real time applications if the underlying OS > causes the troubles. if the underlying memory management is that bad, > even the smallest programm in C suffers from the same problem. 1. I'm not arguing that CPython is not appropriate for realtime applications. 2. The C standard library is not (usually) part of the OS. 3. The smallest program in C need not allocate memory dynamically at all. And it might be possible to structure larger programs such that the portions requiring realtime performance need not allocate memory dynamically. Currently I am using working with an embedded realtime system where the dynamic memory allocation is only performed at system startup time. Cheers, Brian From jepler at unpythonic.net Wed Oct 23 16:48:03 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 23 Oct 2002 15:48:03 -0500 Subject: embedding tcl interpreter in Python In-Reply-To: <3DB5C6F2.1060208@physics.rutgers.edu> References: <3DB5C6F2.1060208@physics.rutgers.edu> Message-ID: <20021023204802.GE17118@unpythonic.net> I think it would be sometimes-convenient to have _tclinter/Tclinter modules. It should not be difficult to do, though a little harder to do if you want to share the code with _tkinter/Tkinter, not duplicate it. (I hear that Tk can be loaded with a tcl "load" command in 8.4 by default, and in previous versions with corret configuration, which would make it easy to write Tkinter on top of the hypothetical _tclinter) The patch tracker on the sourceforge site is a good place to put this, even if it's not ultimately incorporated into Python. http://sourceforge.net/tracker/?group_id=5470&atid=305470 A few years go there was a program, possibly called "minotaur", intended to be a bridge between multiple scripting languages. I know Python and tcl were two of the languages bridged. Jeff From tsidwick at remove.yahoo.co.uk Mon Oct 14 18:15:20 2002 From: tsidwick at remove.yahoo.co.uk (Tom) Date: Tue, 15 Oct 2002 00:15:20 +0200 Subject: mod_python and xml.dom.minidom problem References: <3DAB182B.9000201@remove.yahoo.co.uk> <3DAB2C4D.5040602@remove.yahoo.co.uk> Message-ID: <3DAB41F8.1080308@remove.yahoo.co.uk> > > I see. It then appears that you have picked up the wrong copy of the > pyexpat module. Can you find out the value of > > xml.parsers.expat.__file__ /usr/lib/python2.2/site-packages/_xmlplus/parsers/pyexpat.so > xml.parsers.pyexpat.__file__ /usr/lib/python2.2/site-packages/_xmlplus/parsers/expat.pyc > xml.parsers.expat.version_info (1, 95, 2) > xml.parsers.expat.pyxml_expat_version this doesn't appear to exist but, xml.parsers.pyexpat.version_info = (1, 95, 2) Tom From martin at v.loewis.de Fri Oct 18 03:20:25 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 18 Oct 2002 09:20:25 +0200 Subject: no struct.pack for unicode strings? References: Message-ID: Radovan Garabik writes: > Why there is no format to pack/unpack unicode strings? > Or am I missing something? It's not entirely clear what struct.pack should do with a Unicode object: UTF-8, UTF-16 (big or little endian, with or without BOM), UTF-32 (big or little endian, with or without BOM), system encoding, ... Hence, no packing is provided. > My application needs to struct.pack unicode strings, to save them into a > file which can be then read by a C extension module where I need to > access characters of the string (as Py_UNICODE). To save Unicode in a file, I recommend to encode them as UTF-8, and use PyUnicode_DecodeUTF8 in your extension module to restore the Unicode object. Regards, Martin From google at teknico.net Wed Oct 9 13:39:42 2002 From: google at teknico.net (Nicola Larosa) Date: 9 Oct 2002 10:39:42 -0700 Subject: Love "Python Cookbook" References: <3d9b05b5$0$220$4d4ebb8e@news.nl.uu.net> Message-ID: <2b134d29.0210090939.6dfd12b8@posting.google.com> > ...or I wouldn't have spent about 9 months of my life > as a co-editor helping to make it happen (I'd have been content to > be among the most prolific contributors of recipes to the online one:-). You were caught, admit it, at last: LUTHER BLISSETT IS YOU! (Nobody expects etc. etc.) ;^) From pythonaut at hotmail.com Fri Oct 18 11:57:16 2002 From: pythonaut at hotmail.com (Mr P) Date: Fri, 18 Oct 2002 11:57:16 -0400 Subject: Lucene and indexing Message-ID: I am looking for a fast, "industrial strength", incremental indexer for Python. I have looked at ransacker and indexer.py, but they don't cut the mustard. Are there any other I should look at? The Java community has a great indexer in Lucene (jakarta.apache.org/lucene). I have some experience with Lucene and it's feature rich, extensible and very fast. I was wondering if anyone has ported Lucene to Python? I think such a port would be a great addition to the .py universe. _________________________________________________________________ Surf the Web without missing calls!?Get MSN Broadband. http://resourcecenter.msn.com/access/plans/freeactivation.asp From JXSternChangeX2R at gte.net Mon Oct 7 21:11:29 2002 From: JXSternChangeX2R at gte.net (JXSternChangeX2R) Date: Tue, 08 Oct 2002 01:11:29 GMT Subject: Is there a "reset" in Idle? Message-ID: Another newbie question. After I've run a python program a few times and fixed a few bugs, it seems that the name spaces are polluted with old values. Is there any kind of a "reset" that clears everything without exiting and restarting the process? Python 2.2 on XP Pro. Thanks. Joshua Stern From aahz at pythoncraft.com Wed Oct 16 13:59:20 2002 From: aahz at pythoncraft.com (Aahz) Date: 16 Oct 2002 13:59:20 -0400 Subject: Most efficient method to search text? References: Message-ID: In article , Tim Peters wrote: > >re doesn't build a DFA. Alternatives are searched for one at a time, left >to right. See Friedl's "Mastering Regular Expression" book for long >discussions of the tradeoffs. In case people weren't paying attention a couple of months ago, Friedl now has the second edition out. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From alessandro.bottoni at infinito.it Thu Oct 17 10:48:35 2002 From: alessandro.bottoni at infinito.it (Alex @ Infinito) Date: Thu, 17 Oct 2002 16:48:35 +0200 Subject: [XML-SIG] SimpleXMLRPCServer-related questions In-Reply-To: References: <200210171245.g9HCjll26567@mail2.infinito.it> Message-ID: <200210171440.g9HEesl27837@mail2.infinito.it> Alle 15:22, gioved? 17 ottobre 2002, Martin v. Loewis ha scritto: > > What is ESO? > (OK, it is "OSE", actually... just a typo...:-) It is an (apparently) nice platform for distributed computing that can use messaging (a l? ISIS/HORUS), XML-RPC and SOAP technologies (maybe CORBA, as well...). You can find it at: Dumpleton Software Consulting Pty Limited http://www.dscpl.com.au and at: http://ose.sourceforge.net It is a C++ library with a Python wrapper. It has been briefly described by Graham Dumpleton at: http://aspn.activestate.com/ASPN/Coookbook/Python/ Many thanks for the info regarding the XML-RPC Server. I will look at CORBA, as you suggested, as well. ---------------------- Alessandro Bottoni From Doc at goodweb.de Fri Oct 4 09:15:54 2002 From: Doc at goodweb.de (Thomas Korb) Date: 04 Oct 2002 15:15:54 +0200 Subject: McMillan / Tk / encoding problem References: Message-ID: Actually, I have the usual import sys sys.setdefaultencoding('iso-8859-1') in my sitecustomize.py. I don't know, how the default-encoding can be set otherwise. In my script, I use an explicit 'import sitecustomize', which is maybe very naive, but somehow worked. (Before that, I got errors when a character was not in the ASCII-range 0-127; after that, those errors did not show up anymore; so it seemed to have 'some' effect.) Is there another way to set the default-encoding for use with your installer? (I never liked sitecustomize.py any way; and I always felt that something like sys.setdefaultencoding(...) should work in a normal script, too.) -- ________________________________________________________________________ Dr. Thomas Korb / GOODWEB.DEsign / www.goodweb.de / Doc at goodweb.de From loewis at informatik.hu-berlin.de Mon Oct 7 07:15:43 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 07 Oct 2002 13:15:43 +0200 Subject: Tcl/Tkinter problem References: Message-ID: Xiao-Qin Xia writes: > If I rename the directory /usr/lib/tcl8.3 and /usr/lib/tk8.3 to anything > other, python1.5 cannot use Tkinter either. So I guess python1.5 and > python2.2 use the same Tk library. But why they behavior different? Does > anybody know how to solve this problem? I assume Tk tries to convert Unicode strings to the encoding of your font and crashes in doing so. This problem then would not occur if there are no Unicode strings, as is the case with Python 1.5. I would guess that this is a bug in Tk; you may want to try Tcl 8.4 instead. Alternatively, try removing some of the encoding files in tcl, e.g. gb2312.enc or big5.enc. HTH, Martin From max at alcyone.com Wed Oct 16 18:32:04 2002 From: max at alcyone.com (Erik Max Francis) Date: Wed, 16 Oct 2002 15:32:04 -0700 Subject: Globals References: Message-ID: <3DADE8E4.612DAECA@alcyone.com> Newt wrote: > Questions: > > 1. Is this the correct/best way? > 2. To save typing in all the global statements, can I put them in to > an > include file or a source file? No, you can't. The global statements are notes in local scopes that some names should refer to the global names, not the local ones. These statements by definition have to be located in the _local_ scope, or otherwise they wouldn't serve their purposes. > 3. If I declare them in a .py file, do I still need the global > commands to > use them within Classes and Functions etc defined within that same > module? I find it's pretty rare that I have to use a true global variable -- that is, a variable at toplevel scope that actually gets rebound or points to a mutable object. (A "constant" is global in the sense of being available everywhere but obviously won't be changing so the bag of worms with modifying globals doesn't enter into it.) In the cases where I do need a mutable or rebindable global, I simply include the global statements wherever the globals are referenced (whether they're accessed or rebound). You only need the global statements where there is an ambiguity to be resolved, but I find it much more appropriate to simply use it wherever the globals are referenced. In practice, globals are rare enough, and the number of local scopes where the globals are actually referenced is low enough to make this not unreasonable. Note that I don't bother to do this with "constants" -- i.e., globals that are always only referenced, never modified or rebound. In my (not uncommon style) these are always represented with all-uppercase identifiers so they stand out enough to not cause a problem. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ Ride / Ride this wave of mine \__/ Res Sade Deluxe / http://www.sadedeluxe.com/ The ultimate Sade encyclopedia. From nospam at bigfoot.com Sat Oct 5 13:21:41 2002 From: nospam at bigfoot.com (Gillou) Date: Sat, 5 Oct 2002 19:21:41 +0200 Subject: About Zope References: Message-ID: "Juan Garcia" a ?crit dans le message de news: f8dcdd47.0210050828.5d8520fb at posting.google.com... > Hi, I am new using zope and I was trying to understand how the > "Quickstart" page works generating dynamic links. I have found a lot > of quotations in this style: > > or similar. This is not DTML nor TAL nor python. > Somebody can tell me what is this? This is old fashioned DTML (still working but AFAIK deprecated and may be abandoned in the future). and are equivalent. Try it in the Quickstart. BTW, TALES expressions in DTML would be great. > > > thank you Welcome --Gilles From logistix at zworg.com Sat Oct 12 15:33:42 2002 From: logistix at zworg.com (logistix) Date: 12 Oct 2002 12:33:42 -0700 Subject: Win32 and Excel ranges References: Message-ID: "L Whitley" wrote in message news:... > I've been going through Mark Hammond's book doing his Python/Excel examples. > It's working nicely but I'm dissapointed with the performance of storing a > lot of data in the spread sheet cell by cell. My data is in lists and I > would think that I would be reasonable to use ranges deliver the data to > Excel. I've found examples of how to read data from Excel using range, but > haven't found an example of how to write data to Excel using range. Can > anyone help? > > Larry Slightly offtopic, but did you run makepy against the Excel components? From cnetzer at mail.arc.nasa.gov Thu Oct 3 15:17:56 2002 From: cnetzer at mail.arc.nasa.gov (Chad Netzer) Date: Thu, 3 Oct 2002 12:17:56 -0700 Subject: [Python-Dev] PEP239 (Rational Numbers) Reference Implementation and new issues In-Reply-To: <15772.24761.92493.82590@localhost.localdomain> References: <7xlm5flfnj.fsf@ruckus.brouhaha.com> <15772.24761.92493.82590@localhost.localdomain> Message-ID: <200210031918.MAA11575@mail.arc.nasa.gov> On Thursday 03 October 2002 08:22, Skip Montanaro wrote: > Paul> I don't think you can do it that way without kludges to > deal with Paul> rational(NaN), rational(Inf), etc. > > Dunno about NaN, but wouldn't rational(Inf) be 1/0? And what about rational 0/0? Is that 1, or NaN (or Inf :-) )? -- Chad Netzer cnetzer at mail.arc.nasa.gov From psimmo60 at hotmail.com Wed Oct 16 08:18:09 2002 From: psimmo60 at hotmail.com (Paul Simmonds) Date: Wed, 16 Oct 2002 12:18:09 +0000 Subject: How to print an integer with commas; E.g., 3,056,789 Message-ID: Richard Bow wrote: >Given any integer n, how can I convert str(n) to a string with commas in >the appropriate places? For example, if n is 3056789, I'd like to convert >str(3056789) to "3,056,789", for better readability of output. I don't think there's a function available for this, but it's fairly easy to roll your own- just use slices of the string: def comma(bigint): strint=str(bigint) i=0 #increment counter j=len(strint)%3 #number of chars @ beginning newstr=strint[0:j] while i <3DA0C5AB.7050609@something.invalid> Message-ID: On Mon, 07 Oct 2002 12:22:19 +1300, Greg Ewing wrote: >Mark McEahern wrote: > >> Sorry, I was unclear. The FAQ I was suggesting was: >> >> How should I install Python 2.x on Red Hat 7.x so it doesn't mess up Red >> Hat's dependency on Python 1.5.2? > > >I think the trick is to install it so that the >binary has a distinctive name, e.g. "python2.2" >or "my_python" instead of just "python". Then >always explicitly refer to your version when >you want it. > IMO it would be nice if RH took that advice for *its* use of Python, and left bare "python" for the user to link as he saw fit, if s/he didn't like a default convenience setting to the latest stable version. Regards, Bengt Richter From tundra at tundraware.com Sun Oct 6 12:20:06 2002 From: tundra at tundraware.com (Tim Daneliuk) Date: 06 Oct 2002 16:20:06 GMT Subject: Python + Win32: Cut/Paste w/o GUI References: <5dukna.oh1.ln@boundary.tundraware.com> Message-ID: Steve Holden wrote: >>> >>>Sadly, I don't believe that it can. Certainly attempts to drag-and-drop >> > text > >>>from another window change the cursor into a "no-entry" sign over >> > program > >>>icons, implying that Windows doesn't regard them as legitiamte drop >> > targets. > >>>Neither does the context-menu item on a program shortcut include a >> > "Paste" > >>>option. >>> >> >>Well you definitely *can* paste text to a DOS box, at least under Win2K. >>You copy the text as usual, highight the DOS box and right click the > > mouse - > >>text pasted! >> > > > Yes, but that's pasting into a running program, not pasting into an icon > which then runs the program and somehow makes the text available. Since Yes, this was the behavior I wanted. But , actually, as I think about it, I don't recall having ever seen this done in any language, at least not on Win32. I guess you do have to have a running program to do the paste - which was your original point, I guess ;) > there have now been at least three different responses, apparently none of > them doing what you want, perhaps you could be a little more explicit about > your requirements? > The response from Roger Upole gave me what I wanted - I wrote a script which grabs the clipboard and parses it automatically to do what I need doing. Thanks for taking the time to respond... -- ------------------------------------------------------------------------------ Tim Daneliuk tundra at tundraware.com From max at alcyone.com Tue Oct 1 20:55:49 2002 From: max at alcyone.com (Erik Max Francis) Date: Wed, 02 Oct 2002 00:55:49 GMT Subject: Is the word "Python" copyrighted/trademarked? References: Message-ID: <3D9A4414.675036D7@alcyone.com> sismex01 at hebmex.com wrote: > Hmmm... "Python" is the name of a snake, and it's also > a common english word; I don't think it can be copyrighted. The question was about trademarks, not copyright. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ Honesty has nothing to hide \__/ Joi Crank Dot Net / http://www.crank.net/ Cranks, crackpots, kooks, & loons on the Net. From blackprogramming at yahoo.com Thu Oct 31 22:58:18 2002 From: blackprogramming at yahoo.com (black) Date: Thu, 31 Oct 2002 19:58:18 -0800 (PST) Subject: could python serve web scripts ? Message-ID: <20021101035818.16417.qmail@web14507.mail.yahoo.com> Howdy~ I'm learning ASP these days and bothered VBScript much, I want to kick it off and I wonder if Python could be substitution. and what about other scripts if not, thanx~ --------------------------------- Do you Yahoo!? HotJobs - Search new jobs daily now -------------- next part -------------- An HTML attachment was scrubbed... URL: From fperez528 at yahoo.com Tue Oct 8 23:55:30 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Tue, 08 Oct 2002 21:55:30 -0600 Subject: [OT} How to un-GPL parts of a GPL'd module. References: Message-ID: Seen on slashdot: "GPL made simple: What was my stuff is now our stuff. If you improve our stuff, please keep it our stuff." Credit: user #46721, whoever that is. (I quote my sources :) Cheers, f. ps. No, I won't get into the flamewar. I just liked the soundbite. From davegaramond at icqmail.com Sun Oct 6 05:01:01 2002 From: davegaramond at icqmail.com (David Garamond) Date: Sun, 06 Oct 2002 02:01:01 -0700 Subject: importing module from two packages with the same name Message-ID: <3D9FFBCD.4020806@icqmail.com> i have two modules in different location, but they belong to the same package name: /home/david/usr/lib/python/Package1/Libra.pm (1) /home/david/proj/Proj1/lib/python/Package1/Scorpio.pm (2) i have added both paths to sys.path: import sys sys.path.insert(0, '/home/david/usr/lib/python') sys.path.insert(0, '/home/david/proj/Proj1/lib/python') once python found Package1 in (1): import Package1.Libra it won't search in (2), so i can't import Package1.Scorpio. any hint/trick to work around this? is this the intended python module search behaviour? -- dave From aleax at aleax.it Fri Oct 4 04:12:31 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 04 Oct 2002 08:12:31 GMT Subject: regexp: extracting multiple multiline groups References: Message-ID: Steven Bethard wrote: > I have an input file that looks something like: > > --- 1 > A description that > could be multiple lines > --- 2 > Another description > ... > > I'd like to extract both the number and the corresponding description for > each entry. Right now, I do this by: > > docNumbersMatcher = re.compile(r"^--- (\d+)$", re.MULTILINE) > docNumbers = docNumbersMatcher.findall(output) > > docBoundaryMatcher = re.compile("^--- \d+$", re.MULTILINE) > docs = docBoundaryMatcher.split(output) > > However, it seems a waste to run through the same document twice with > essentially the same expression. Is there a way to do this with a single > pass? I've tried a few things, but they typically take too much or too > little. For example: You need non-greedy matching and look-forward: import re m = re.compile(r'^--- (\d+)\n(.*?)((?=--- \d+\n)|\Z)', re.MULTILINE | re.DOTALL) output = """\ --- 1 A description that could be multiple lines --- 2 Another description also potentially multiline --- 3 But descriptions can also be singleline --- 4 although they need not be """ print m.findall(output) This prints: [alex at lancelot ba]$ python mure.py [('1', 'A description that\ncould be multiple lines\n', ''), ('2', 'Another description\nalso potentially multiline\n', ''), ('3', 'But descriptions can also be singleline\n', ''), ('4', 'although they\nneed not\nbe\n', '')] If the empty-group '' at the end of each tuple is a bother, you can also use nongrouping parentheses m = re.compile(r'^--- (\d+)\n(.*?)(?:(?=--- \d+\n)|\Z)', re.MULTILINE | re.DOTALL) and now: [alex at lancelot ba]$ python mure.py [('1', 'A description that\ncould be multiple lines\n'), ('2', 'Another description\nalso potentially multiline\n'), ('3', 'But descriptions can also be singleline\n'), ('4', 'although they\nneed not\nbe\n')] [alex at lancelot ba]$ One more detail -- get into the habit of using r'...' notation (raw string literals) for pattern strings of RE's -- or else one day or another some \ escape sequence you didn't know or think about will produce surprising results... Alex From jb at cascade-sys.com Thu Oct 10 00:26:10 2002 From: jb at cascade-sys.com (James J. Besemer) Date: Wed, 09 Oct 2002 21:26:10 -0700 Subject: PEP239 (Rational Numbers) Reference Implementation and new issues References: <20021002221421.GA29958@thyrsus.com> Message-ID: <3DA50162.7030902@cascade-sys.com> Bengt Richter wrote: >Why not a way to introduce special rules for a limited scope? E.g., if there >were a 'scope' keyword that would introduce in indented block where the rules >would apply, and a dictionary defining rules and hooks. Then you could write > > scope rational_rules: > a = b/c # the '/' operator coerces to rational, let's say > blah() # blah's internal rules would not be affected > d = a # would have to act according to enclosing scope > >rational_rules might be {'enter_scope':__enter_rational__, > 'leave_scope':__leave_rational__, > 'exception_hook': __rational_exception__, ...} > >More than one set of rules is conceivable, as a sequence of dictionaries. > > This is an interesting idea but it strikes me as overly "inventive." It would be a much bigger change to Python than simply adding rationals. >You could import stuff (e.g., from __future__) or whatever. > If anything as dramatic as changing division to produce rational results is introduced I think it should apply globally to the entire module, not selectively per scope. And I don't see any need for "special scope rules". In any context where rational numbers already exist, we can define "/" to work naturally. That is any division involving one or more rational arguments would product a rational result. Personally, I don't have a problem saying something like "rat( 3, 4 )" to introduce a new rational. It's consistent with the rest of Python's OO. Alternatively, a "R" suffix to ordinary integers would be pretty clean, e.g., you could say "3/4R". Personally, FWIW, I oppose changing builtins so that int(x)/int(y) produces a rational. For the small minority who would use rationals, one of the above forms should be no hardship. >You'd probably like > > scope classic_division: > assert 3/4==0 > ... > >for some stuff ? > I count myself among the people who did not want integer division to change from it's original definition. However, given that it HAS changed, I don't think it should vary on a per-scope basis. At least not beyond: assert int( 3/4 ) == 0 or assert 3//4 == 0 Regards --jb -- James J. Besemer 503-280-0838 voice 2727 NE Skidmore St. 503-280-0375 fax Portland, Oregon 97211-6557 mailto:jb at cascade-sys.com http://cascade-sys.com From k.robert at gmx.de Wed Oct 9 18:23:08 2002 From: k.robert at gmx.de (Robert) Date: Thu, 10 Oct 2002 00:23:08 +0200 Subject: which outgoing network device/IP is used? Message-ID: <3da4ac9b$0$169$9b622d9e@news.freenet.de> hello, if a computer has more network devices I want to know which one (IP) is used for a outgoing socket connection to a certain remote host. (in order to 'bind/accept' later on that IP for an incoming connection request) found only that socket.gethostbyname_ex(socket.gethostname()) provides a list of IPs robert From tdelaney at avaya.com Mon Oct 14 20:08:55 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Tue, 15 Oct 2002 10:08:55 +1000 Subject: Need help reading damaged file Message-ID: > From: PoulsenL at capanalysis.com [mailto:PoulsenL at capanalysis.com] > > I have about 100+ files that are a dump of old tape from a > database. Most > of the data is good, but it is interspersed with damage that contains > backspace characters and I _believe_ EOF characters. When we > try to import > the data it only imports 1/3 or 1/10, etc of the data > depending on the file. You will need to open the files in binary mode. In text mode, embedded EOF characters will stop processing. In binary mode, it will rely on the size reported by the filesystem. Tim Delaney From peter at engcorp.com Sun Oct 6 12:11:43 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 06 Oct 2002 12:11:43 -0400 Subject: are these operations on list valid? References: Message-ID: <3da060be$1@news.sentex.net> Ken wrote: > "Terry Reedy" wrote in message: >>Start up interactive interpreter and try them out. Best way to learn. > > Can you tell me how to use the interpreter? I am using a stupid and slow way > compiling on telnet in a remote server.... Ken, it sounds like you aren't running Python on your own machine. If you are using telnet to connect to another computer that has Python installed, you should be able simply to type "python" at the command line prompt in your telnet session to the other computer. That would give you the interactive prompt... Alternatively, download Python for Windows from http://www.python.org and install it on your machine. Then change to the c:\python22 directory (using the CD command in DOS... I'm not sure if you know DOS... ask if you need help getting there). At that point, you can again type "python" and you will get the interactive prompt, this time on your own computer. I strongly recommend going through the tutorial (from the same site) when you get this far. See also the FAQ entry at http://www.python.org/cgi-bin/faqw.py?req=show&file=faq08.018.htp for more help. -Peter From rober.fm at terra.es Sun Oct 20 18:31:41 2002 From: rober.fm at terra.es (Roberto Ferreras) Date: Mon, 21 Oct 2002 00:31:41 +0200 Subject: Tkinter, problem when using 2 scrollbars Message-ID: First, it's my first program with Tkinter ... Ok, I have a Listbox with two Scrollbars around it. But they "overlap" at the bottom right corner. One is a bit larger than the other, ie, the verticall scrollbar goes from the top of the Listbox to the bottom of the horizontal Scrollbar. How can I avoid that? How can I put an empty square so the vertical Sb has the height of the Lb and the horizontal Sb the width of the Lb? Thanks. From nospam at eurologic.com Wed Oct 9 05:30:38 2002 From: nospam at eurologic.com (Pat Knight) Date: 09 Oct 2002 10:30:38 +0100 Subject: SimpleXMLRPCServer Releasing Ports References: Message-ID: In Python 2.2 (I haven't checked earlier releases), the base class for SimpleXMLRPCServer, SocketServer.TCPServer has an attribute allow_reuse_address. If you set this to 1 or anything else evaluating true before invoking serve_forever(), the correct socket option SO_REUSEADDR is set for you. You don't need to write any code yourself. -- Cheers, Pat Tel: 0117 930 9621 (Intl: +44-117-930-9621). From phil at river-bank.demon.co.uk Wed Oct 2 03:24:11 2002 From: phil at river-bank.demon.co.uk (Phil Thompson) Date: Wed, 2 Oct 2002 08:24:11 +0100 Subject: How to use: QMenuBar In-Reply-To: References: Message-ID: <200210020824.11631.phil@river-bank.demon.co.uk> On Wednesday 02 October 2002 1:17 am, Hans - G. Normann wrote: > I'm newbie to Python and QT. I can't find a soloution to implement a menu > bar in an existing project (using QT gui). Is there someone, who can give > an easy example, e. g. File / Save / bla bla? Look at the menu.py example included with PyQt. Phil From -$P-W$- at verence.demon.co.uk Sat Oct 19 10:47:23 2002 From: -$P-W$- at verence.demon.co.uk (Paul Wright) Date: 19 Oct 2002 15:47:23 +0100 Subject: Security of Bastion and RExec (was Re: Private variables References: Message-ID: In article , Delaney, Timothy wrote: > From: Timothy J. Wood [mailto:tjw at omnigroup.com] >> >> Is there any way to have truly private instance variables in Python? >> >> My situation is this -- I'm going to be working on a module that >> has C 'native methods'. Several of the Python classes will >> correspond to C structures that will be used in these native >> methods. Additionally, I'll want to allow (along with other >> security measures) to be able to safely run third-party code that >> uses my module. > >If your users must truly be considered as adversaries (i.e. you >*cannot* trust them) then Python is not the correct language to use. I thought that the RExec and Bastion modules could be combined to provide the sort of security the original poster was asking about (which seems to be restricting object attribute access). Is this not so, or are you talking about something else here? I did notice from the RExec HOWTO that it's impossible to prevent denial of service type attacks from resource exhaustion, say. (Unless you're willing to start forking processes). I'd also mention mxProxy at this point as another restricted environment I've come across: -- Paul Wright | http://pobox.com/~pw201 | From lei_pku at hotmail.com Tue Oct 15 02:33:14 2002 From: lei_pku at hotmail.com (hunj) Date: Tue, 15 Oct 2002 14:33:14 +0800 Subject: Problem with DNS resolver library -- pydns References: Message-ID: Could you tell me where to get the pydns package besides sourceforge? Thanks. hunj "VanL" wrote in message news:mailman.1034616412.13524.python-list at python.org... > Hello, > > Has anyone used the pynds resolver libraries? I think I must be missing > something, because I'm just not getting out what I think that I should get. > > I'm trying to get a call getIP(domain, nameserver) that will return the > IP of domain, (or at least what that nameserver thinks the IP is). > > However, I'm instead getting nothing in the answers, just a bunch of > authority records. > > For example: > > import DNS > r = DNS.Request(name='yahoo.com', server='151.164.1.1', qtype='A') > a = r.req() > a.show() > ; <<>> PDG.py 1.0 <<>> yahoo.com A > ;; options: recurs > ;; got answer: > ;; ->>HEADER<<- opcode 0, status NOERROR, id 0 > ;; flags: qr rd; Ques: 1, Ans: 0, Auth: 5, Addit: 5 > ;; QUESTIONS: > ;; yahoo.com, type = A, class = IN > > ;; ANSWERS: > > ;; AUTHORITY RECORDS: > yahoo.com 172800L NS ns1.yahoo.com > yahoo.com 172800L NS ns2.yahoo.com > yahoo.com 172800L NS ns3.yahoo.com > yahoo.com 172800L NS ns4.yahoo.com > yahoo.com 172800L NS ns5.yahoo.com > > ;; ADDITIONAL RECORDS: > ns1.yahoo.com 172800L A 66.218.71.63 > ns2.yahoo.com 172800L A 209.132.1.28 > ns3.yahoo.com 172800L A 217.12.4.104 > ns4.yahoo.com 172800L A 63.250.206.138 > ns5.yahoo.com 172800L A 64.58.77.85 > > ;; Total query time: 48 msec > ;; To SERVER: 151.164.1.1 > ;; WHEN: Mon Oct 14 11:19:37 2002 > > > Notice that the ANSWERS section is empty. Not even the tests work: > test5 returns an IndexError for trying to access answers[0]['data']. > > Any help? Should I try another library? If so, which one? > > Thanks, > > VanL > > From duncan-news at grisby.org Sat Oct 5 12:35:18 2002 From: duncan-news at grisby.org (Duncan Grisby) Date: Sat, 5 Oct 2002 16:35:18 +0000 (UTC) Subject: sys.settrace for all threads References: <8a6ba1da.0210041339.323e22e3@posting.google.com> Message-ID: <1033839146.159500@cache1.news.support.nl> In article <8a6ba1da.0210041339.323e22e3 at posting.google.com>, Richie Hindle wrote: >sys.settrace sets the trace function for the current thread. What I'd >like is a way of setting it for all threads. I've written a code >coverage module, which a friend is trying to run with his omniORBpy >server (Hi Alik!). The server is multithreaded, with each thread >being started by omniORBpy, so there's no convenient place for him to >install the coverage module's trace function for the threads. omniORBpy has a hook you can use specifically for this purpose. Look at the omniORB.addWThreadHook() function, defined in omniORB/__init__.py. Cheers, Duncan. -- -- Duncan Grisby -- -- duncan at grisby.org -- -- http://www.grisby.org -- From dsavitsk at e-coli.net Sun Oct 13 04:17:56 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Sun, 13 Oct 2002 08:17:56 GMT Subject: who can show me an available address to download swig? References: Message-ID: swig.org works for me, but you can try http://swig.sourceforge.net too. -d "hunj" wrote in message news:aob7oq$2mkv$1 at mail.cn99.com... > Hi all, > I could not visit www.swig.org now. > > Best regards! > > Jun Huang > > From Mitch.Chapman at bioreason.com Tue Oct 1 12:25:16 2002 From: Mitch.Chapman at bioreason.com (Mitch Chapman) Date: Tue, 01 Oct 2002 10:25:16 -0600 Subject: Can python be used to debug other languages? References: <4d1e3be8.0209301702.109d2b04@posting.google.com> Message-ID: bumm3rm4n at yahoo.com wrote: > I am doing research in school and I was just wondering if python can > be used to debug other languages such as C++ and java. IF it does, > can anybody give me an info how? This probably isn't what you had in mind, but... I used to do a lot of C/C++ development. For some applications interactive debugging was impractical, and the most popular alternative was to write diagnostic messages to a log file. It was painful to interpret the log file manually. Eventually I realized that, instead of writing human-readable text to the log file, one could write Python statements and then interpret the log file using a Python-based, high-level model of the program. My memory is fading now, but the log might include statements like these: model.startRIP(10127, "/tmp/rip_me.ps") This technique made it possible to detect invalid event sequences, help find unbalanced resource allocation/release, identify slow sections of code (given timestamps like the one above), etc., without manually slogging through all of the messages. Better yet, in many cases it was possible to record a single log file and then re-interpret it many times, refining the Python model on each pass so it could describe problems in greater detail. There are better ways to do this sort of thing, but Python-intelligible log files were a lot of fun. -- Mitch Mitch.Chapman at bioreason.com From carbombo at libero.it Fri Oct 11 05:50:48 2002 From: carbombo at libero.it (CARbomboniere spa) Date: Fri, 11 Oct 2002 09:50:48 GMT Subject: newbie : removing recurring element from lists Message-ID: Hi, How can I remove all occurences of a given value from a list ? E.g. : I have a list like : a = [1,4,5,1,3,1,5,1,1,6] And I want to remove all the 1 values; so the output should be : a = [4,5,3,5,6] I tried the following two ways, neither of which works as expected : ----------------------------------- # first way a = [1,4,5,1,3,1,5,1,1,6] x = 0 for t in a : if t == 1 : del a[x] x = x + 1 print a --------------------------------- # second way a = [1,4,5,1,3,1,5,1,1,6] for t in a : if t == 1 : a.pop(t) print a --------- TIA. Fabrizio From zhangz at in.tum.de Wed Oct 16 09:04:14 2002 From: zhangz at in.tum.de (Zhen Zhang) Date: Wed, 16 Oct 2002 15:04:14 +0200 Subject: question about python extension with c/c++ Message-ID: There are two more things to do before i can use my new extension: compiling and linking it with the Python system. If i want to make my module a permanent part of the Python interpreter, i will have to change the configuration setup and rebuild the interpreter. Luckily, this is very simple on Unix: just place my file (spammodule.c for example) in the Modules/ directory of an unpacked source distribution, add a line to the file Modules/Setup.local describing my file: spam spammodule.o and rebuild the interpreter by running make in the toplevel directory. QUESTION: If my module requires additional headerfiles to include (qstring.h for example) and additional libraries (qtlibraies for example) to link with, please tell me how to do. Any help will be greatly appreciated. From sismex01 at hebmex.com Thu Oct 31 09:54:43 2002 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Thu, 31 Oct 2002 08:54:43 -0600 Subject: Dictionary Enhancement? Message-ID: > From: Rich Harkins [mailto:rich at worldsinfinite.com] > > I was wondering if anyone else had been wanting to enhance Python > dictionaries such that instead of raising KeyError in the case of > errors that another method on the dictionary object, say > __makeitem__ would be called to try to auto-generate an appropriate value. > That __makeitem__ method would then either raise KeyError itself > or return the value to insert into the dictionary and return through > __getitem__. > > I scanned the PEP's but didn't see anything similar. > > Rich > Well, there *is* setdefault(key, default), which is the functional equivalent of what you're describing; if the key doesn't exist, it's created with the default value given, and *then* returned. -gustavo From bloke at ii.net Tue Oct 15 12:35:41 2002 From: bloke at ii.net (Rob Hall) Date: Wed, 16 Oct 2002 00:35:41 +0800 Subject: yielding control Message-ID: <3dac43ad$0$634@echo-01.iinet.net.au> I have a long-running CPU intensive task under W98 and Python 2.2. The trouble is, it hogs the CPU when I am trying to do other things. Even the mouse is sluggish. Is there a way for me to yield control to the OS occasionally in my main loop? Thanks in advance. Rob From daniel.dittmar at sap.com Fri Oct 11 12:46:49 2002 From: daniel.dittmar at sap.com (Daniel Dittmar) Date: Fri, 11 Oct 2002 18:46:49 +0200 Subject: Stringify object reference? References: <3DA6FB65.5D6A4AFE@hotmail.com> Message-ID: Alan Kennedy wrote: >>>> o > > ^^^^^^^^^^ > > But being able to get at this number depends on the __repr__ and > __str__ method implementations for the class in question. You're looking for the id () builtin. Daniel From kokohh at hotmail.com Mon Oct 21 18:36:36 2002 From: kokohh at hotmail.com (koko) Date: Mon, 21 Oct 2002 22:36:36 GMT Subject: how to user handle_data() to extract text from a html file Message-ID: I am haveing some trouble for extract text from a html file. example import htmllib, urllib, formatter class webParser(htmllib.HTMLParser): def __init__(self, base): htmllib.HTMLParser.__init__(self, formatter.NullFormatter()) self.BaseURL = base def handle_data(self,text): htmllib.HTMLParser.handle_data(self,text) url="http://www.uchicago.edu" u=urllib.urlopen(url) urlread=u.read() print urlread # but how can I ouput the content of the html link From max at alcyone.com Sat Oct 5 18:33:37 2002 From: max at alcyone.com (Erik Max Francis) Date: Sat, 05 Oct 2002 15:33:37 -0700 Subject: Which Linux distribution References: Message-ID: <3D9F68C1.AF711693@alcyone.com> Mark McEahern wrote: > > I don't understand what your problem is since you > > can install different versions of Python into distinct > > locations. I run at least four or five different Python > > versions under RH 7.3 without any problems. The key > > to your success is to compile Python on your own and > > use the configure --prefix=.... > > Doesn't `make altinstall` do the trick? make altinstall doesn't overwrite the main `python' binary. The --prefix configure option puts the installation under an entirely different hierarchy. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ There's a reason why we / Keep chasing morning \__/ Sandra St. Victor Physics reference / http://www.alcyone.com/max/reference/physics/ A physics reference. From bokr at oz.net Thu Oct 17 19:30:37 2002 From: bokr at oz.net (Bengt Richter) Date: 17 Oct 2002 23:30:37 GMT Subject: Bug in RE's? References: <886c5e4b.0210170849.3d2c61d@posting.google.com> Message-ID: On 17 Oct 2002 09:49:13 -0700, robin.siebler at corp.palm.com (Robin Siebler) wrote: >I have a list of words that I need to search for in a large number of >files. I decided to put the patterns into one huge string and make an >RE out of it. However, at a certain point the RE stops working. By >this, I mean that the findall method does not return any matches for a >line that contain matches. If I recompile the RE, it works fine. the >RE always stops working in the same place and it always starts working >again in the same place. I have no idea why. Has anyone ever seen >this? If this is a bug, where would I report it? I wonder if it is related to the 65535 problem seen before. That particular magic value in a repeat x{65535} is apparently equivalent to x*: >>> import re >>> rxo = re.compile(r'xy{65535}(z+)') >>> rxo.findall('x'+'y'*66000+'z'*5) ['zzzzz'] >>> rxo = re.compile(r'xy{65534}(z+)') >>> rxo.findall('x'+'y'*66000+'z'*5) [] It seems to be storing string lengths modulo 2**16: >>> for i in range(65536-8,65536+8): ... rxo = re.compile(r'xy{%d}(z+)'% i) ... print '%6d: %s' % (i, rxo.findall('x'+'y'*i+'z'*5)), ... print ' -- vs %6d: %s' % (i%65536, rxo.findall('x'+'y'*(i%65536)+'z'*5)) ... 65528: ['zzzzz'] -- vs 65528: ['zzzzz'] 65529: ['zzzzz'] -- vs 65529: ['zzzzz'] 65530: ['zzzzz'] -- vs 65530: ['zzzzz'] 65531: ['zzzzz'] -- vs 65531: ['zzzzz'] 65532: ['zzzzz'] -- vs 65532: ['zzzzz'] 65533: ['zzzzz'] -- vs 65533: ['zzzzz'] 65534: ['zzzzz'] -- vs 65534: ['zzzzz'] 65535: ['zzzzz'] -- vs 65535: ['zzzzz'] 65536: [] -- vs 0: ['zzzzz'] 65537: [] -- vs 1: ['zzzzz'] 65538: [] -- vs 2: ['zzzzz'] 65539: [] -- vs 3: ['zzzzz'] 65540: [] -- vs 4: ['zzzzz'] 65541: [] -- vs 5: ['zzzzz'] 65542: [] -- vs 6: ['zzzzz'] 65543: [] -- vs 7: ['zzzzz'] Regards, Bengt Richter From spam at melkor.dnp.fmph.uniba.sk Thu Oct 10 06:23:05 2002 From: spam at melkor.dnp.fmph.uniba.sk (Radovan Garabik) Date: Thu, 10 Oct 2002 12:23:05 +0200 Subject: encoding python scripts References: <291p9.17755$ZO1.822767@news20.bellglobal.com> <8a6ba1da.0210100024.1d937392@posting.google.com> Message-ID: <911g7-fuf.ln1@atlas15.dnp.fmph.uniba.sk> Richie Hindle wrote: : Hi Rick, :> I was wondering what approaches python developers :> have taken to encode and thus protect their commercial applications? : I believe Freeze is good enough. It compiles your Python to bytecode, : creates a C module which defines the bytecode as a big char array, : then links that C module with the Python interpreter. It's possible : to hack the bytecode out again and Decompyle it, but it's not trivial. And you can always UPX the resulting binary to make it even more obfuscated. -- ----------------------------------------------------------- | Radovan Garab?k http://melkor.dnp.fmph.uniba.sk/~garabik | | __..--^^^--..__ garabik @ fmph . uniba . sk | ----------------------------------------------------------- Antivirus alert: file .signature infected by signature virus. Hi! I'm a signature virus! Copy me into your signature file to help me spread! From sismex01 at hebmex.com Fri Oct 4 16:24:38 2002 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Fri, 4 Oct 2002 15:24:38 -0500 Subject: making a class return None from __init__ Message-ID: > From: Rajarshi Guha [mailto:rajarshi at presidency.com] > > Hi, > I have a class which makes some basic error checks in the __init__ > function. Ideally, if the parameters passed to the __init__ > function fail > the checks I would like to return a None. But this does'nt seem to > happen: > > class Graph: > > def __init__(self,v): > if SOME_TEST: > return None > > However when I test it out as: > > g = Graph(v) > print g > > (where v will fail) I always get <__main__.Graph instance at 0xXXXXXX> > Is there any way to make the constructor return a None object? > > Thanks, > Hmmm... I believe you have a simple misunderstanding; whatever value __init__() would return is irretrievably lost (ok, enough drama), because __init__() is not called to *create* the object, but to *initialize* it, the object is already allocated by the time __init__() is called. What you *can* do is raise an exception, in which case the assignment is aborted. Good luck. -gustavo From lars at gustaebel.de Wed Oct 23 17:14:28 2002 From: lars at gustaebel.de (Lars Gustaebel) Date: Wed, 23 Oct 2002 23:14:28 +0200 Subject: ANN: tarfile 0.6 released Message-ID: I'm proud to announce the 0.6 release of tarfile. tarfile is a python module for reading and writing tar archives. The 0.6 release has some important bug fixes and introduces the support for bzip2 compression and tape devices. For users of tarfile versions below 0.6, it is highly recommended to update. Features list: * platform independent. * creates POSIX compliant tar archives, GNU tar archives on demand. * support for gzip and bzip2 compressed archives. (bzip2 compression requires the bz2 module version 1.1) * support for tape devices. * support for the most common GNU tar extensions. * support for files, directories, hardlinks, symbolic links, fifos and character and block devices. * optional zipfile compatible class interface. * comprehensive documentation and a unittest. * BSD-style license. tarfile is available here: http://www.gustaebel.de/lars/tarfile/ Thank you. -- Lars Gust?bel lars at gustaebel.de From mongo57a at comcast.net Wed Oct 2 23:28:48 2002 From: mongo57a at comcast.net (andy surany) Date: Wed, 02 Oct 2002 23:28:48 -0400 Subject: string.join question Message-ID: <003c01c26a8c$fd0f4fc0$2502a8c0@emily.ewndsr01.nj.comcast.net> I'm accessing MySQL from Python. This is for an insert statement which looks like this: values = [input1, input2] # input values are derived from askstring, ex: input1 = aaa, input =bbb sqlcmd = sql.Insert_Cmd (tables, columns, values) ----------------------------------------------------------------------- def Insert_Cmd(self,tables,fields,values): insert_str = 'INSERT INTO %s ( %s ) VALUES ( %s )' % (string.join(tables,','),string.join(fields,','),string.join(values,',')) This yields: INSERT INTO tablename (column1,column2) VALUES (aaa,bbb) What I need is: INSERT INTO tablename (column1,column2) VALUES ('aaa','bbb') Regards, Andy -----Original Message----- From: Michal Wallace To: mongo57a at comcast.net Cc: python-list at python.org Date: Wednesday, October 02, 2002 9:54 PM Subject: Re: string.join question >On Thu, 3 Oct 2002 mongo57a at comcast.net wrote: > >> Thanks - it "kind of" works - but not quite. So now there is a part 2 of the >> question: >> >> value = 'aaa' >> a = string.join(string.join(["'", value,"'"],''),',') >> >> This should yield (what I want.....): 'aaa', >> >> Instead it yields: ',a,a,a,' >> >> ??????????????????????? Looks crazy to me...... > >No, it's right, because join takes a sequence. Your "aaa" >string is a sequence of characters. :) > >What are you really trying to do? :) > >Cheers, > >- Michal http://www.sabren.net/ sabren at manifestation.com >------------------------------------------------------------ >Switch to Cornerhost! http://www.cornerhost.com/ > Low Priced, Reliable Blog Hosting, With a Human Touch. :) >------------------------------------------------------------ > From nas at python.ca Thu Oct 10 19:21:00 2002 From: nas at python.ca (Neil Schemenauer) Date: Thu, 10 Oct 2002 16:21:00 -0700 Subject: off topic -- spam assassin In-Reply-To: <20021010210541.GB16228@unpythonic.net> References: <200209261407.g8QE76Wo028975@ratthing-b246.strakt.com> <20021010210541.GB16228@unpythonic.net> Message-ID: <20021010232100.GA21257@glacier.arctrix.com> Jeff Epler: > "Astroturfing" (fake praise for a product) is one example that is > happening today. And it's not just online: http://cbc.ca/stories/2002/07/31/Consumers/cell_market020731 The world is a crazy place. Neil From mongo57a at comcast.net Fri Oct 4 22:22:05 2002 From: mongo57a at comcast.net (mongo57a at comcast.net) Date: Sat, 5 Oct 2002 02:22:05 GMT Subject: What a mess! References: <3d9e2b8f$1_8@goliath.newsgroups.com> Message-ID: <3d9e3b69_8@goliath.newsgroups.com> Thanks - but I only have python1.5 directory in /usr/lib and it has no link. -----------== Posted via Newsfeed.Com - Uncensored Usenet News ==---------- http://www.newsfeed.com The #1 Newsgroup Service in the World! -----= Over 100,000 Newsgroups - Unlimited Fast Downloads - 19 Servers =----- From bokr at oz.net Tue Oct 15 19:09:06 2002 From: bokr at oz.net (Bengt Richter) Date: 15 Oct 2002 23:09:06 GMT Subject: Python pattern repository References: Message-ID: On Tue, 15 Oct 2002 18:33:13 GMT, Robin Munn wrote: >It's been a couple of days since Holger Krekel's post to the "Buffering >control in python?" thread and I haven't seen anyone start up a thread >on this subject, so I'm starting one. I'd also like to see this happen. >I don't have server space to contribute, but I could help with coding, >administration, etc. > >Holger's original post is duplicated below. > >>From: holger krekel >>Newsgroups: comp.lang.python >>Subject: Re: Buffering control in python? >>Date: Sun, 13 Oct 2002 10:31:08 +0200 >> >>Hi Bengt, >> >>Bengt Richter wrote: >>> ... >>> >>> >Yip, proxying is a nice pattern especially with python. >>> > >>> Is there a Python pattern repository somewhere? >> >>No that i know off. The closest is the aspn-cookbook. >> >>Heck, I can't believe it. >> >>We still don't have a useful repository for all >>the nice snippets, recipes and patterns posted and >>discussed everywhere. Although there is plenty of nice >>web-software, mailing lists and whatnot written in python. >>Sometimes people say that we have a great standard lib >>aka "batteries included". True, but i don't think that's >>enough. E.g. >> >>1) i have figured out two screens of code >> to use the Spread-module for basic things. >> Is there a generic place to publish this example >> so that others can find it, use it, discuss it, >> enhance it? >> >>2) i have a nice filename class which has all the os.path >> methods and filtering walks and and and. It needs some >> work but if people use it i would definitely enhance it. >> Now am i supposed to setup a sourceforge project for it? >> No, thanks. >> >>3) i have done a new introspecting rlcompleter ... >> >>4) i need a small class that ... >> >>hopefully, we as a community will finally come up with a >>hybrid web/mail approach (aka roundup) to serve these needs. >>I am definitely interested to code, implement/design concepts >>and offer server-space/cvs for it. >> >>sorry, but i couldn't help it :-) >> >>regards, >> >> holger > > >-- >Robin Munn >rmunn at pobox.com ========================================== The fact that there is so much that can be found via Google (which deserves some kind of Nobel Prize for increasing the planet's aggregate IQ several notches, IMO) means that there is a kind of distributed repository already. It just isn't optimally indexed and organized for retrieval of python code and info. But my thought was that we could leverage Google and newsgroups etc. to improve on the retrieval, rather than trying to concentrate material in various specialized locations such as Parnassus and the cookbook (which are great, don't get me wrong). Introducing PyPAN: Python Pervasive Archive Network ;-) Here's the concept: If you want to include your code snippet in the PyPAN, post it embedded in a document that Google will see. You embed it for easy extraction by putting a PyPAN expression in the first and last (+/- 1, discussed later[1]) lines of your snippet, e.g., # ++PyPAN++ mySnippet.py /clp/forcomment/ -- minimal PyPan snippet def mySnippet(): print 'Hello PyPAN!' # --PyPAN-- I think Google would find '++PyPan++' and show an interesting list. The "/clp/forcomment/" part of the expression is optional, but the intent is to express the location of mySnippet.py in a classification hierarchy, to aid in searching, to limit hits to particular topics etc. mySnippet.py is a recommended file name, and comes first after the '++PyPAN++' tag. The classification path is also for optional use as an actual directory path which can be rooted anywhere convenient for the user (e.g., ~/PyPAN or C:\pywk\PyPan etc.) and thereby support automatic extraction/downloading/placement from e.g., newsgroup archives, disk files, etc. One common usage would be to see a PyPAN snippet in a post -- like the above in this post. To make it available to the extraction tool as a file, I wrote a little program [2] called getclip.exe which simply gets the text from the windows clipboard and writes it to stdout. This makes the clipboard visible as a file object using os.popen('getclip') -- which you can pass to anything that wants to read a file. (getclip is also handy outside of Python, since you can easily pipe the output or redirect it to a file, without having to go to an editor an pasting and saving-as. Instead you just type getclip>theFile.txt). The intent is not to require you to select the exact lines, but just do a select-all, copy or whatever is easy. Then getclip will make all that available to the actual snippet extractor, which can put it in particular directories, etc. I am putting together a PyPAN.py module to provide convenient methods for retrieving PyPAN snippets from clipboard, files, or urls, etc. by regex pattern matches, but it's not finished. It will be runnable from the command line or importable for programmatic use. There will be options for file placement similar to winzip extraction. I.e., you can ignore paths and put everything in a specified directory, or you can root the paths where you like etc. I guess if there is no interest in PyPAN, I may only be able to retrieve my own snippets ;-) In any case, I would be interested in hearing of any standard hierarchy for classifying software. Is there real librarian in the house? --------------- [1] Variations on the PyPAN tags: (Note that PyPAN will search based on space-delimited tags, therefore quoting them as in the following makes them safe against inadvertently interfering with searching for an actual snippet like the (not quite) minimal one above). '++PyPAN++' => start with current line '++PyPAN++-' => start with previous line '++PyPAN+++' => start with next line '++PyPAN--' => reserved for future expressions within a snippet '--PyPAN--' => end with current line '--PyPAN---' => end with previous line '--PyPAN--+' => end with next line --------------- [2] /* ++PyPAN++ getclip.c -- get and write win32 clipboard text to stdout */ /* ** To compile with msvc++60 at command line use ** cl getclip.c /link /defaultlib:user32 */ #include #include #include int main (){ HANDLE hClipData; /* handle to clip data */ LPSTR lpClipData; /* pointer to clip data */ if (!OpenClipboard(NULL)) return 0; /* NULL <=> current task */ /* get text from the clipboard */ if( (hClipData = GetClipboardData(CF_TEXT)) && (lpClipData = GlobalLock(hClipData)) ){ write(1, lpClipData, strlen(lpClipData)); /*text string to stdout */ GlobalUnlock(hClipData); CloseClipboard(); return 0; } else { CloseClipboard(); return 1; } } /* --PyPAN-- */ Note: The cl command assumes environment settings, which you can set by invoking D:\VC98\Bin\VCVARS32.BAT (or whatever your path to it is). BTW, getclip.exe is not big (freshly recompiled): 02-10-15 15:58 24,576 getclip.exe BTW2, ISTM it ought to be possible to make a getclip for unix (maybe talking to gpm or some gui thing?) so that os.popen(getclip) will be a platform-independent thing to write. Further ideas? Regards, Bengt Richter From sholden at holdenweb.com Mon Oct 7 10:30:08 2002 From: sholden at holdenweb.com (Steve Holden) Date: Mon, 7 Oct 2002 10:30:08 -0400 Subject: String help References: <3DA18C4C.1050705@Linux.ie> Message-ID: <2Zgo9.157$cG.11@fe04> "CheapSkate" wrote ... > and that will give me?? > aaa, bbb or ccc? > [P?draig's suggestion ] As with many suggestions you will receive in response to comp.lang.python questions, the easiest thing is to try running them in an interactive interpreter session, as follows... >>> "aaa,bbb,ccc".split(",") ['aaa', 'bbb', 'ccc'] >>> As you can see, the split() function returns a list comprising the substrings around the separator (which was a comma in this case). If you want a particular substring you should subscript the resulting list, e.g.: >>> r = "aaa,bbb,ccc".split(",") >>> r[1] 'bbb' >>> Hope this helps. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- From thephoenix235 at gmx.net Mon Oct 21 00:57:37 2002 From: thephoenix235 at gmx.net (thephoenix235 at gmx.net) Date: Mon, 21 Oct 2002 06:57:37 +0200 (MEST) Subject: variable refences for nested functions References: <001601c278bc$f6d47a20$0200a8c0@limstn01.de.comcast.net> Message-ID: <29316.1035176257@www28.gmx.net> A class would be too heavy duty. You're idea works great. I'm doing this now. class Blank: pass def foo (): top = Blank () top.a = 1 def bar(): print top.a top.a=2 bar() print top.a foo() Thanks. > You have the right idea: make enclosing function var mutable. Besides > 'class'ing it (a bit too heavy duty for most purposes, you can also > wrap it as a list. For multiple vars, use a list of appropriate > length. Or use a dict for name instead of positional access. > > Terry J. Reedy -- +++ GMX - Mail, Messaging & more http://www.gmx.net +++ NEU: Mit GMX ins Internet. Rund um die Uhr f?r 1 ct/ Min. surfen! From BC at energy.com Mon Oct 21 19:02:09 2002 From: BC at energy.com (Bill Carter) Date: Mon, 21 Oct 2002 16:02:09 -0700 Subject: Help with MySQLdb Please References: Message-ID: On Mon, 21 Oct 2002 14:08:09 -0500, John Hunter wrote: >>>>>> "Bill" == Bill Carter writes: > > Bill> That work just like I want it to work, But the same example > Bill> in python returns "errortype" errors. > > Bill> Python: userinput = "123" cursor.execute(" SELECT t.col1, > Bill> t.col2, t.col3 from test as t where t.col2 LIKE '%%%s%%', > Bill> (userinput)) > >I am not sure why the %% quoting is not working in the mysql format >string, and I'm sure someone else can give you guidance there. As a >quick work around, you can just use python's string formatting >capabilities > >q = "SELECT blah,blah1 from test where col LIKE '%%%s%%'" % userinput >cursor.execute(q) > > >as long as the default string conversion of userinput is OK. > >JDH Thanks, That work around did work perfectly BC From phr-n2002b at NOSPAMnightsong.com Wed Oct 2 00:17:48 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 01 Oct 2002 21:17:48 -0700 Subject: Decimal arithmetic, was Re: Python GUI app to impress the boss? References: <7xd6qwqtgz.fsf@ruckus.brouhaha.com> <7xelbcgo56.fsf@ruckus.brouhaha.com> <3D9A5DC4.9030704@tismer.com> Message-ID: <7x4rc5324z.fsf@ruckus.brouhaha.com> "Chris Gonnerman" writes: > What, exactly, is wrong with wanting math involving essentially > decimal monetary amounts to lead to proper decimal rounding? Paul > keeps waving bananas in my face. That's not the problem... since > time immemorial, grocers have had to handle three-for-a-buck sales. > They know how they want the math done; and adding some extra > precision to the intermediate steps solves Paul's complaint. So why > does he keep complaining? I'm told that a certain rounding method might not always produce the same answer as doing it the "right" way. So I asked for a deterministic algorithm for finding the "right" answer in order to compare the results. So far I haven't gotten that algorithm. From nika at kassube.de Sat Oct 5 07:56:41 2002 From: nika at kassube.de (Nils Kassube) Date: Sat, 05 Oct 2002 13:56:41 +0200 Subject: Which Linux distribution References: <814a0eba.0210050348.452ed9ab@posting.google.com> Message-ID: <81heg1gkue.fsf@darwin.lan.kassube.de> jgresula at seznam.cz (Jaroslav Gresula) writes: > What is your experience? What distribution would you recommend to me? > My primary requirement on the distrubution is to have a nice Pyton > environment with easy maintenance of multiple python versions. Debian GNU/Linux http://www.debian.org You will never look back. From oliphant at ee.byu.edu Tue Oct 15 20:07:09 2002 From: oliphant at ee.byu.edu (Travis Oliphant) Date: Tue, 15 Oct 2002 18:07:09 -0600 Subject: Numeric: fromfunction() performance In-Reply-To: <20021015095754.GB850@jsaul.de> References: <20021015095754.GB850@jsaul.de> Message-ID: > Hi there, > > I have a code in which an array is created 'on the fly' using > Numeric's fromfunction() command: > > import Numeric > > x1,x2,nf = 1.08E-8, 6.28E-3, 100000 > q = Numeric.fromfunction (lambda i,k: - x1*i*i - 1j*i*x2 , (nf,1)) > q.shape = (nf,) # make it a one-dimensional array (arhhh) > q = Numeric.exp(q) > My experience is that fromfunction is rarely needed. The usual way I build up evaluations like this is to create an array of indexes like this i = Numeric.arange(0,nf) then use it to do the calculation q = Numeric.exp(-x1*i*i - 1j*i*x2) If I understand your code, correctly, then this should reproduce what you want and be very fast. > And, is there a way to avoid that 'shape' statement? > fromfunction() apparently refuses to produce a one-dimensional > array of length nf, I was not aware of this fromfunction limitation. I will look into it. > > What I actually want is a (quicker) construct corresponding to > > for i in range(0, nf): > q[i] = cmath.exp(-x1*i*i -1j*i*x2) > i = Numeric.arange(0,nf) q = Numeric.exp(-x1*i*i-1j*i*x2) > Which is much too slow. > > Gru?, jsaul > Best, -Travis -- Travis Oliphant Assistant Professor 459 CB Electrical and Computer Engineering Brigham Young University Provo, UT 84602 Tel: (801) 422-3108 oliphant.travis at ieee.org From jtk at yahoo.com Thu Oct 31 12:37:25 2002 From: jtk at yahoo.com (Jeff Kowalczyk) Date: Thu, 31 Oct 2002 12:37:25 -0500 Subject: Regular exp matching delimited string excepting trailing delimiters? Message-ID: Can anyone suggest a reg exp (using re) that will match the entirety of a delimited string of values, omitting zero or more delimiters at the end of the string? For example: from 'A,B,C,123,D,E,,,,,,' with delimiter ',' match 'A,B,C,123,D,E' I have (,*\Z) to match the trailing delimiters for removal with string slicing, but I'd prefer to directly match the text to keep, or match both keep and discard as groups. What would be the syntax for an omission like that? Thanks. From usenet at techmx.com Wed Oct 9 12:39:23 2002 From: usenet at techmx.com (Daniel Harik) Date: Wed, 09 Oct 2002 18:39:23 +0200 Subject: mod_python problem :-( Message-ID: <3da44da7_1@news.estpak.ee> Hello I've installed everything according to manual, compiled via apache apsx,a dn added LoadModule, apache loads ok and show correct signature, but when i try to run simple script from mod_perl tutorial (from doc-html dir), i get floowing output: Mod_python error: "PythonHandler welcome_test" Traceback (most recent call last): File "/usr/lib/python2.2/site-packages/mod_python/apache.py", line 181, in Dispatch module = import_module(module_name, _req) File "/usr/lib/python2.2/site-packages/mod_python/apache.py", line 332, in import_module f, p, d = imp.find_module(parts[i], path) ImportError: No module named welcome_test Thank you very much in advance. From max at alcyone.com Wed Oct 16 23:04:31 2002 From: max at alcyone.com (Erik Max Francis) Date: Wed, 16 Oct 2002 20:04:31 -0700 Subject: Question about output... References: Message-ID: <3DAE28BF.74E561D7@alcyone.com> Tony Warmath wrote: > I'm a C++ programmer and I'm trying to pick up on Python, so I've > starting out making the same programs I have in college in C++ except > coding > them in Python, and I'm already stumped. I'm trying to produce the > Python > equivalent of this statement in C++: > > cout << "The average of " << firstInt << " and " << secondInt << " is > " << > average << endl; > > using variables and strings in one line of output. I've seen some FAQs > but > didn't like the way they said do them, i.e. assigning a variable to > the > whole string. What's the Python equivalent to that statement to get me > on my > way. Thanx! As other people have pointed out, something as simple as print "The average of", first, "and", second, "is", average or print "The average of %d and %d is %d" % (first, second, average) One of the primary motivations for iostreams in C++ vs. stdio is that stdio (printf, etc.) does not support polymorphism, and that's the motivation for having the << stream insertion operator (the reason for it being an operator is so that it's easily chained together like you used above). In Python this motivation simply doesn't exist, since printing an object automatically calls str on it (a function which converts it to a string, and which can be overridden with __str__ methods), so right out of the gate Python's printing facilities do not suffer from the limitations of stdio. You could, of course, write your own iostream-like class wrapper so that you can continue to use << as an insertion operator; it would in fact be quite straightforward, even if one wanted to support manipulators: ... snip ... import sys class IOManipulator: def __init__(self, function=None): self.function = function def do(self, output): self.function(output) class OStream: def __init__(self, output=None): if output is None: output = sys.stdout self.output = output def __lshift__(self, thing): if isinstance(thing, IOManipulator): thing.do(self.output) else: self.output.write(str(thing)) return self def main(): endl = IOManipulator(lambda s: (s.write('\n'), s.flush())) cout = OStream() cout << "The average of " << 1 << " and " << 3 << " is " << (1 + 3)/2 << endl if __name__ == '__main__': main() -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ Be able to be alone. Lose not the advantage of solitude. \__/ Sir Thomas Browne REALpolitik / http://www.realpolitik.com/ Get your own customized newsfeed online in realtime ... for free! From llchen223 at hotmail.com Wed Oct 16 16:47:56 2002 From: llchen223 at hotmail.com (Lei Chen) Date: 16 Oct 2002 13:47:56 -0700 Subject: classes question! References: <2dfzv6y2g4.fsf@synapse.hut.fi> Message-ID: Hello! What is the error message? I can only guess that the error is coming from attempts to add a number to an array returned by RandomArray.random(shape=[])... Karthikesh Raju wrote in message news:<2dfzv6y2g4.fsf at synapse.hut.fi>... > Hi, > > i just started to write a class, when i was struck: > > i did something like: > > > import Numeric > import RandomArray > > class source: > def __init__(self, k=1,n=1,type='uniform'): > self.k = k > self.n = n > self.type = type > if type == 'uniform': > self.data = RandomArray.random([K,N]) > > Now i want to do __add__ overloading and the function should return an > another source > > i did: > > def__add__(self, other): > return source(self.data + other) > > i keep getting errors when i try x+5; x is an object of type source. > i want to be able to implement > > x+5 > x+y (x,y are of type sources) > > and other non source types should be converted to source types. > > Any help is great, > > thankx in advance, > karthik > > -- > > ----------------------------------------------------------------------- > Karthikesh Raju, email: karthik at james.hut.fi > Researcher, http://www.cis.hut.fi/karthik > Helsinki University of Technology, Tel: +358-9-451 5389 > Laboratory of Comp. & Info. Sc., Fax: +358-9-451 3277 > Department of Computer Sc., > P.O Box 5400, FIN 02015 HUT, > Espoo, FINLAND > ----------------------------------------------------------------------- From dsavitsk at e-coli.net Thu Oct 3 12:19:34 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Thu, 03 Oct 2002 16:19:34 GMT Subject: ASP and ADO AGAIN! References: Message-ID: "Mark Ainsworth" wrote in message news:mailman.1033655766.31394.python-list at python.org... * * * > objEquip = Server.CreateObject("ADODB.RecordSet") > objEquip.Open("Select * from Equipment", objCalib) > stDate = objEquip("dateinfo").value > > This gets the correct information, and it prints ok. > > If I now do: > > StString = "date %s" % stDate > I get an empty string. Or > > StString = "date " + stDate > I get an error message telling me it can't concenate string and time > objects. But if stDate is a time object, why does > > IdValue = stDate.ctime() > Tell me that ctime() isn't an method associated with the object because > StDate = time > LdValue = stDate.ctime() > Does work! > > Anyway, what exactly is returned for a date/time object from the ADO > libraries? I can do anything I want with strings and numbers. It's just date > and time values that are confusing me. I need to convert the info to find > out which data value was stored before a predetermined date. > > Any help would be greatly appreciated. have you tried Format? >>> x = r.Fields.Item(1).Value >>> x